diff --git a/src/main/java/org/lwjglx/BufferChecks.java b/src/main/java/org/lwjglx/BufferChecks.java new file mode 100644 index 0000000..828fd4d --- /dev/null +++ b/src/main/java/org/lwjglx/BufferChecks.java @@ -0,0 +1,286 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +import java.nio.*; + +/** + *

A class to check buffer boundaries in general. If there is unsufficient space + * in the buffer when the call is made then a buffer overflow would otherwise + * occur and cause unexpected behaviour, a crash, or worse, a security risk. + * + * Internal class, don't use. + *

+ * @author cix_foo + * @author elias_naur + * @version $Revision$ + * $Id$ + */ +public class BufferChecks { + /** Static methods only! */ + private BufferChecks() { + } + + /** + * Helper methods to ensure a function pointer is not-null (0) + */ + public static void checkFunctionAddress(long pointer) { + if (LWJGLUtil.CHECKS && pointer == 0) { + throw new IllegalStateException("Function is not supported"); + } + } + + /** + * Helper methods to ensure a ByteBuffer is null-terminated + */ + public static void checkNullTerminated(ByteBuffer buf) { + if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0) { + throw new IllegalArgumentException("Missing null termination"); + } + } + + public static void checkNullTerminated(ByteBuffer buf, int count) { + if ( LWJGLUtil.CHECKS ) { + int nullFound = 0; + for ( int i = buf.position(); i < buf.limit(); i++ ) { + if ( buf.get(i) == 0 ) + nullFound++; + } + + if ( nullFound < count ) + throw new IllegalArgumentException("Missing null termination"); + } + } + + /** Helper method to ensure an IntBuffer is null-terminated */ + public static void checkNullTerminated(IntBuffer buf) { + if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) { + throw new IllegalArgumentException("Missing null termination"); + } + } + + /** Helper method to ensure a LongBuffer is null-terminated */ + public static void checkNullTerminated(LongBuffer buf) { + if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) { + throw new IllegalArgumentException("Missing null termination"); + } + } + + /** Helper method to ensure a PointerBuffer is null-terminated */ + public static void checkNullTerminated(PointerBuffer buf) { + if ( LWJGLUtil.CHECKS && buf.get(buf.limit() - 1) != 0 ) { + throw new IllegalArgumentException("Missing null termination"); + } + } + + public static void checkNotNull(Object o) { + if ( LWJGLUtil.CHECKS && o == null) + throw new IllegalArgumentException("Null argument"); + } + + /** + * Helper methods to ensure a buffer is direct (and, implicitly, non-null). + */ + public static void checkDirect(ByteBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("ByteBuffer is not direct"); + } + } + + public static void checkDirect(ShortBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("ShortBuffer is not direct"); + } + } + + public static void checkDirect(IntBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("IntBuffer is not direct"); + } + } + + public static void checkDirect(LongBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("LongBuffer is not direct"); + } + } + + public static void checkDirect(FloatBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("FloatBuffer is not direct"); + } + } + + public static void checkDirect(DoubleBuffer buf) { + if ( LWJGLUtil.CHECKS && !buf.isDirect()) { + throw new IllegalArgumentException("DoubleBuffer is not direct"); + } + } + + public static void checkDirect(PointerBuffer buf) { + // NO-OP, PointerBuffer is always direct. + } + + public static void checkArray(Object[] array) { + if ( LWJGLUtil.CHECKS && (array == null || array.length == 0) ) + throw new IllegalArgumentException("Invalid array"); + } + + /** + * This is a separate call to help inline checkBufferSize. + */ + private static void throwBufferSizeException(Buffer buf, int size) { + throw new IllegalArgumentException("Number of remaining buffer elements is " + buf.remaining() + ", must be at least " + size + ". Because at most " + size + " elements can be returned, a buffer with at least " + size + " elements is required, regardless of actual returned element count"); + } + + private static void throwBufferSizeException(PointerBuffer buf, int size) { + throw new IllegalArgumentException("Number of remaining pointer buffer elements is " + buf.remaining() + ", must be at least " + size); + } + + private static void throwArraySizeException(Object[] array, int size) { + throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size); + } + + private static void throwArraySizeException(long[] array, int size) { + throw new IllegalArgumentException("Number of array elements is " + array.length + ", must be at least " + size); + } + + /** + * Helper method to ensure a buffer is big enough to receive data from a + * glGet* operation. + * + * @param buf + * The buffer to check + * @param size + * The minimum buffer size + * @throws IllegalArgumentException + */ + public static void checkBufferSize(Buffer buf, int size) { + if ( LWJGLUtil.CHECKS && buf.remaining() < size) { + throwBufferSizeException(buf, size); + } + } + + /** + * Detects the buffer type and performs the corresponding check + * and also returns the buffer position in bytes. + * + * @param buffer the buffer to check + * @param size the size to check + * + * @return the buffer position in bytes + */ + public static int checkBuffer(final Buffer buffer, final int size) { + final int posShift; + if ( buffer instanceof ByteBuffer ) { + BufferChecks.checkBuffer((ByteBuffer)buffer, size); + posShift = 0; + } else if ( buffer instanceof ShortBuffer ) { + BufferChecks.checkBuffer((ShortBuffer)buffer, size); + posShift = 1; + } else if ( buffer instanceof IntBuffer ) { + BufferChecks.checkBuffer((IntBuffer)buffer, size); + posShift = 2; + } else if ( buffer instanceof LongBuffer ) { + BufferChecks.checkBuffer((LongBuffer)buffer, size); + posShift = 4; + } else if ( buffer instanceof FloatBuffer ) { + BufferChecks.checkBuffer((FloatBuffer)buffer, size); + posShift = 2; + } else if ( buffer instanceof DoubleBuffer ) { + BufferChecks.checkBuffer((DoubleBuffer)buffer, size); + posShift = 4; + } else + throw new IllegalArgumentException("Unsupported Buffer type specified: " + buffer.getClass()); + + return buffer.position() << posShift; + } + + public static void checkBuffer(ByteBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(ShortBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(IntBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(LongBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(FloatBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(DoubleBuffer buf, int size) { + if ( LWJGLUtil.CHECKS ) { + checkBufferSize(buf, size); + checkDirect(buf); + } + } + + public static void checkBuffer(PointerBuffer buf, int size) { + if ( LWJGLUtil.CHECKS && buf.remaining() < size ) { + throwBufferSizeException(buf, size); + } + } + + public static void checkArray(Object[] array, int size) { + if ( LWJGLUtil.CHECKS && array.length < size ) + throwArraySizeException(array, size); + } + + public static void checkArray(long[] array, int size) { + if ( LWJGLUtil.CHECKS && array.length < size ) + throwArraySizeException(array, size); + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/BufferUtils.java b/src/main/java/org/lwjglx/BufferUtils.java new file mode 100644 index 0000000..0fd803d --- /dev/null +++ b/src/main/java/org/lwjglx/BufferUtils.java @@ -0,0 +1,205 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; + +/** + * Some often-used Buffer code for creating native buffers of the appropriate size. + * + * @author $Author: spasi $ + * @version $Revision: 3528 $ + * $Id: BufferUtils.java 3528 2011-05-11 00:12:52Z spasi $ + */ + +public final class BufferUtils { + + /** + * Construct a direct native-ordered bytebuffer with the specified size. + * @param size The size, in bytes + * @return a ByteBuffer + */ + public static ByteBuffer createByteBuffer(int size) { + return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()); + } + + /** + * Construct a direct native-order shortbuffer with the specified number + * of elements. + * @param size The size, in shorts + * @return a ShortBuffer + */ + public static ShortBuffer createShortBuffer(int size) { + return createByteBuffer(size << 1).asShortBuffer(); + } + + /** + * Construct a direct native-order charbuffer with the specified number + * of elements. + * @param size The size, in chars + * @return an CharBuffer + */ + public static CharBuffer createCharBuffer(int size) { + return createByteBuffer(size << 1).asCharBuffer(); + } + + /** + * Construct a direct native-order intbuffer with the specified number + * of elements. + * @param size The size, in ints + * @return an IntBuffer + */ + public static IntBuffer createIntBuffer(int size) { + return createByteBuffer(size << 2).asIntBuffer(); + } + + /** + * Construct a direct native-order longbuffer with the specified number + * of elements. + * @param size The size, in longs + * @return an LongBuffer + */ + public static LongBuffer createLongBuffer(int size) { + return createByteBuffer(size << 3).asLongBuffer(); + } + + /** + * Construct a direct native-order floatbuffer with the specified number + * of elements. + * @param size The size, in floats + * @return a FloatBuffer + */ + public static FloatBuffer createFloatBuffer(int size) { + return createByteBuffer(size << 2).asFloatBuffer(); + } + + /** + * Construct a direct native-order doublebuffer with the specified number + * of elements. + * @param size The size, in floats + * @return a FloatBuffer + */ + public static DoubleBuffer createDoubleBuffer(int size) { + return createByteBuffer(size << 3).asDoubleBuffer(); + } + + /** + * Construct a PointerBuffer with the specified number + * of elements. + * @param size The size, in memory addresses + * @return a PointerBuffer + */ + public static PointerBuffer createPointerBuffer(int size) { + return PointerBuffer.allocateDirect(size); + } + + /** + * @return n, where buffer_element_size=2^n. + */ + public static int getElementSizeExponent(Buffer buf) { + if (buf instanceof ByteBuffer) + return 0; + else if (buf instanceof ShortBuffer || buf instanceof CharBuffer) + return 1; + else if (buf instanceof FloatBuffer || buf instanceof IntBuffer) + return 2; + else if (buf instanceof LongBuffer || buf instanceof DoubleBuffer) + return 3; + else + throw new IllegalStateException("Unsupported buffer type: " + buf); + } + + /** + * A helper function which is used to get the byte offset in an arbitrary buffer + * based on its position + * @return the position of the buffer, in BYTES + */ + public static int getOffset(Buffer buffer) { + return buffer.position() << getElementSizeExponent(buffer); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(ByteBuffer b) { + zeroBuffer0(b, b.position(), b.remaining()); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(ShortBuffer b) { + zeroBuffer0(b, b.position()*2L, b.remaining()*2L); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(CharBuffer b) { + zeroBuffer0(b, b.position()*2L, b.remaining()*2L); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(IntBuffer b) { + zeroBuffer0(b, b.position()*4L, b.remaining()*4L); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(FloatBuffer b) { + zeroBuffer0(b, b.position()*4L, b.remaining()*4L); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(LongBuffer b) { + zeroBuffer0(b, b.position()*8L, b.remaining()*8L); + } + + /** Fill buffer with zeros from position to remaining */ + public static void zeroBuffer(DoubleBuffer b) { + zeroBuffer0(b, b.position()*8L, b.remaining()*8L); + } + + /** Fill buffer with zeros from position to remaining */ + private static native void zeroBuffer0(Buffer b, long off, long size); + + /** + * Returns the memory address of the specified buffer. + * + * @param buffer the buffer + * + * @return the memory address + */ + static native long getBufferAddress(Buffer buffer); + +} diff --git a/src/main/java/org/lwjglx/LWJGLException.java b/src/main/java/org/lwjglx/LWJGLException.java new file mode 100644 index 0000000..5d2c33f --- /dev/null +++ b/src/main/java/org/lwjglx/LWJGLException.java @@ -0,0 +1,79 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +/** + *

+ * This exception is supplied to make exception handling more generic for LWJGL + * specific exceptions + *

+ * + * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +public class LWJGLException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Plain c'tor + */ + public LWJGLException() { + super(); + } + + /** + * Creates a new LWJGLException + * + * @param msg + * String identifier for exception + */ + public LWJGLException(String msg) { + super(msg); + } + + /** + * @param message + * @param cause + */ + public LWJGLException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param cause + */ + public LWJGLException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/org/lwjglx/LWJGLUtil.java b/src/main/java/org/lwjglx/LWJGLUtil.java new file mode 100644 index 0000000..2a90897 --- /dev/null +++ b/src/main/java/org/lwjglx/LWJGLUtil.java @@ -0,0 +1,612 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.*; + +/** + *

+ * Internal library methods + *

+ * + * @author Brian Matzon + * @version $Revision: 3608 $ + * $Id: LWJGLUtil.java 3608 2011-08-10 16:05:46Z spasi $ + */ +public class LWJGLUtil { + public static final int PLATFORM_LINUX = 1; + public static final int PLATFORM_MACOSX = 2; + public static final int PLATFORM_WINDOWS = 3; + public static final String PLATFORM_LINUX_NAME = "linux"; + public static final String PLATFORM_MACOSX_NAME = "macosx"; + public static final String PLATFORM_WINDOWS_NAME = "windows"; + + private static final String LWJGL_ICON_DATA_16x16 = + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\376\377\377\377\302\327\350\377" + + "\164\244\313\377\120\213\275\377\124\216\277\377\206\257\322\377" + + "\347\357\366\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\365\365\365\377\215\217\221\377\166\202\215\377" + + "\175\215\233\377\204\231\252\377\224\267\325\377\072\175\265\377" + + "\110\206\272\377\332\347\361\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\364\370\373\377\234\236\240\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\344\344\344\377\204\255\320\377" + + "\072\175\265\377\133\222\301\377\374\375\376\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\221\266\325\377\137\137\137\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\042\042\042\377\377\377\377\377\350\360\366\377" + + "\071\174\265\377\072\175\265\377\304\330\351\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\306\331\351\377" + + "\201\253\316\377\035\035\035\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\146\146\146\377\377\377\377\377\320\340\355\377" + + "\072\175\265\377\072\175\265\377\215\264\324\377\377\377\377\377" + + "\362\362\362\377\245\245\245\377\337\337\337\377\242\301\334\377" + + "\260\305\326\377\012\012\012\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\250\250\250\377\377\377\377\377\227\272\330\377" + + "\072\175\265\377\072\175\265\377\161\241\312\377\377\377\377\377" + + "\241\241\241\377\000\000\000\377\001\001\001\377\043\043\043\377" + + "\314\314\314\377\320\320\320\377\245\245\245\377\204\204\204\377" + + "\134\134\134\377\357\357\357\377\377\377\377\377\140\226\303\377" + + "\072\175\265\377\072\175\265\377\155\236\310\377\377\377\377\377" + + "\136\136\136\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\317\317\317\377\037\037\037\377\003\003\003\377\053\053\053\377" + + "\154\154\154\377\306\306\306\377\372\374\375\377\236\277\332\377" + + "\167\245\314\377\114\211\274\377\174\250\316\377\377\377\377\377" + + "\033\033\033\377\000\000\000\377\000\000\000\377\027\027\027\377" + + "\326\326\326\377\001\001\001\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\122\122\122\377\345\345\345\377\075\075\075\377" + + "\150\150\150\377\246\246\247\377\332\336\341\377\377\377\377\377" + + "\164\164\164\377\016\016\016\377\000\000\000\377\131\131\131\377" + + "\225\225\225\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\221\221\221\377\233\233\233\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\002\002\002\377\103\103\103\377" + + "\377\377\377\377\356\356\356\377\214\214\214\377\277\277\277\377" + + "\126\126\126\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\323\323\323\377\130\130\130\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\063\063\063\377" + + "\377\377\377\377\377\377\377\377\374\375\376\377\377\377\377\377" + + "\300\300\300\377\100\100\100\377\002\002\002\377\000\000\000\377" + + "\033\033\033\377\373\373\373\377\027\027\027\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\170\170\170\377" + + "\377\377\377\377\377\377\377\377\322\341\356\377\176\251\316\377" + + "\340\352\363\377\377\377\377\377\324\324\324\377\155\155\155\377" + + "\204\204\204\377\323\323\323\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\275\275\275\377" + + "\377\377\377\377\377\377\377\377\376\376\376\377\146\232\305\377" + + "\075\177\266\377\202\254\320\377\344\355\365\377\377\377\377\377" + + "\377\377\377\377\345\345\345\377\055\055\055\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\014\014\014\377\366\366\366\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\342\354\364\377" + + "\115\211\274\377\072\175\265\377\076\200\266\377\207\260\322\377" + + "\347\357\366\377\377\377\377\377\376\376\376\377\274\274\274\377" + + "\117\117\117\377\003\003\003\377\112\112\112\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\353\362\370\377\214\263\324\377\126\220\300\377\120\214\275\377" + + "\167\245\314\377\355\363\370\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\337\337\337\377\346\346\346\377\377\377\377\377"; + + private static final String LWJGL_ICON_DATA_32x32 = + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\372\374\375\377" + + "\313\335\354\377\223\267\326\377\157\240\311\377\134\223\302\377\140\226\303\377\172\247\315\377\254\310\340\377\355\363\370\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\374\375\376\377\265\316\343\377\132\222\301\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\105\205\271\377" + + "\241\301\334\377\374\375\376\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\374\374\374\377\342\352\361\377\270\317\343\377\256\311\340\377" + + "\243\302\334\377\230\272\330\377\214\263\323\377\201\254\317\377\156\237\310\377\075\177\266\377\072\175\265\377\072\175\265\377" + + "\072\175\265\377\162\242\312\377\365\370\373\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\330\330\330\377\061\061\061\377\044\044\044\377\061\061\061\377\100\100\100\377" + + "\122\122\122\377\145\145\145\377\164\164\164\377\217\217\217\377\367\370\370\377\254\310\337\377\073\175\265\377\072\175\265\377" + + "\072\175\265\377\072\175\265\377\171\247\315\377\374\375\376\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\376\376\376\377\150\150\150\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\266\266\266\377\376\376\376\377\206\256\321\377\072\175\265\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\256\312\341\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\323\342\356\377\341\352\362\377\050\050\050\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\002\002\002\377\336\336\336\377\377\377\377\377\365\370\373\377\133\222\301\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\110\206\272\377\364\370\373\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\354\363\370\377\144\231\305\377\327\331\333\377\005\005\005\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\044\044\044\377\376\376\376\377\377\377\377\377\377\377\377\377\300\325\347\377" + + "\071\174\265\377\072\175\265\377\072\175\265\377\072\175\265\377\253\310\340\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\376\377\377\377" + + "\170\246\314\377\173\247\315\377\236\236\236\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\145\145\145\377\377\377\377\377\377\377\377\377\377\377\377\377\342\354\364\377" + + "\067\173\264\377\072\175\265\377\072\175\265\377\072\175\265\377\146\232\305\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\303\327\350\377" + + "\071\175\265\377\262\314\341\377\130\130\130\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\251\251\251\377\377\377\377\377\377\377\377\377\377\377\377\377\274\322\345\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\100\201\267\377\356\364\371\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\372\374\375\377\132\222\301\377" + + "\075\177\266\377\335\345\355\377\034\034\034\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\007\007\007\377\347\347\347\377\377\377\377\377\377\377\377\377\377\377\377\377\205\256\321\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\071\175\265\377\314\336\354\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\376\376\376\377\377\377\377\377\377\377\377\377\377\377\377\377\272\322\345\377\072\175\265\377" + + "\127\220\277\377\320\321\321\377\003\003\003\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\063\063\063\377\375\375\375\377\377\377\377\377\377\377\377\377\373\374\375\377\120\213\275\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\071\175\265\377\261\314\342\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\312\312\312\377\067\067\067\377\141\141\141\377\242\242\242\377\335\335\335\377\344\354\363\377\261\313\341\377" + + "\264\315\342\377\346\346\346\377\043\043\043\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\162\162\162\377\377\377\377\377\377\377\377\377\377\377\377\377\330\345\360\377\072\175\265\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\240\300\333\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\146\146\146\377\000\000\000\377\000\000\000\377\000\000\000\377\006\006\006\377\047\047\047\377\146\146\146\377" + + "\324\324\324\377\377\377\377\377\366\366\366\377\320\320\320\377\227\227\227\377\136\136\136\377\047\047\047\377\004\004\004\377" + + "\000\000\000\377\003\003\003\377\300\300\300\377\377\377\377\377\377\377\377\377\377\377\377\377\242\301\333\377\072\175\265\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\236\277\332\377\377\377\377\377\377\377\377\377" + + "\373\373\373\377\045\045\045\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\134\134\134\377\377\377\377\377\352\352\352\377\217\217\217\377\265\265\265\377\351\351\351\377\375\375\375\377\347\347\347\377" + + "\262\262\262\377\275\275\275\377\376\376\376\377\377\377\377\377\377\377\377\377\377\377\377\377\153\235\307\377\072\175\265\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\241\301\334\377\377\377\377\377\377\377\377\377" + + "\333\333\333\377\003\003\003\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\203\203\203\377\377\377\377\377\137\137\137\377\000\000\000\377\000\000\000\377\013\013\013\377\067\067\067\377\166\166\166\377" + + "\267\267\267\377\360\360\360\377\377\377\377\377\377\377\377\377\377\377\377\377\360\365\371\377\113\210\273\377\075\177\266\377" + + "\071\174\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\262\314\342\377\377\377\377\377\377\377\377\377" + + "\232\232\232\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\305\305\305\377\367\367\367\377\035\035\035\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\007\007\007\377\074\074\074\377\337\337\337\377\377\377\377\377\373\374\375\377\374\375\376\377\363\367\372\377" + + "\314\335\353\377\236\276\332\377\162\241\311\377\114\211\273\377\072\175\265\377\311\334\353\377\377\377\377\377\377\377\377\377" + + "\126\126\126\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\017\017\017\377" + + "\371\371\371\377\321\321\321\377\003\003\003\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\216\216\216\377\377\377\377\377\371\371\371\377\204\204\204\377\160\160\160\377" + + "\260\260\260\377\352\352\352\377\377\377\377\377\371\373\374\377\334\350\362\377\366\371\374\377\377\377\377\377\377\377\377\377" + + "\025\025\025\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\116\116\116\377" + + "\377\377\377\377\221\221\221\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\273\273\273\377\377\377\377\377\236\236\236\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\004\004\004\377\057\057\057\377\160\160\160\377\260\260\260\377\346\346\346\377\376\376\376\377\377\377\377\377" + + "\071\071\071\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\220\220\220\377" + + "\377\377\377\377\115\115\115\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\020\020\020\377\360\360\360\377\377\377\377\377\132\132\132\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\011\011\011\377\062\062\062\377\261\261\261\377" + + "\366\366\366\377\241\241\241\377\065\065\065\377\002\002\002\377\000\000\000\377\000\000\000\377\002\002\002\377\321\321\321\377" + + "\365\365\365\377\023\023\023\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\105\105\105\377\376\376\376\377\370\370\370\377\035\035\035\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\053\053\053\377" + + "\377\377\377\377\377\377\377\377\374\374\374\377\276\276\276\377\120\120\120\377\005\005\005\377\045\045\045\377\371\371\371\377" + + "\302\302\302\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\206\206\206\377\377\377\377\377\322\322\322\377\001\001\001\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\103\103\103\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\376\376\376\377\334\334\334\377\340\340\340\377\377\377\377\377" + + "\225\225\225\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\001\001\001\377\310\310\310\377\377\377\377\377\216\216\216\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\210\210\210\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\337\337\337\377\051\051\051\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\030\030\030\377\365\365\365\377\377\377\377\377\112\112\112\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\317\317\317\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\361\366\372\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\371\371\371\377\265\265\265\377\113\113\113\377\006\006\006\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\122\122\122\377\377\377\377\377\370\370\370\377\020\020\020\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\034\034\034\377\370\370\370\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\206\257\321\377\220\265\325\377\352\361\367\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\333\333\333\377\170\170\170\377\033\033\033\377\000\000\000\377" + + "\000\000\000\377\226\226\226\377\377\377\377\377\306\306\306\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\132\132\132\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\303\330\351\377\072\175\265\377\103\203\270\377" + + "\224\270\326\377\355\363\370\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\364\364\364\377\247\247\247\377" + + "\205\205\205\377\364\364\364\377\377\377\377\377\206\206\206\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\235\235\235\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\372\373\375\377\135\224\302\377\072\175\265\377" + + "\072\175\265\377\106\205\271\377\230\273\330\377\357\364\371\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\233\233\233\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\005\005\005\377\335\335\335\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\305\331\351\377\073\176\266\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\110\206\272\377\236\276\332\377\362\366\372\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\373\373\373\377\216\216\216\377\045\045\045\377\001\001\001\377\000\000\000\377" + + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\054\054\054\377\374\374\374\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\217\265\325\377" + + "\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\112\207\273\377\243\302\334\377\363\367\372\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\372\372\372\377\260\260\260\377\105\105\105\377" + + "\004\004\004\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\156\156\156\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\374\375\376\377" + + "\205\257\321\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\115\211\274\377" + + "\250\305\336\377\366\371\374\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\376\376\376\377" + + "\322\322\322\377\150\150\150\377\016\016\016\377\000\000\000\377\001\001\001\377\270\270\270\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\376\376\377\377\261\313\342\377\114\211\274\377\071\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377\072\175\265\377" + + "\072\175\265\377\115\211\274\377\277\324\347\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\354\354\354\377\223\223\223\377\233\233\233\377\375\375\375\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\363\367\372\377\265\316\343\377\201\254\320\377\145\231\305\377\141\227\304\377\154\236\310\377" + + "\217\265\325\377\305\331\351\377\367\372\374\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" + + "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"; + + /** LWJGL Logo - 16 by 16 pixels */ + public static final ByteBuffer LWJGLIcon16x16 = loadIcon(LWJGL_ICON_DATA_16x16); + + /** LWJGL Logo - 32 by 32 pixels */ + public static final ByteBuffer LWJGLIcon32x32 = loadIcon(LWJGL_ICON_DATA_32x32); + + /** Debug flag. */ + public static final boolean DEBUG = getPrivilegedBoolean("org.lwjgl.util.Debug"); + + public static final boolean CHECKS = !getPrivilegedBoolean("org.lwjgl.util.NoChecks"); + + private static final int PLATFORM; + + static { + final String osName = getPrivilegedProperty("os.name"); + if ( osName.startsWith("Windows") ) + PLATFORM = PLATFORM_WINDOWS; + else if ( osName.startsWith("Linux") || osName.startsWith("FreeBSD") || osName.startsWith("SunOS") || osName.startsWith("Unix") ) + PLATFORM = PLATFORM_LINUX; + else if ( osName.startsWith("Mac OS X") || osName.startsWith("Darwin") ) + PLATFORM = PLATFORM_MACOSX; + else + throw new LinkageError("Unknown platform: " + osName); + } + + private static ByteBuffer loadIcon(String data) { + int len = data.length(); + ByteBuffer bb = BufferUtils.createByteBuffer(len); + for(int i=0 ; i possible_paths = new ArrayList(); + + String classloader_path = getPathFromClassLoader(libname, classloader); + if (classloader_path != null) { + log("getPathFromClassLoader: Path found: " + classloader_path); + possible_paths.add(classloader_path); + } + + for ( String platform_lib_name : platform_lib_names ) { + String lwjgl_classloader_path = getPathFromClassLoader("lwjgl", classloader); + if ( lwjgl_classloader_path != null ) { + log("getPathFromClassLoader: Path found: " + lwjgl_classloader_path); + possible_paths.add(lwjgl_classloader_path.substring(0, lwjgl_classloader_path.lastIndexOf(File.separator)) + + File.separator + platform_lib_name); + } + + // add Installer path + String alternative_path = getPrivilegedProperty("org.lwjgl.librarypath"); + if ( alternative_path != null ) { + possible_paths.add(alternative_path + File.separator + platform_lib_name); + } + + // Add all possible paths from java.library.path + String java_library_path = getPrivilegedProperty("java.library.path"); + + StringTokenizer st = new StringTokenizer(java_library_path, File.pathSeparator); + while ( st.hasMoreTokens() ) { + String path = st.nextToken(); + possible_paths.add(path + File.separator + platform_lib_name); + } + + //add current path + String current_dir = getPrivilegedProperty("user.dir"); + possible_paths.add(current_dir + File.separator + platform_lib_name); + + //add pure library (no path, let OS search) + possible_paths.add(platform_lib_name); + } + + //create needed string array + return possible_paths.toArray(new String[possible_paths.size()]); + } + + static void execPrivileged(final String[] cmd_array) throws Exception { + try { + Process process = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Process run() throws Exception { + return Runtime.getRuntime().exec(cmd_array); + } + }); + // Close unused streams to make sure the child process won't hang + process.getInputStream().close(); + process.getOutputStream().close(); + process.getErrorStream().close(); + } catch (PrivilegedActionException e) { + throw (Exception)e.getCause(); + } + } + + private static String getPrivilegedProperty(final String property_name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(property_name); + } + }); + } + + /** + * Tries to locate named library from the current ClassLoader + * This method exists because native libraries are loaded from native code, and as such + * is exempt from ClassLoader library loading rutines. It therefore always fails. + * We therefore invoke the protected method of the ClassLoader to see if it can + * locate it. + * + * @param libname Name of library to search for + * @param classloader Classloader to use + * @return Absolute path to library if found, otherwise null + */ + private static String getPathFromClassLoader(final String libname, final ClassLoader classloader) { + try { + log("getPathFromClassLoader: searching for: " + libname); + Class c = classloader.getClass(); + while (c != null) { + final Class clazz = c; + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction() { + public String run() throws Exception { + Method findLibrary = clazz.getDeclaredMethod("findLibrary", String.class); + findLibrary.setAccessible(true); + String path = (String)findLibrary.invoke(classloader, libname); + return path; + } + }); + } catch (PrivilegedActionException e) { + log("Failed to locate findLibrary method: " + e.getCause()); + c = c.getSuperclass(); + } + } + } catch (Exception e) { + log("Failure locating " + e + " using classloader:" + e); + } + return null; + } + + /** + * Gets a boolean property as a privileged action. + */ + public static boolean getPrivilegedBoolean(final String property_name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + return Boolean.getBoolean(property_name); + } + }); + } + + /** + * Gets an integer property as a privileged action. + * + * @param property_name the integer property name + * + * @return the property value + */ + public static Integer getPrivilegedInteger(final String property_name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Integer run() { + return Integer.getInteger(property_name); + } + }); + } + + /** + * Gets an integer property as a privileged action. + * + * @param property_name the integer property name + * @param default_val the default value to use if the property is not defined + * + * @return the property value + */ + public static Integer getPrivilegedInteger(final String property_name, final int default_val) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Integer run() { + return Integer.getInteger(property_name, default_val); + } + }); + } + + /** + * Prints the given message to System.err if DEBUG is true. + * + * @param msg Message to print + */ + public static void log(CharSequence msg) { + if (DEBUG) { + System.err.println("[LWJGL] " + msg); + } + } + + /** + * Method to determine if the current system is running a version of + * Mac OS X better than the given version. This is only useful for Mac OS X + * specific code and will not work for any other platform. + */ + public static boolean isMacOSXEqualsOrBetterThan(int major_required, int minor_required) { + String os_version = getPrivilegedProperty("os.version"); + StringTokenizer version_tokenizer = new StringTokenizer(os_version, "."); + int major; + int minor; + try { + String major_str = version_tokenizer.nextToken(); + String minor_str = version_tokenizer.nextToken(); + major = Integer.parseInt(major_str); + minor = Integer.parseInt(minor_str); + } catch (Exception e) { + LWJGLUtil.log("Exception occurred while trying to determine OS version: " + e); + // Best guess, no + return false; + } + return major > major_required || (major == major_required && minor >= minor_required); + } + + /** + * Returns a map of public static final integer fields in the specified classes, to their String representations. + * An optional filter can be specified to only include specific fields. The target map may be null, in which + * case a new map is allocated and returned. + *

+ * This method is useful when debugging to quickly identify values returned from the AL/GL/CL APIs. + * + * @param filter the filter to use (optional) + * @param target the target map (optional) + * @param tokenClasses an array of classes to get tokens from + * + * @return the token map + */ + + public static Map getClassTokens(final TokenFilter filter, final Map target, final Class ... tokenClasses) { + return getClassTokens(filter, target, Arrays.asList(tokenClasses)); + } + + /** + * Returns a map of public static final integer fields in the specified classes, to their String representations. + * An optional filter can be specified to only include specific fields. The target map may be null, in which + * case a new map is allocated and returned. + *

+ * This method is useful when debugging to quickly identify values returned from the AL/GL/CL APIs. + * + * @param filter the filter to use (optional) + * @param target the target map (optional) + * @param tokenClasses the classes to get tokens from + * + * @return the token map + */ + public static Map getClassTokens(final TokenFilter filter, Map target, final Iterable tokenClasses) { + if ( target == null ) + target = new HashMap(); + + final int TOKEN_MODIFIERS = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; + + for ( final Class tokenClass : tokenClasses ) { + for ( final Field field : tokenClass.getDeclaredFields() ) { + // Get only fields. + if ( (field.getModifiers() & TOKEN_MODIFIERS) == TOKEN_MODIFIERS && field.getType() == int.class ) { + try { + final int value = field.getInt(null); + if ( filter != null && !filter.accept(field, value) ) + continue; + + if ( target.containsKey(value) ) // Print colliding tokens in their hex representation. + target.put(value, toHexString(value)); + else + target.put(value, field.getName()); + } catch (IllegalAccessException e) { + // Ignore + } + } + } + } + + return target; + } + + /** + * Returns a string representation of the integer argument as an + * unsigned integer in base 16. The string will be uppercase + * and will have a leading '0x'. + * + * @param value the integer value + * + * @return the hex string representation + */ + public static String toHexString(final int value) { + return "0x" + Integer.toHexString(value).toUpperCase(); + } + + /** Simple interface for Field filtering. */ + public interface TokenFilter { + + /** + * Should return true if the specified Field passes the filter. + * + * @param field the Field to test + * @param value the integer value of the field + * + * @result true if the Field is accepted + */ + boolean accept(Field field, int value); + + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/MemoryUtil.java b/src/main/java/org/lwjglx/MemoryUtil.java new file mode 100644 index 0000000..bcb22e2 --- /dev/null +++ b/src/main/java/org/lwjglx/MemoryUtil.java @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2002-2011 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +import java.lang.reflect.Field; +import java.nio.*; +import java.nio.charset.*; + +/** + * [INTERNAL USE ONLY] + *

+ * This class provides utility methods for passing buffers to JNI API calls. + * + * @author Spasi + */ +public final class MemoryUtil { + + private static final Charset ascii; + private static final Charset utf8; + private static final Charset utf16; + + static { + ascii = Charset.forName("ISO-8859-1"); + utf8 = Charset.forName("UTF-8"); + utf16 = Charset.forName("UTF-16LE"); + } + + private static final Accessor memUtil; + + static { + Accessor util; + try { + // Depends on java.nio.Buffer#address and sun.misc.Unsafe + util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorUnsafe"); + } catch (Exception e0) { + try { + // Depends on java.nio.Buffer#address and sun.reflect.FieldAccessor + util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorReflectFast"); + } catch (Exception e1) { + try { + // Depends on java.nio.Buffer#address + util = new AccessorReflect(); + } catch (Exception e2) { + LWJGLUtil.log("Unsupported JVM detected, this will likely result in low performance. Please inform LWJGL developers."); + util = new AccessorJNI(); + } + } + } + + LWJGLUtil.log("MemoryUtil Accessor: " + util.getClass().getSimpleName()); + memUtil = util; + + /* + BENCHMARK RESULTS - Oracle Server VM: + + Unsafe: 4ns + ReflectFast: 8ns + Reflect: 10ns + JNI: 82ns + + BENCHMARK RESULTS - Oracle Client VM: + + Unsafe: 5ns + ReflectFast: 81ns + Reflect: 85ns + JNI: 87ns + + On non-Oracle VMs, Unsafe should be the fastest implementation as well. In the absence + of Unsafe, performance will depend on how reflection and JNI are implemented. For now + we'll go with what we see on the Oracle VM (that is, we'll prefer reflection over JNI). + */ + } + + private MemoryUtil() { + } + + /** + * Returns the memory address of the specified buffer. [INTERNAL USE ONLY] + * + * @param buffer the buffer + * + * @return the memory address + */ + public static long getAddress0(Buffer buffer) { return memUtil.getAddress(buffer); } + + public static long getAddress0Safe(Buffer buffer) { return buffer == null ? 0L : memUtil.getAddress(buffer); } + + public static long getAddress0(PointerBuffer buffer) { return memUtil.getAddress(buffer.getBuffer()); } + + public static long getAddress0Safe(PointerBuffer buffer) { return buffer == null ? 0L : memUtil.getAddress(buffer.getBuffer()); } + + // --- [ API utilities ] --- + + public static long getAddress(ByteBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(ByteBuffer buffer, int position) { return getAddress0(buffer) + position; } + + public static long getAddress(ShortBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(ShortBuffer buffer, int position) { return getAddress0(buffer) + (position << 1); } + + public static long getAddress(CharBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(CharBuffer buffer, int position) { return getAddress0(buffer) + (position << 1); } + + public static long getAddress(IntBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(IntBuffer buffer, int position) { return getAddress0(buffer) + (position << 2); } + + public static long getAddress(FloatBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(FloatBuffer buffer, int position) { return getAddress0(buffer) + (position << 2); } + + public static long getAddress(LongBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(LongBuffer buffer, int position) { return getAddress0(buffer) + (position << 3); } + + public static long getAddress(DoubleBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(DoubleBuffer buffer, int position) { return getAddress0(buffer) + (position << 3); } + + public static long getAddress(PointerBuffer buffer) { return getAddress(buffer, buffer.position()); } + + public static long getAddress(PointerBuffer buffer, int position) { return getAddress0(buffer) + (position * PointerBuffer.getPointerSize()); } + + // --- [ API utilities - Safe ] --- + + public static long getAddressSafe(ByteBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(ByteBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(ShortBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(ShortBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(CharBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(CharBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(IntBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(IntBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(FloatBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(FloatBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(LongBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(LongBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(DoubleBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(DoubleBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + public static long getAddressSafe(PointerBuffer buffer) { return buffer == null ? 0L : getAddress(buffer); } + + public static long getAddressSafe(PointerBuffer buffer, int position) { return buffer == null ? 0L : getAddress(buffer, position); } + + // --- [ String utilities ] --- + + /** + * Returns a ByteBuffer containing the specified text ASCII encoded and null-terminated. + * If text is null, null is returned. + * + * @param text the text to encode + * + * @return the encoded text or null + * + * @see String#getBytes() + */ + public static ByteBuffer encodeASCII(final CharSequence text) { + return encode(text, ascii); + } + + /** + * Returns a ByteBuffer containing the specified text UTF-8 encoded and null-terminated. + * If text is null, null is returned. + * + * @param text the text to encode + * + * @return the encoded text or null + * + * @see String#getBytes() + */ + public static ByteBuffer encodeUTF8(final CharSequence text) { + return encode(text, utf8); + } + + /** + * Returns a ByteBuffer containing the specified text UTF-16LE encoded and null-terminated. + * If text is null, null is returned. + * + * @param text the text to encode + * + * @return the encoded text + */ + public static ByteBuffer encodeUTF16(final CharSequence text) { + return encode(text, utf16); + } + + /** + * Wraps the specified text in a null-terminated CharBuffer and encodes it using the specified Charset. + * + * @param text the text to encode + * @param charset the charset to use for encoding + * + * @return the encoded text + */ + private static ByteBuffer encode(final CharSequence text, final Charset charset) { + if ( text == null ) + return null; + + return encode(CharBuffer.wrap(new CharSequenceNT(text)), charset); + } + + /** + * A {@link CharsetEncoder#encode(java.nio.CharBuffer)} implementation that uses {@link BufferUtils#createByteBuffer(int)} + * instead of {@link ByteBuffer#allocate(int)}. + * + * @see CharsetEncoder#encode(java.nio.CharBuffer) + */ + private static ByteBuffer encode(final CharBuffer in, final Charset charset) { + final CharsetEncoder encoder = charset.newEncoder(); // encoders are not thread-safe, create a new one on every call + + int n = (int)(in.remaining() * encoder.averageBytesPerChar()); + ByteBuffer out = BufferUtils.createByteBuffer(n); + + if ( n == 0 && in.remaining() == 0 ) + return out; + + encoder.reset(); + while ( true ) { + CoderResult cr = in.hasRemaining() ? encoder.encode(in, out, true) : CoderResult.UNDERFLOW; + if ( cr.isUnderflow() ) + cr = encoder.flush(out); + + if ( cr.isUnderflow() ) + break; + + if ( cr.isOverflow() ) { + n = 2 * n + 1; // Ensure progress; n might be 0! + ByteBuffer o = BufferUtils.createByteBuffer(n); + out.flip(); + o.put(out); + out = o; + continue; + } + + try { + cr.throwException(); + } catch (CharacterCodingException e) { + throw new RuntimeException(e); + } + } + out.flip(); + return out; + } + + public static String decodeASCII(final ByteBuffer buffer) { + return decode(buffer, ascii); + } + + public static String decodeUTF8(final ByteBuffer buffer) { + return decode(buffer, utf8); + } + + public static String decodeUTF16(final ByteBuffer buffer) { + return decode(buffer, utf16); + } + + private static String decode(final ByteBuffer buffer, final Charset charset) { + if ( buffer == null ) + return null; + + return decodeImpl(buffer, charset); + } + + private static String decodeImpl(final ByteBuffer in, final Charset charset) { + final CharsetDecoder decoder = charset.newDecoder(); // decoders are not thread-safe, create a new one on every call + + int n = (int)(in.remaining() * decoder.averageCharsPerByte()); + CharBuffer out = BufferUtils.createCharBuffer(n); + + if ( (n == 0) && (in.remaining() == 0) ) + return ""; + + decoder.reset(); + for (; ; ) { + CoderResult cr = in.hasRemaining() ? decoder.decode(in, out, true) : CoderResult.UNDERFLOW; + if ( cr.isUnderflow() ) + cr = decoder.flush(out); + + if ( cr.isUnderflow() ) + break; + if ( cr.isOverflow() ) { + n = 2 * n + 1; // Ensure progress; n might be 0! + CharBuffer o = BufferUtils.createCharBuffer(n); + out.flip(); + o.put(out); + out = o; + continue; + } + try { + cr.throwException(); + } catch (CharacterCodingException e) { + throw new RuntimeException(e); + } + } + out.flip(); + return out.toString(); + } + + /** A null-terminated CharSequence. */ + private static class CharSequenceNT implements CharSequence { + + final CharSequence source; + + CharSequenceNT(CharSequence source) { + this.source = source; + } + + public int length() { + return source.length() + 1; + + } + + public char charAt(final int index) { + return index == source.length() ? '\0' : source.charAt(index); + + } + + public CharSequence subSequence(final int start, final int end) { + return new CharSequenceNT(source.subSequence(start, Math.min(end, source.length()))); + } + + } + + interface Accessor { + + long getAddress(Buffer buffer); + + } + + private static Accessor loadAccessor(final String className) throws Exception { + return (Accessor)Class.forName(className).newInstance(); + } + + /** Default implementation. */ + private static class AccessorJNI implements Accessor { + + public long getAddress(final Buffer buffer) { + return BufferUtils.getBufferAddress(buffer); + } + + } + + /** Implementation using reflection on ByteBuffer. */ + private static class AccessorReflect implements Accessor { + + private final Field address; + + AccessorReflect() { + try { + address = getAddressField(); + } catch (NoSuchFieldException e) { + throw new UnsupportedOperationException(e); + } + address.setAccessible(true); + } + + public long getAddress(final Buffer buffer) { + try { + return address.getLong(buffer); + } catch (IllegalAccessException e) { + // cannot happen + return 0L; + } + } + + } + + static Field getAddressField() throws NoSuchFieldException { + return getDeclaredFieldRecursive(ByteBuffer.class, "address"); + } + + private static Field getDeclaredFieldRecursive(final Class root, final String fieldName) throws NoSuchFieldException { + Class type = root; + + do { + try { + return type.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + type = type.getSuperclass(); + } + } while ( type != null ); + + throw new NoSuchFieldException(fieldName + " does not exist in " + root.getSimpleName() + " or any of its superclasses."); + } + +} diff --git a/src/main/java/org/lwjglx/PointerBuffer.java b/src/main/java/org/lwjglx/PointerBuffer.java new file mode 100644 index 0000000..d1fd7b0 --- /dev/null +++ b/src/main/java/org/lwjglx/PointerBuffer.java @@ -0,0 +1,960 @@ +/* + * Copyright (c) 2002-2010 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +import java.lang.reflect.Method; +import java.nio.*; + +/** + * This class is a container for architecture independent pointer data. + * The interface mirrors the NIO LongBuffer API for convenience. + * + * @author Spasi + */ +public class PointerBuffer implements Comparable { + + private static final boolean is64Bit; + + static { + // Use reflection so that we can compile this class for the Generator. + boolean is64 = false; + try { + Method m = Class.forName("org.lwjgl.Sys").getDeclaredMethod("is64Bit", (Class[])null); + is64 = (Boolean)m.invoke(null, (Object[])null); + } catch (Throwable t) { + // ignore + } finally { + is64Bit = is64; + } + } + + protected final ByteBuffer pointers; + + protected final Buffer view; + protected final IntBuffer view32; + protected final LongBuffer view64; + + /** + * Creates a new PointerBuffer with the specified capacity. + * + * @param capacity the PointerBuffer size, in number of pointers + */ + public PointerBuffer(final int capacity) { + this(BufferUtils.createByteBuffer(capacity * getPointerSize())); + } + + /** + * Creates a new PointerBuffer using the specified ByteBuffer as its pointer + * data source. This is useful for users that do their own memory management + * over a big ByteBuffer, instead of allocating many small ones. + * + * @param source the source buffer + */ + public PointerBuffer(final ByteBuffer source) { + if ( LWJGLUtil.CHECKS ) + checkSource(source); + + pointers = source.slice().order(source.order()); + + if ( is64Bit ) { + view32 = null; + view = view64 = pointers.asLongBuffer(); + } else { + view = view32 = pointers.asIntBuffer(); + view64 = null; + } + } + + private static void checkSource(final ByteBuffer source) { + if ( !source.isDirect() ) + throw new IllegalArgumentException("The source buffer is not direct."); + + final int alignment = is64Bit ? 8 : 4; + if ( (MemoryUtil.getAddress0(source) + source.position()) % alignment != 0 || source.remaining() % alignment != 0 ) + throw new IllegalArgumentException("The source buffer is not aligned to " + alignment + " bytes."); + } + + /** + * Returns the ByteBuffer that backs this PointerBuffer. + * + * @return the pointer ByteBuffer + */ + public ByteBuffer getBuffer() { + return pointers; + } + + /** Returns true if the underlying architecture is 64bit. */ + public static boolean is64Bit() { + return is64Bit; + } + + /** + * Returns the pointer size in bytes, based on the underlying architecture. + * + * @return The pointer size in bytes + */ + public static int getPointerSize() { + return is64Bit ? 8 : 4; + } + + /** + * Returns this buffer's capacity.

+ * + * @return The capacity of this buffer + */ + public final int capacity() { + return view.capacity(); + } + + /** + * Returns this buffer's position.

+ * + * @return The position of this buffer + */ + public final int position() { + return view.position(); + } + + /** + * Returns this buffer's position, in bytes.

+ * + * @return The position of this buffer in bytes. + */ + public final int positionByte() { + return position() * getPointerSize(); + } + + /** + * Sets this buffer's position. If the mark is defined and larger than the + * new position then it is discarded.

+ * + * @param newPosition The new position value; must be non-negative + * and no larger than the current limit + * + * @return This buffer + * + * @throws IllegalArgumentException If the preconditions on newPosition do not hold + */ + public final PointerBuffer position(int newPosition) { + view.position(newPosition); + return this; + } + + /** + * Returns this buffer's limit.

+ * + * @return The limit of this buffer + */ + public final int limit() { + return view.limit(); + } + + /** + * Sets this buffer's limit. If the position is larger than the new limit + * then it is set to the new limit. If the mark is defined and larger than + * the new limit then it is discarded.

+ * + * @param newLimit The new limit value; must be non-negative + * and no larger than this buffer's capacity + * + * @return This buffer + * + * @throws IllegalArgumentException If the preconditions on newLimit do not hold + */ + public final PointerBuffer limit(int newLimit) { + view.limit(newLimit); + return this; + } + + /** + * Sets this buffer's mark at its position.

+ * + * @return This buffer + */ + public final PointerBuffer mark() { + view.mark(); + return this; + } + + /** + * Resets this buffer's position to the previously-marked position. + *

+ *

Invoking this method neither changes nor discards the mark's + * value.

+ * + * @return This buffer + * + * @throws java.nio.InvalidMarkException If the mark has not been set + */ + public final PointerBuffer reset() { + view.reset(); + return this; + } + + /** + * Clears this buffer. The position is set to zero, the limit is set to + * the capacity, and the mark is discarded. + *

+ *

Invoke this method before using a sequence of channel-read or + * put operations to fill this buffer. For example: + *

+ *

+	 * buf.clear();     // Prepare buffer for reading
+	 * in.read(buf);    // Read data
+ *

+ *

This method does not actually erase the data in the buffer, but it + * is named as if it did because it will most often be used in situations + * in which that might as well be the case.

+ * + * @return This buffer + */ + public final PointerBuffer clear() { + view.clear(); + return this; + } + + /** + * Flips this buffer. The limit is set to the current position and then + * the position is set to zero. If the mark is defined then it is + * discarded. + *

+ *

After a sequence of channel-read or put operations, invoke + * this method to prepare for a sequence of channel-write or relative + * get operations. For example: + *

+ *

+	 * buf.put(magic);    // Prepend header
+	 * in.read(buf);      // Read data into rest of buffer
+	 * buf.flip();        // Flip buffer
+	 * out.write(buf);    // Write header + data to channel
+ *

+ *

This method is often used in conjunction with the {@link + * java.nio.ByteBuffer#compact compact} method when transferring data from + * one place to another.

+ * + * @return This buffer + */ + public final PointerBuffer flip() { + view.flip(); + return this; + } + + /** + * Rewinds this buffer. The position is set to zero and the mark is + * discarded. + *

+ *

Invoke this method before a sequence of channel-write or get + * operations, assuming that the limit has already been set + * appropriately. For example: + *

+ *

+	 * out.write(buf);    // Write remaining data
+	 * buf.rewind();      // Rewind buffer
+	 * buf.get(array);    // Copy data into array
+ * + * @return This buffer + */ + public final PointerBuffer rewind() { + view.rewind(); + return this; + } + + /** + * Returns the number of elements between the current position and the + * limit.

+ * + * @return The number of elements remaining in this buffer + */ + public final int remaining() { + return view.remaining(); + } + + /** + * Returns the number of bytes between the current position and the + * limit.

+ * + * @return The number of bytes remaining in this buffer + */ + public final int remainingByte() { + return remaining() * getPointerSize(); + } + + /** + * Tells whether there are any elements between the current position and + * the limit.

+ * + * @return true if, and only if, there is at least one element + * remaining in this buffer + */ + public final boolean hasRemaining() { + return view.hasRemaining(); + } + + /** + * Allocates a new pointer buffer. + *

+ *

The new buffer's position will be zero, its limit will be its + * capacity, and its mark will be undefined.

+ * + * @param capacity The new buffer's capacity, in pointers + * + * @return The new pointer buffer + * + * @throws IllegalArgumentException If the capacity is a negative integer + */ + public static PointerBuffer allocateDirect(int capacity) { + return new PointerBuffer(capacity); + } + + /** + * This method is used in slice and duplicate instead of normal object construction, + * so that subclasses can return themselves. + * + * @param source + * + * @return A new PointerBuffer instance + */ + protected PointerBuffer newInstance(final ByteBuffer source) { + return new PointerBuffer(source); + } + + /** + * Creates a new pointer buffer whose content is a shared subsequence of + * this buffer's content. + *

+ *

The content of the new buffer will start at this buffer's current + * position. Changes to this buffer's content will be visible in the new + * buffer, and vice versa; the two buffers' position, limit, and mark + * values will be independent. + *

+ *

The new buffer's position will be zero, its capacity and its limit + * will be the number of longs remaining in this buffer, and its mark + * will be undefined. The new buffer will be direct if, and only if, this + * buffer is direct, and it will be read-only if, and only if, this buffer + * is read-only.

+ * + * @return The new pointer buffer + */ + public PointerBuffer slice() { + final int pointerSize = getPointerSize(); + + pointers.position(view.position() * pointerSize); + pointers.limit(view.limit() * pointerSize); + + try { + // We're slicing in the constructor. + return newInstance(pointers); + } finally { + pointers.clear(); + } + } + + /** + * Creates a new pointer buffer that shares this buffer's content. + *

+ *

The content of the new buffer will be that of this buffer. Changes + * to this buffer's content will be visible in the new buffer, and vice + * versa; the two buffers' position, limit, and mark values will be + * independent. + *

+ *

The new buffer's capacity, limit and position will be + * identical to those of this buffer. The new buffer will be direct if, + * and only if, this buffer is direct, and it will be read-only if, and + * only if, this buffer is read-only.

+ * + * @return The new pointer buffer + */ + public PointerBuffer duplicate() { + final PointerBuffer buffer = newInstance(pointers); + + buffer.position(view.position()); + buffer.limit(view.limit()); + + return buffer; + } + + /** + * Creates a new, read-only pointer buffer that shares this buffer's + * content. + *

+ *

The content of the new buffer will be that of this buffer. Changes + * to this buffer's content will be visible in the new buffer; the new + * buffer itself, however, will be read-only and will not allow the shared + * content to be modified. The two buffers' position, limit, and mark + * values will be independent. + *

+ *

The new buffer's capacity, limit and position will be + * identical to those of this buffer. + *

+ *

If this buffer is itself read-only then this method behaves in + * exactly the same way as the {@link #duplicate duplicate} method.

+ * + * @return The new, read-only pointer buffer + */ + public PointerBuffer asReadOnlyBuffer() { + final PointerBuffer buffer = new PointerBufferR(pointers); + + buffer.position(view.position()); + buffer.limit(view.limit()); + + return buffer; + } + + public boolean isReadOnly() { + return false; + } + + /** + * Relative get method. Reads the long at this buffer's + * current position, and then increments the position.

+ * + * @return The long at the buffer's current position + * + * @throws BufferUnderflowException If the buffer's current position is not smaller than its limit + */ + public long get() { + if ( is64Bit ) + return view64.get(); + else + return view32.get() & 0x00000000FFFFFFFFL; + } + + /** + * Relative put method  (optional operation). + *

+ *

Writes the given long into this buffer at the current + * position, and then increments the position.

+ * + * @param l The long to be written + * + * @return This buffer + * + * @throws BufferOverflowException If this buffer's current position is not smaller than its limit + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public PointerBuffer put(long l) { + if ( is64Bit ) + view64.put(l); + else + view32.put((int)l); + return this; + } + + /** + * Convenience put that accepts PointerWrapper objects. + * + * @see #put(long) + */ + public PointerBuffer put(final PointerWrapper pointer) { + return put(pointer.getPointer()); + } + + /** + * Convenience put on a target ByteBuffer. + * + * @param target the target ByteBuffer + * @param l the long value to be written + */ + public static void put(final ByteBuffer target, long l) { + if ( is64Bit ) + target.putLong(l); + else + target.putInt((int)l); + } + + /** + * Absolute get method. Reads the long at the given + * index.

+ * + * @param index The index from which the long will be read + * + * @return The long at the given index + * + * @throws IndexOutOfBoundsException If index is negative + * or not smaller than the buffer's limit + */ + public long get(int index) { + if ( is64Bit ) + return view64.get(index); + else + return view32.get(index) & 0x00000000FFFFFFFFL; + } + + /** + * Absolute put method  (optional operation). + *

+ *

Writes the given long into this buffer at the given + * index.

+ * + * @param index The index at which the long will be written + * @param l The long value to be written + * + * @return This buffer + * + * @throws IndexOutOfBoundsException If index is negative + * or not smaller than the buffer's limit + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public PointerBuffer put(int index, long l) { + if ( is64Bit ) + view64.put(index, l); + else + view32.put(index, (int)l); + return this; + } + + /** + * Convenience put that accepts PointerWrapper objects. + * + * @see #put(int, long) + */ + public PointerBuffer put(int index, PointerWrapper pointer) { + return put(index, pointer.getPointer()); + } + + /** + * Convenience put on a target ByteBuffer. + * + * @param target the target ByteBuffer + * @param index the index at which the long will be written + * @param l the long value to be written + */ + public static void put(final ByteBuffer target, int index, long l) { + if ( is64Bit ) + target.putLong(index * 8, l); + else + target.putInt(index * 4, (int)l); + } + + // -- Bulk get operations -- + + /** + * Relative bulk get method. + *

+ *

This method transfers longs from this buffer into the given + * destination array. If there are fewer longs remaining in the + * buffer than are required to satisfy the request, that is, if + * length > remaining(), then no + * longs are transferred and a {@link BufferUnderflowException} is + * thrown. + *

+ *

Otherwise, this method copies length longs from this + * buffer into the given array, starting at the current position of this + * buffer and at the given offset in the array. The position of this + * buffer is then incremented by length. + *

+ *

In other words, an invocation of this method of the form + * src.get(dst, off, len) has exactly the same effect as + * the loop + *

+ *

+	 *     for (int i = off; i < off + len; i++)
+	 *         dst[i] = src.get(); 
+ *

+ * except that it first checks that there are sufficient longs in + * this buffer and it is potentially much more efficient.

+ * + * @param dst The array into which longs are to be written + * @param offset The offset within the array of the first long to be + * written; must be non-negative and no larger than + * dst.length + * @param length The maximum number of longs to be written to the given + * array; must be non-negative and no larger than + * dst.length - offset + * + * @return This buffer + * + * @throws BufferUnderflowException If there are fewer than length longs + * remaining in this buffer + * @throws IndexOutOfBoundsException If the preconditions on the offset and length + * parameters do not hold + */ + public PointerBuffer get(long[] dst, int offset, int length) { + if ( is64Bit ) + view64.get(dst, offset, length); + else { + checkBounds(offset, length, dst.length); + if ( length > view32.remaining() ) + throw new BufferUnderflowException(); + int end = offset + length; + for ( int i = offset; i < end; i++ ) + dst[i] = view32.get() & 0x00000000FFFFFFFFL; + } + + return this; + } + + /** + * Relative bulk get method. + *

+ *

This method transfers longs from this buffer into the given + * destination array. An invocation of this method of the form + * src.get(a) behaves in exactly the same way as the invocation + *

+ *

+	 *     src.get(a, 0, a.length) 
+ * + * @return This buffer + * + * @throws BufferUnderflowException If there are fewer than length longs + * remaining in this buffer + */ + public PointerBuffer get(long[] dst) { + return get(dst, 0, dst.length); + } + + /** + * Relative bulk put method  (optional operation). + *

+ *

This method transfers the longs remaining in the given source + * buffer into this buffer. If there are more longs remaining in the + * source buffer than in this buffer, that is, if + * src.remaining() > remaining(), + * then no longs are transferred and a {@link + * BufferOverflowException} is thrown. + *

+ *

Otherwise, this method copies + * n = src.remaining() longs from the given + * buffer into this buffer, starting at each buffer's current position. + * The positions of both buffers are then incremented by n. + *

+ *

In other words, an invocation of this method of the form + * dst.put(src) has exactly the same effect as the loop + *

+ *

+	 *     while (src.hasRemaining())
+	 *         dst.put(src.get()); 
+ *

+ * except that it first checks that there is sufficient space in this + * buffer and it is potentially much more efficient.

+ * + * @param src The source buffer from which longs are to be read; + * must not be this buffer + * + * @return This buffer + * + * @throws BufferOverflowException If there is insufficient space in this buffer + * for the remaining longs in the source buffer + * @throws IllegalArgumentException If the source buffer is this buffer + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public PointerBuffer put(PointerBuffer src) { + if ( is64Bit ) + view64.put(src.view64); + else + view32.put(src.view32); + return this; + } + + /** + * Relative bulk put method  (optional operation). + *

+ *

This method transfers longs into this buffer from the given + * source array. If there are more longs to be copied from the array + * than remain in this buffer, that is, if + * length > remaining(), then no + * longs are transferred and a {@link BufferOverflowException} is + * thrown. + *

+ *

Otherwise, this method copies length longs from the + * given array into this buffer, starting at the given offset in the array + * and at the current position of this buffer. The position of this buffer + * is then incremented by length. + *

+ *

In other words, an invocation of this method of the form + * dst.put(src, off, len) has exactly the same effect as + * the loop + *

+ *

+	 *     for (int i = off; i < off + len; i++)
+	 *         dst.put(a[i]); 
+ *

+ * except that it first checks that there is sufficient space in this + * buffer and it is potentially much more efficient.

+ * + * @param src The array from which longs are to be read + * @param offset The offset within the array of the first long to be read; + * must be non-negative and no larger than array.length + * @param length The number of longs to be read from the given array; + * must be non-negative and no larger than + * array.length - offset + * + * @return This buffer + * + * @throws BufferOverflowException If there is insufficient space in this buffer + * @throws IndexOutOfBoundsException If the preconditions on the offset and length + * parameters do not hold + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public PointerBuffer put(long[] src, int offset, int length) { + if ( is64Bit ) + view64.put(src, offset, length); + else { + checkBounds(offset, length, src.length); + if ( length > view32.remaining() ) + throw new BufferOverflowException(); + int end = offset + length; + for ( int i = offset; i < end; i++ ) + view32.put((int)src[i]); + } + + return this; + } + + /** + * Relative bulk put method  (optional operation). + *

+ *

This method transfers the entire content of the given source + * long array into this buffer. An invocation of this method of the + * form dst.put(a) behaves in exactly the same way as the + * invocation + *

+ *

+	 *     dst.put(a, 0, a.length) 
+ * + * @return This buffer + * + * @throws BufferOverflowException If there is insufficient space in this buffer + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public final PointerBuffer put(long[] src) { + return put(src, 0, src.length); + } + + /** + * Compacts this buffer  (optional operation). + *

+ *

The longs between the buffer's current position and its limit, + * if any, are copied to the beginning of the buffer. That is, the + * long at index p = position() is copied + * to index zero, the long at index p + 1 is copied + * to index one, and so forth until the long at index + * limit() - 1 is copied to index + * n = limit() - 1 - p. + * The buffer's position is then set to n+1 and its limit is set to + * its capacity. The mark, if defined, is discarded. + *

+ *

The buffer's position is set to the number of longs copied, + * rather than to zero, so that an invocation of this method can be + * followed immediately by an invocation of another relative put + * method.

+ * + * @return This buffer + * + * @throws ReadOnlyBufferException If this buffer is read-only + */ + public PointerBuffer compact() { + if ( is64Bit ) + view64.compact(); + else + view32.compact(); + return this; + } + + /** + * Retrieves this buffer's byte order. + *

+ *

The byte order of a pointer buffer created by allocation or by + * wrapping an existing long array is the {@link + * ByteOrder#nativeOrder native order} of the underlying + * hardware. The byte order of a pointer buffer created as a view of a byte buffer is that of the + * byte buffer at the moment that the view is created.

+ * + * @return This buffer's byte order + */ + public ByteOrder order() { + if ( is64Bit ) + return view64.order(); + else + return view32.order(); + } + + /** + * Returns a string summarizing the state of this buffer.

+ * + * @return A summary string + */ + public String toString() { + StringBuilder sb = new StringBuilder(48); + sb.append(getClass().getName()); + sb.append("[pos="); + sb.append(position()); + sb.append(" lim="); + sb.append(limit()); + sb.append(" cap="); + sb.append(capacity()); + sb.append("]"); + return sb.toString(); + } + + /** + * Returns the current hash code of this buffer. + *

+ *

The hash code of a pointer buffer depends only upon its remaining + * elements; that is, upon the elements from position() up to, and + * including, the element at limit() - 1. + *

+ *

Because buffer hash codes are content-dependent, it is inadvisable + * to use buffers as keys in hash maps or similar data structures unless it + * is known that their contents will not change.

+ * + * @return The current hash code of this buffer + */ + public int hashCode() { + int h = 1; + int p = position(); + for ( int i = limit() - 1; i >= p; i-- ) + h = 31 * h + (int)get(i); + return h; + } + + /** + * Tells whether or not this buffer is equal to another object. + *

+ *

Two pointer buffers are equal if, and only if, + *

+ *

    + *

    + *

  1. They have the same element type,

  2. + *

    + *

  3. They have the same number of remaining elements, and + *

  4. + *

    + *

  5. The two sequences of remaining elements, considered + * independently of their starting positions, are pointwise equal. + *

  6. + *

    + *

+ *

+ *

A pointer buffer is not equal to any other type of object.

+ * + * @param ob The object to which this buffer is to be compared + * + * @return true if, and only if, this buffer is equal to the + * given object + */ + public boolean equals(Object ob) { + if ( !(ob instanceof PointerBuffer) ) + return false; + PointerBuffer that = (PointerBuffer)ob; + if ( this.remaining() != that.remaining() ) + return false; + int p = this.position(); + for ( int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j-- ) { + long v1 = this.get(i); + long v2 = that.get(j); + if ( v1 != v2 ) { + return false; + } + } + return true; + } + + /** + * Compares this buffer to another. + *

+ *

Two pointer buffers are compared by comparing their sequences of + * remaining elements lexicographically, without regard to the starting + * position of each sequence within its corresponding buffer. + *

+ *

A pointer buffer is not comparable to any other type of object. + * + * @return A negative integer, zero, or a positive integer as this buffer + * is less than, equal to, or greater than the given buffer + */ + public int compareTo(Object o) { + final PointerBuffer that = (PointerBuffer)o; + int n = this.position() + Math.min(this.remaining(), that.remaining()); + for ( int i = this.position(), j = that.position(); i < n; i++, j++ ) { + long v1 = this.get(i); + long v2 = that.get(j); + if ( v1 == v2 ) + continue; + if ( v1 < v2 ) + return -1; + return +1; + } + return this.remaining() - that.remaining(); + } + + private static void checkBounds(int off, int len, int size) { + if ( (off | len | (off + len) | (size - (off + len))) < 0 ) + throw new IndexOutOfBoundsException(); + } + + /** + * Read-only version of PointerBuffer. + * + * @author Spasi + */ + private static final class PointerBufferR extends PointerBuffer { + + PointerBufferR(final ByteBuffer source) { + super(source); + } + + public boolean isReadOnly() { + return true; + } + + protected PointerBuffer newInstance(final ByteBuffer source) { + return new PointerBufferR(source); + } + + public PointerBuffer asReadOnlyBuffer() { + return duplicate(); + } + + public PointerBuffer put(final long l) { + throw new ReadOnlyBufferException(); + } + + public PointerBuffer put(final int index, final long l) { + throw new ReadOnlyBufferException(); + } + + public PointerBuffer put(final PointerBuffer src) { + throw new ReadOnlyBufferException(); + } + + public PointerBuffer put(final long[] src, final int offset, final int length) { + throw new ReadOnlyBufferException(); + } + + public PointerBuffer compact() { + throw new ReadOnlyBufferException(); + } + + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/PointerWrapper.java b/src/main/java/org/lwjglx/PointerWrapper.java new file mode 100644 index 0000000..9d0878c --- /dev/null +++ b/src/main/java/org/lwjglx/PointerWrapper.java @@ -0,0 +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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +/** + * A common interface for classes that wrap pointer addresses. + * + * @author Spasi + */ +public interface PointerWrapper { + + long getPointer(); + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/PointerWrapperAbstract.java b/src/main/java/org/lwjglx/PointerWrapperAbstract.java new file mode 100644 index 0000000..81b7df5 --- /dev/null +++ b/src/main/java/org/lwjglx/PointerWrapperAbstract.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2002-2010 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx; + +/** + * Base PointerWrapper implementation. + * + * @author Spasi + */ +public abstract class PointerWrapperAbstract implements PointerWrapper { + + protected final long pointer; + + protected PointerWrapperAbstract(final long pointer) { + this.pointer = pointer; + } + + /** + * Returns true if this object represents a valid pointer. + * The pointer might be invalid because it is NULL or because + * some other action has deleted the object that this pointer + * represents. + * + * @return true if the pointer is valid + */ + public boolean isValid() { + return pointer != 0; + } + + /** + * Checks if the pointer is valid and throws an IllegalStateException if + * it is not. This method is a NO-OP, unless the org.lwjgl.util.Debug + * property has been set to true. + */ + public final void checkValid() { + if ( LWJGLUtil.DEBUG && !isValid() ) + throw new IllegalStateException("This " + getClass().getSimpleName() + " pointer is not valid."); + } + + public final long getPointer() { + checkValid(); + return pointer; + } + + public boolean equals(final Object o) { + if ( this == o ) return true; + if ( !(o instanceof PointerWrapperAbstract) ) return false; + + final PointerWrapperAbstract that = (PointerWrapperAbstract)o; + + if ( pointer != that.pointer ) return false; + + return true; + } + + public int hashCode() { + return (int)(pointer ^ (pointer >>> 32)); + } + + public String toString() { + return getClass().getSimpleName() + " pointer (0x" + Long.toHexString(pointer).toUpperCase() + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/Sys.java b/src/main/java/org/lwjglx/Sys.java new file mode 100644 index 0000000..ff666a0 --- /dev/null +++ b/src/main/java/org/lwjglx/Sys.java @@ -0,0 +1,77 @@ +package org.lwjglx; + +import static org.lwjgl.glfw.GLFW.glfwInit; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.glfw.GLFW; + +import java.awt.Desktop; +import java.net.URI; + +import javax.swing.JOptionPane; +import javax.swing.UIManager; + +public class Sys { + + static { + if ( glfwInit() != GL11.GL_TRUE ) + throw new IllegalStateException("Unable to initialize glfw"); + } + + public static void initialize() { + + } + + /** Returns the LWJGL version. */ + public static String getVersion() { + return org.lwjgl.Sys.getVersion(); + } + + /** + * Obtains the number of ticks that the hires timer does in a second. This method is fast; + * it should be called as frequently as possible, as it recalibrates the timer. + * + * @return timer resolution in ticks per second or 0 if no timer is present. + */ + public static long getTimerResolution() { + return 1000; + } + + /** + * Gets the current value of the hires timer, in ticks. When the Sys class is first loaded + * the hires timer is reset to 0. If no hires timer is present then this method will always + * return 0.

NOTEZ BIEN that the hires timer WILL wrap around. + * + * @return the current hires time, in ticks (always >= 0) + */ + public static long getTime() { + return (long) (GLFW.glfwGetTime() * 1000); + } + + public static long getNanoTime() { + return (long) (GLFW.glfwGetTime() * (1000L * 1000L * 1000L)); + } + + public static boolean openURL(String url) { + if (!Desktop.isDesktopSupported()) return false; + + Desktop desktop = Desktop.getDesktop(); + if (!desktop.isSupported(Desktop.Action.BROWSE)) return false; + + try { + desktop.browse(new URI(url)); + return true; + } catch (Exception ex) { + return false; + } + } + + public static void alert(String title, String message) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch(Exception e) { + LWJGLUtil.log("Caught exception while setting LAF: " + e); + } + JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE); + } +} diff --git a/src/main/java/org/lwjglx/input/Cursor.java b/src/main/java/org/lwjglx/input/Cursor.java new file mode 100644 index 0000000..90b90f2 --- /dev/null +++ b/src/main/java/org/lwjglx/input/Cursor.java @@ -0,0 +1,258 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.input; + +import java.nio.IntBuffer; + +import org.lwjglx.BufferChecks; +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLException; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.Sys; + +/** + * + * A class representing a native cursor. Instances of this + * class can be used with Mouse.setCursor(), if available. + * + * @author elias_naur + * @version $Revision$ + * $Id$ + */ + +public class Cursor { + /** 1 bit transparency for native cursor */ + public static final int CURSOR_ONE_BIT_TRANSPARENCY = 1; + + /** 8 bit alhpa native cursor */ + public static final int CURSOR_8_BIT_ALPHA = 2; + + /** animation native cursor */ + public static final int CURSOR_ANIMATION = 4; + + /** First element to display */ + private final CursorElement[] cursors; + + /** Index into list of cursors */ + private int index; + + private boolean destroyed; + + /** + * Constructs a new Cursor, with the given parameters. Mouse must have been created before you can create + * Cursor objects. Cursor images are in ARGB format, but only one bit transparancy is guaranteed to be supported. + * So to maximize portability, lwjgl applications should only create cursor images with 0x00 or 0xff as alpha values. + * The constructor will copy the images and delays, so there's no need to keep them around. + * + * @param width cursor image width + * @param height cursor image height + * @param xHotspot the x coordinate of the cursor hotspot + * @param yHotspot the y coordinate of the cursor hotspot + * @param numImages number of cursor images specified. Must be 1 if animations are not supported. + * @param images A buffer containing the images. The origin is at the lower left corner, like OpenGL. + * @param delays An int buffer of animation frame delays, if numImages is greater than 1, else null + * @throws LWJGLException if the cursor could not be created for any reason + */ + public Cursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException { + // TODO + cursors = null; + } + + /** + * Gets the minimum size of a native cursor. Can only be called if + * The Mouse is created and cursor caps includes at least + * CURSOR_ONE_BIT_TRANSPARANCY. + * + * @return the maximum size of a native cursor + */ + public static int getMinCursorSize() { + // TODO + return 0; + } + + /** + * Gets the maximum size of a native cursor. Can only be called if + * The Mouse is created and cursor caps includes at least + * CURSOR_ONE_BIT_TRANSPARANCY. + * + * @return the maximum size of a native cursor + */ + public static int getMaxCursorSize() { + // TODO + return 0; + } + + /** + * Get the capabilities of the native cursor. Return a bit mask of the native cursor capabilities. + * The CURSOR_ONE_BIT_TRANSPARANCY indicates support for cursors with one bit transparancy, + * the CURSOR_8_BIT_ALPHA indicates support for 8 bit alpha and CURSOR_ANIMATION indicates + * support for cursor animations. + * + * @return A bit mask with native cursor capabilities. + */ + public static int getCapabilities() { + // TODO + return 0; + } + + /** + * Creates the actual cursor, using a platform specific class + */ + private static CursorElement[] createCursors(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException { + // TODO + return null; + } + + /** + * Convert an IntBuffer image of ARGB format into ABGR + * + * @param imageBuffer image to convert + */ + private static void convertARGBtoABGR(IntBuffer imageBuffer) { + for (int i = 0; i < imageBuffer.limit(); i++) { + int argbColor = imageBuffer.get(i); + + byte alpha = (byte)(argbColor >>> 24); + byte blue = (byte)(argbColor >>> 16); + byte green = (byte)(argbColor >>> 8); + byte red = (byte)argbColor; + + int abgrColor = ((alpha & 0xff) << 24 ) + ((red & 0xff) << 16 ) + ((green & 0xff) << 8 ) + ((blue & 0xff) ); + + imageBuffer.put(i, abgrColor); + } + } + + /** + * Flips the images so they're oriented according to opengl + * + * @param width Width of image + * @param height Height of images + * @param numImages How many images to flip + * @param images Source images + * @param images_copy Destination images + */ + private static void flipImages(int width, int height, int numImages, IntBuffer images, IntBuffer images_copy) { + for (int i = 0; i < numImages; i++) { + int start_index = i*width*height; + flipImage(width, height, start_index, images, images_copy); + } + } + + /** + * @param width Width of image + * @param height Height of images + * @param start_index index into source buffer to copy to + * @param images Source images + * @param images_copy Destination images + */ + private static void flipImage(int width, int height, int start_index, IntBuffer images, IntBuffer images_copy) { + for (int y = 0; y < height>>1; y++) { + int index_y_1 = y*width + start_index; + int index_y_2 = (height - y - 1)*width + start_index; + for (int x = 0; x < width; x++) { + int index1 = index_y_1 + x; + int index2 = index_y_2 + x; + int temp_pixel = images.get(index1 + images.position()); + images_copy.put(index1, images.get(index2 + images.position())); + images_copy.put(index2, temp_pixel); + } + } + } + + /** + * Gets the native handle associated with the cursor object. + */ + Object getHandle() { + checkValid(); + return cursors[index].cursorHandle; + } + + private void checkValid() { + if (destroyed) + throw new IllegalStateException("The cursor is destroyed"); + } + + /** + * Destroy the native cursor. If the cursor is current, + * the current native cursor is set to null (the default + * OS cursor) + */ + public void destroy() { + // TODO + } + + /** + * Sets the timout property to the time it should be changed + */ + protected void setTimeout() { + checkValid(); + cursors[index].timeout = System.currentTimeMillis() + cursors[index].delay; + } + + /** + * Determines whether this cursor has timed out + * @return true if the this cursor has timed out, false if not + */ + protected boolean hasTimedOut() { + checkValid(); + return cursors.length > 1 && cursors[index].timeout < System.currentTimeMillis(); + } + + /** + * Changes to the next cursor + */ + protected void nextCursor() { + checkValid(); + index = ++index % cursors.length; + } + + /** + * A single cursor element, used when animating + */ + private static class CursorElement { + /** Handle to cursor */ + final Object cursorHandle; + + /** How long a delay this element should have */ + final long delay; + + /** Absolute time this element times out */ + long timeout; + + CursorElement(Object cursorHandle, long delay, long timeout) { + this.cursorHandle = cursorHandle; + this.delay = delay; + this.timeout = timeout; + } + } +} diff --git a/src/main/java/org/lwjglx/input/EventQueue.java b/src/main/java/org/lwjglx/input/EventQueue.java new file mode 100644 index 0000000..202f817 --- /dev/null +++ b/src/main/java/org/lwjglx/input/EventQueue.java @@ -0,0 +1,57 @@ +package org.lwjglx.input; + +/** + * Internal utility class to keep track of event positions in an array. + * When the array is full the position will wrap to the beginning. + */ +class EventQueue { + + private int maxEvents = 32; + private int eventCount = 0; + private int currentEventPos = -1; + private int nextEventPos = 0; + + EventQueue(int maxEvents) { + this.maxEvents = maxEvents; + } + + /** + * add event to the queue + */ + void add() { + eventCount++; // increment event count + if (eventCount > maxEvents) eventCount = maxEvents; // cap max events + + nextEventPos++; // increment next event position + if (nextEventPos == maxEvents) nextEventPos = 0; // wrap next event position + + if (nextEventPos == currentEventPos) currentEventPos++; // skip oldest event is queue full + if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position + } + + /** + * Increment the event queue + * @return - true if there is an event available + */ + boolean next() { + if (eventCount == 0) return false; + + eventCount--; // decrement event count + currentEventPos++; // increment current event position + if (currentEventPos == maxEvents) currentEventPos = 0; // wrap current event position + + return true; + } + + int getMaxEvents() { + return maxEvents; + } + + int getCurrentPos() { + return currentEventPos; + } + + int getNextPos() { + return nextEventPos; + } +} diff --git a/src/main/java/org/lwjglx/input/KeyCodes.java b/src/main/java/org/lwjglx/input/KeyCodes.java new file mode 100644 index 0000000..8fd3d9e --- /dev/null +++ b/src/main/java/org/lwjglx/input/KeyCodes.java @@ -0,0 +1,321 @@ +package org.lwjglx.input; + +import org.lwjgl.glfw.GLFW; + +public class KeyCodes { + + public static int toLwjglKey(int glfwKeyCode) { + + switch(glfwKeyCode) { + + case GLFW.GLFW_KEY_ESCAPE : return Keyboard.KEY_ESCAPE; + case GLFW.GLFW_KEY_BACKSPACE: return Keyboard.KEY_BACK; + case GLFW.GLFW_KEY_TAB : return Keyboard.KEY_TAB; + case GLFW.GLFW_KEY_ENTER : return Keyboard.KEY_RETURN; + case GLFW.GLFW_KEY_SPACE : return Keyboard.KEY_SPACE; + + case GLFW.GLFW_KEY_LEFT_CONTROL : return Keyboard.KEY_LCONTROL; + case GLFW.GLFW_KEY_LEFT_SHIFT : return Keyboard.KEY_LSHIFT; + case GLFW.GLFW_KEY_LEFT_ALT : return Keyboard.KEY_LMENU; + case GLFW.GLFW_KEY_LEFT_SUPER : return Keyboard.KEY_LMETA; + + case GLFW.GLFW_KEY_RIGHT_CONTROL: return Keyboard.KEY_RCONTROL; + case GLFW.GLFW_KEY_RIGHT_SHIFT : return Keyboard.KEY_RSHIFT; + case GLFW.GLFW_KEY_RIGHT_ALT : return Keyboard.KEY_RMENU; + case GLFW.GLFW_KEY_RIGHT_SUPER : return Keyboard.KEY_RMETA; + + case GLFW.GLFW_KEY_1 : return Keyboard.KEY_1; + case GLFW.GLFW_KEY_2 : return Keyboard.KEY_2; + case GLFW.GLFW_KEY_3 : return Keyboard.KEY_3; + case GLFW.GLFW_KEY_4 : return Keyboard.KEY_4; + case GLFW.GLFW_KEY_5 : return Keyboard.KEY_5; + case GLFW.GLFW_KEY_6 : return Keyboard.KEY_6; + case GLFW.GLFW_KEY_7 : return Keyboard.KEY_7; + case GLFW.GLFW_KEY_8 : return Keyboard.KEY_8; + case GLFW.GLFW_KEY_9 : return Keyboard.KEY_9; + case GLFW.GLFW_KEY_0 : return Keyboard.KEY_0; + + case GLFW.GLFW_KEY_A : return Keyboard.KEY_A; + case GLFW.GLFW_KEY_B : return Keyboard.KEY_B; + case GLFW.GLFW_KEY_C : return Keyboard.KEY_C; + case GLFW.GLFW_KEY_D : return Keyboard.KEY_D; + case GLFW.GLFW_KEY_E : return Keyboard.KEY_E; + case GLFW.GLFW_KEY_F : return Keyboard.KEY_F; + case GLFW.GLFW_KEY_G : return Keyboard.KEY_G; + case GLFW.GLFW_KEY_H : return Keyboard.KEY_H; + case GLFW.GLFW_KEY_I : return Keyboard.KEY_I; + case GLFW.GLFW_KEY_J : return Keyboard.KEY_J; + case GLFW.GLFW_KEY_K : return Keyboard.KEY_K; + case GLFW.GLFW_KEY_L : return Keyboard.KEY_L; + case GLFW.GLFW_KEY_M : return Keyboard.KEY_M; + case GLFW.GLFW_KEY_N : return Keyboard.KEY_N; + case GLFW.GLFW_KEY_O : return Keyboard.KEY_O; + case GLFW.GLFW_KEY_P : return Keyboard.KEY_P; + case GLFW.GLFW_KEY_Q : return Keyboard.KEY_Q; + case GLFW.GLFW_KEY_R : return Keyboard.KEY_R; + case GLFW.GLFW_KEY_S : return Keyboard.KEY_S; + case GLFW.GLFW_KEY_T : return Keyboard.KEY_T; + case GLFW.GLFW_KEY_U : return Keyboard.KEY_U; + case GLFW.GLFW_KEY_V : return Keyboard.KEY_V; + case GLFW.GLFW_KEY_W : return Keyboard.KEY_W; + case GLFW.GLFW_KEY_X : return Keyboard.KEY_X; + case GLFW.GLFW_KEY_Y : return Keyboard.KEY_Y; + case GLFW.GLFW_KEY_Z : return Keyboard.KEY_Z; + + case GLFW.GLFW_KEY_UP : return Keyboard.KEY_UP; + case GLFW.GLFW_KEY_DOWN : return Keyboard.KEY_DOWN; + case GLFW.GLFW_KEY_LEFT : return Keyboard.KEY_LEFT; + case GLFW.GLFW_KEY_RIGHT : return Keyboard.KEY_RIGHT; + + case GLFW.GLFW_KEY_INSERT : return Keyboard.KEY_INSERT; + case GLFW.GLFW_KEY_DELETE : return Keyboard.KEY_DELETE; + case GLFW.GLFW_KEY_HOME : return Keyboard.KEY_HOME; + case GLFW.GLFW_KEY_END : return Keyboard.KEY_END; + case GLFW.GLFW_KEY_PAGE_UP : return Keyboard.KEY_PRIOR; + case GLFW.GLFW_KEY_PAGE_DOWN: return Keyboard.KEY_NEXT; + + case GLFW.GLFW_KEY_F1 : return Keyboard.KEY_F1; + case GLFW.GLFW_KEY_F2 : return Keyboard.KEY_F2; + case GLFW.GLFW_KEY_F3 : return Keyboard.KEY_F3; + case GLFW.GLFW_KEY_F4 : return Keyboard.KEY_F4; + case GLFW.GLFW_KEY_F5 : return Keyboard.KEY_F5; + case GLFW.GLFW_KEY_F6 : return Keyboard.KEY_F6; + case GLFW.GLFW_KEY_F7 : return Keyboard.KEY_F7; + case GLFW.GLFW_KEY_F8 : return Keyboard.KEY_F8; + case GLFW.GLFW_KEY_F9 : return Keyboard.KEY_F9; + case GLFW.GLFW_KEY_F10 : return Keyboard.KEY_F10; + case GLFW.GLFW_KEY_F11 : return Keyboard.KEY_F11; + case GLFW.GLFW_KEY_F12 : return Keyboard.KEY_F12; + case GLFW.GLFW_KEY_F13 : return Keyboard.KEY_F13; + case GLFW.GLFW_KEY_F14 : return Keyboard.KEY_F14; + case GLFW.GLFW_KEY_F15 : return Keyboard.KEY_F15; + case GLFW.GLFW_KEY_F16 : return Keyboard.KEY_F16; + case GLFW.GLFW_KEY_F17 : return Keyboard.KEY_F17; + case GLFW.GLFW_KEY_F18 : return Keyboard.KEY_F18; + case GLFW.GLFW_KEY_F19 : return Keyboard.KEY_F19; + + case GLFW.GLFW_KEY_KP_1 : return Keyboard.KEY_NUMPAD1; + case GLFW.GLFW_KEY_KP_2 : return Keyboard.KEY_NUMPAD2; + case GLFW.GLFW_KEY_KP_3 : return Keyboard.KEY_NUMPAD3; + case GLFW.GLFW_KEY_KP_4 : return Keyboard.KEY_NUMPAD4; + case GLFW.GLFW_KEY_KP_5 : return Keyboard.KEY_NUMPAD5; + case GLFW.GLFW_KEY_KP_6 : return Keyboard.KEY_NUMPAD6; + case GLFW.GLFW_KEY_KP_7 : return Keyboard.KEY_NUMPAD7; + case GLFW.GLFW_KEY_KP_8 : return Keyboard.KEY_NUMPAD8; + case GLFW.GLFW_KEY_KP_9 : return Keyboard.KEY_NUMPAD9; + case GLFW.GLFW_KEY_KP_0 : return Keyboard.KEY_NUMPAD0; + + case GLFW.GLFW_KEY_KP_ADD : return Keyboard.KEY_ADD; + case GLFW.GLFW_KEY_KP_SUBTRACT : return Keyboard.KEY_SUBTRACT; + case GLFW.GLFW_KEY_KP_MULTIPLY : return Keyboard.KEY_MULTIPLY; + case GLFW.GLFW_KEY_KP_DIVIDE: return Keyboard.KEY_DIVIDE; + case GLFW.GLFW_KEY_KP_DECIMAL : return Keyboard.KEY_DECIMAL; + case GLFW.GLFW_KEY_KP_EQUAL : return Keyboard.KEY_NUMPADEQUALS; + case GLFW.GLFW_KEY_KP_ENTER : return Keyboard.KEY_NUMPADENTER; + case GLFW.GLFW_KEY_NUM_LOCK : return Keyboard.KEY_NUMLOCK; + + case GLFW.GLFW_KEY_SEMICOLON: return Keyboard.KEY_SEMICOLON; + case GLFW.GLFW_KEY_BACKSLASH: return Keyboard.KEY_BACKSLASH; + case GLFW.GLFW_KEY_COMMA : return Keyboard.KEY_COMMA; + case GLFW.GLFW_KEY_PERIOD : return Keyboard.KEY_PERIOD; + case GLFW.GLFW_KEY_SLASH : return Keyboard.KEY_SLASH; + case GLFW.GLFW_KEY_GRAVE_ACCENT : return Keyboard.KEY_GRAVE; + + case GLFW.GLFW_KEY_CAPS_LOCK: return Keyboard.KEY_CAPITAL; + case GLFW.GLFW_KEY_SCROLL_LOCK : return Keyboard.KEY_SCROLL; + + case GLFW.GLFW_KEY_WORLD_1 : return Keyboard.KEY_CIRCUMFLEX; // TODO not sure if correct + case GLFW.GLFW_KEY_PAUSE : return Keyboard.KEY_PAUSE; + + case GLFW.GLFW_KEY_MINUS : return Keyboard.KEY_MINUS; + case GLFW.GLFW_KEY_EQUAL : return Keyboard.KEY_EQUALS; + case GLFW.GLFW_KEY_LEFT_BRACKET : return Keyboard.KEY_LBRACKET; + case GLFW.GLFW_KEY_RIGHT_BRACKET: return Keyboard.KEY_RBRACKET; + case GLFW.GLFW_KEY_APOSTROPHE : return Keyboard.KEY_APOSTROPHE; +// public static final int KEY_AT = 0x91; /* (NEC PC98) */ +// public static final int KEY_COLON = 0x92; /* (NEC PC98) */ +// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */ + +// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */ +// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */ +// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */ +// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */ +// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */ +// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */ +// public static final int KEY_STOP = 0x95; /* (NEC PC98) */ +// public static final int KEY_AX = 0x96; /* (Japan AX) */ +// public static final int KEY_UNLABELED = 0x97; /* (J3100) */ +// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */ +// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */ +// public static final int KEY_SYSRQ = 0xB7; +// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */ +// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */ + +// public static final int KEY_APPS = 0xDD; /* AppMenu key */ +// public static final int KEY_POWER = 0xDE; +// public static final int KEY_SLEEP = 0xDF; + + default: System.out.println("UNKNOWN GLFW KEY CODE: " + glfwKeyCode); + return Keyboard.KEY_NONE; + } + } + + public static int toGlfwKey(int lwjglKeyCode) { + + switch(lwjglKeyCode) { + + case Keyboard.KEY_ESCAPE : return GLFW.GLFW_KEY_ESCAPE; + case Keyboard.KEY_BACK : return GLFW.GLFW_KEY_BACKSPACE; + case Keyboard.KEY_TAB : return GLFW.GLFW_KEY_TAB; + case Keyboard.KEY_RETURN : return GLFW.GLFW_KEY_ENTER; + case Keyboard.KEY_SPACE : return GLFW.GLFW_KEY_SPACE; + + case Keyboard.KEY_LCONTROL : return GLFW.GLFW_KEY_LEFT_CONTROL; + case Keyboard.KEY_LSHIFT : return GLFW.GLFW_KEY_LEFT_SHIFT; + case Keyboard.KEY_LMENU : return GLFW.GLFW_KEY_LEFT_ALT; + case Keyboard.KEY_LMETA : return GLFW.GLFW_KEY_LEFT_SUPER; + + case Keyboard.KEY_RCONTROL : return GLFW.GLFW_KEY_RIGHT_CONTROL; + case Keyboard.KEY_RSHIFT : return GLFW.GLFW_KEY_RIGHT_SHIFT; + case Keyboard.KEY_RMENU : return GLFW.GLFW_KEY_RIGHT_ALT; + case Keyboard.KEY_RMETA : return GLFW.GLFW_KEY_RIGHT_SUPER; + + case Keyboard.KEY_1 : return GLFW.GLFW_KEY_1; + case Keyboard.KEY_2 : return GLFW.GLFW_KEY_2; + case Keyboard.KEY_3 : return GLFW.GLFW_KEY_3; + case Keyboard.KEY_4 : return GLFW.GLFW_KEY_4; + case Keyboard.KEY_5 : return GLFW.GLFW_KEY_5; + case Keyboard.KEY_6 : return GLFW.GLFW_KEY_6; + case Keyboard.KEY_7 : return GLFW.GLFW_KEY_7; + case Keyboard.KEY_8 : return GLFW.GLFW_KEY_8; + case Keyboard.KEY_9 : return GLFW.GLFW_KEY_9; + case Keyboard.KEY_0 : return GLFW.GLFW_KEY_0; + + case Keyboard.KEY_A : return GLFW.GLFW_KEY_A; + case Keyboard.KEY_B : return GLFW.GLFW_KEY_B; + case Keyboard.KEY_C : return GLFW.GLFW_KEY_C; + case Keyboard.KEY_D : return GLFW.GLFW_KEY_D; + case Keyboard.KEY_E : return GLFW.GLFW_KEY_E; + case Keyboard.KEY_F : return GLFW.GLFW_KEY_F; + case Keyboard.KEY_G : return GLFW.GLFW_KEY_G; + case Keyboard.KEY_H : return GLFW.GLFW_KEY_H; + case Keyboard.KEY_I : return GLFW.GLFW_KEY_I; + case Keyboard.KEY_J : return GLFW.GLFW_KEY_J; + case Keyboard.KEY_K : return GLFW.GLFW_KEY_K; + case Keyboard.KEY_L : return GLFW.GLFW_KEY_L; + case Keyboard.KEY_M : return GLFW.GLFW_KEY_M; + case Keyboard.KEY_N : return GLFW.GLFW_KEY_N; + case Keyboard.KEY_O : return GLFW.GLFW_KEY_O; + case Keyboard.KEY_P : return GLFW.GLFW_KEY_P; + case Keyboard.KEY_Q : return GLFW.GLFW_KEY_Q; + case Keyboard.KEY_R : return GLFW.GLFW_KEY_R; + case Keyboard.KEY_S : return GLFW.GLFW_KEY_S; + case Keyboard.KEY_T : return GLFW.GLFW_KEY_T; + case Keyboard.KEY_U : return GLFW.GLFW_KEY_U; + case Keyboard.KEY_V : return GLFW.GLFW_KEY_V; + case Keyboard.KEY_W : return GLFW.GLFW_KEY_W; + case Keyboard.KEY_X : return GLFW.GLFW_KEY_X; + case Keyboard.KEY_Y : return GLFW.GLFW_KEY_Y; + case Keyboard.KEY_Z : return GLFW.GLFW_KEY_Z; + + case Keyboard.KEY_UP : return GLFW.GLFW_KEY_UP; + case Keyboard.KEY_DOWN : return GLFW.GLFW_KEY_DOWN; + case Keyboard.KEY_LEFT : return GLFW.GLFW_KEY_LEFT; + case Keyboard.KEY_RIGHT : return GLFW.GLFW_KEY_RIGHT; + + case Keyboard.KEY_INSERT : return GLFW.GLFW_KEY_INSERT; + case Keyboard.KEY_DELETE : return GLFW.GLFW_KEY_DELETE; + case Keyboard.KEY_HOME : return GLFW.GLFW_KEY_HOME; + case Keyboard.KEY_END : return GLFW.GLFW_KEY_END; + case Keyboard.KEY_PRIOR : return GLFW.GLFW_KEY_PAGE_UP; + case Keyboard.KEY_NEXT : return GLFW.GLFW_KEY_PAGE_DOWN; + + case Keyboard.KEY_F1 : return GLFW.GLFW_KEY_F1; + case Keyboard.KEY_F2 : return GLFW.GLFW_KEY_F2; + case Keyboard.KEY_F3 : return GLFW.GLFW_KEY_F3; + case Keyboard.KEY_F4 : return GLFW.GLFW_KEY_F4; + case Keyboard.KEY_F5 : return GLFW.GLFW_KEY_F5; + case Keyboard.KEY_F6 : return GLFW.GLFW_KEY_F6; + case Keyboard.KEY_F7 : return GLFW.GLFW_KEY_F7; + case Keyboard.KEY_F8 : return GLFW.GLFW_KEY_F8; + case Keyboard.KEY_F9 : return GLFW.GLFW_KEY_F9; + case Keyboard.KEY_F10 : return GLFW.GLFW_KEY_F10; + case Keyboard.KEY_F11 : return GLFW.GLFW_KEY_F11; + case Keyboard.KEY_F12 : return GLFW.GLFW_KEY_F12; + case Keyboard.KEY_F13 : return GLFW.GLFW_KEY_F13; + case Keyboard.KEY_F14 : return GLFW.GLFW_KEY_F14; + case Keyboard.KEY_F15 : return GLFW.GLFW_KEY_F15; + case Keyboard.KEY_F16 : return GLFW.GLFW_KEY_F16; + case Keyboard.KEY_F17 : return GLFW.GLFW_KEY_F17; + case Keyboard.KEY_F18 : return GLFW.GLFW_KEY_F18; + case Keyboard.KEY_F19 : return GLFW.GLFW_KEY_F19; + + case Keyboard.KEY_NUMPAD1 : return GLFW.GLFW_KEY_KP_1; + case Keyboard.KEY_NUMPAD2 : return GLFW.GLFW_KEY_KP_2; + case Keyboard.KEY_NUMPAD3 : return GLFW.GLFW_KEY_KP_3; + case Keyboard.KEY_NUMPAD4 : return GLFW.GLFW_KEY_KP_4; + case Keyboard.KEY_NUMPAD5 : return GLFW.GLFW_KEY_KP_5; + case Keyboard.KEY_NUMPAD6 : return GLFW.GLFW_KEY_KP_6; + case Keyboard.KEY_NUMPAD7 : return GLFW.GLFW_KEY_KP_7; + case Keyboard.KEY_NUMPAD8 : return GLFW.GLFW_KEY_KP_8; + case Keyboard.KEY_NUMPAD9 : return GLFW.GLFW_KEY_KP_9; + case Keyboard.KEY_NUMPAD0 : return GLFW.GLFW_KEY_KP_0; + + case Keyboard.KEY_ADD : return GLFW.GLFW_KEY_KP_ADD; + case Keyboard.KEY_SUBTRACT : return GLFW.GLFW_KEY_KP_SUBTRACT; + case Keyboard.KEY_MULTIPLY : return GLFW.GLFW_KEY_KP_MULTIPLY; + case Keyboard.KEY_DIVIDE : return GLFW.GLFW_KEY_KP_DIVIDE; + case Keyboard.KEY_DECIMAL : return GLFW.GLFW_KEY_KP_DECIMAL; + case Keyboard.KEY_NUMPADEQUALS : return GLFW.GLFW_KEY_KP_EQUAL; + case Keyboard.KEY_NUMPADENTER : return GLFW.GLFW_KEY_KP_ENTER; + case Keyboard.KEY_NUMLOCK : return GLFW.GLFW_KEY_NUM_LOCK; + + case Keyboard.KEY_SEMICOLON : return GLFW.GLFW_KEY_SEMICOLON; + case Keyboard.KEY_BACKSLASH : return GLFW.GLFW_KEY_BACKSLASH; + case Keyboard.KEY_COMMA : return GLFW.GLFW_KEY_COMMA; + case Keyboard.KEY_PERIOD : return GLFW.GLFW_KEY_PERIOD; + case Keyboard.KEY_SLASH : return GLFW.GLFW_KEY_SLASH; + case Keyboard.KEY_GRAVE : return GLFW.GLFW_KEY_GRAVE_ACCENT; + + case Keyboard.KEY_CAPITAL : return GLFW.GLFW_KEY_CAPS_LOCK; + case Keyboard.KEY_SCROLL : return GLFW.GLFW_KEY_SCROLL_LOCK; + + case Keyboard.KEY_PAUSE : return GLFW.GLFW_KEY_PAUSE; + case Keyboard.KEY_CIRCUMFLEX: return GLFW.GLFW_KEY_WORLD_1; // TODO not sure if correct + + case Keyboard.KEY_MINUS : return GLFW.GLFW_KEY_MINUS; + case Keyboard.KEY_EQUALS : return GLFW.GLFW_KEY_EQUAL; + case Keyboard.KEY_LBRACKET : return GLFW.GLFW_KEY_LEFT_BRACKET; + case Keyboard.KEY_RBRACKET : return GLFW.GLFW_KEY_RIGHT_BRACKET; + case Keyboard.KEY_APOSTROPHE: return GLFW.GLFW_KEY_APOSTROPHE; +// public static final int KEY_AT = 0x91; /* (NEC PC98) */ +// public static final int KEY_COLON = 0x92; /* (NEC PC98) */ +// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */ + +// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */ +// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */ +// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */ +// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */ + +// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */ +// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */ +// public static final int KEY_STOP = 0x95; /* (NEC PC98) */ +// public static final int KEY_AX = 0x96; /* (Japan AX) */ +// public static final int KEY_UNLABELED = 0x97; /* (J3100) */ +// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */ +// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */ +// public static final int KEY_SYSRQ = 0xB7; +// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */ + +// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */ + +// public static final int KEY_APPS = 0xDD; /* AppMenu key */ +// public static final int KEY_POWER = 0xDE; +// public static final int KEY_SLEEP = 0xDF; + + default: System.out.println("UNKNOWN LWJGL KEY CODE: " + lwjglKeyCode); + return GLFW.GLFW_KEY_UNKNOWN; + } + } + +} diff --git a/src/main/java/org/lwjglx/input/Keyboard.java b/src/main/java/org/lwjglx/input/Keyboard.java new file mode 100644 index 0000000..78a8038 --- /dev/null +++ b/src/main/java/org/lwjglx/input/Keyboard.java @@ -0,0 +1,292 @@ +package org.lwjglx.input; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +import org.lwjgl.glfw.GLFW; +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; +import org.lwjglx.opengl.Display; + +public class Keyboard { + + /** + * The special character meaning that no + * character was translated for the event. + */ + public static final int CHAR_NONE = '\0'; + + /** + * The special keycode meaning that only the + * translated character is valid. + */ + public static final int KEY_NONE = 0x00; + + public static final int KEY_ESCAPE = 0x01; + public static final int KEY_1 = 0x02; + public static final int KEY_2 = 0x03; + public static final int KEY_3 = 0x04; + public static final int KEY_4 = 0x05; + public static final int KEY_5 = 0x06; + public static final int KEY_6 = 0x07; + public static final int KEY_7 = 0x08; + public static final int KEY_8 = 0x09; + public static final int KEY_9 = 0x0A; + public static final int KEY_0 = 0x0B; + public static final int KEY_MINUS = 0x0C; /* - on main keyboard */ + public static final int KEY_EQUALS = 0x0D; + public static final int KEY_BACK = 0x0E; /* backspace */ + public static final int KEY_TAB = 0x0F; + public static final int KEY_Q = 0x10; + public static final int KEY_W = 0x11; + public static final int KEY_E = 0x12; + public static final int KEY_R = 0x13; + public static final int KEY_T = 0x14; + public static final int KEY_Y = 0x15; + public static final int KEY_U = 0x16; + public static final int KEY_I = 0x17; + public static final int KEY_O = 0x18; + public static final int KEY_P = 0x19; + public static final int KEY_LBRACKET = 0x1A; + public static final int KEY_RBRACKET = 0x1B; + public static final int KEY_RETURN = 0x1C; /* Enter on main keyboard */ + public static final int KEY_LCONTROL = 0x1D; + public static final int KEY_A = 0x1E; + public static final int KEY_S = 0x1F; + public static final int KEY_D = 0x20; + public static final int KEY_F = 0x21; + public static final int KEY_G = 0x22; + public static final int KEY_H = 0x23; + public static final int KEY_J = 0x24; + public static final int KEY_K = 0x25; + public static final int KEY_L = 0x26; + public static final int KEY_SEMICOLON = 0x27; + public static final int KEY_APOSTROPHE = 0x28; + public static final int KEY_GRAVE = 0x29; /* accent grave */ + public static final int KEY_LSHIFT = 0x2A; + public static final int KEY_BACKSLASH = 0x2B; + public static final int KEY_Z = 0x2C; + public static final int KEY_X = 0x2D; + public static final int KEY_C = 0x2E; + public static final int KEY_V = 0x2F; + public static final int KEY_B = 0x30; + public static final int KEY_N = 0x31; + public static final int KEY_M = 0x32; + public static final int KEY_COMMA = 0x33; + public static final int KEY_PERIOD = 0x34; /* . on main keyboard */ + public static final int KEY_SLASH = 0x35; /* / on main keyboard */ + public static final int KEY_RSHIFT = 0x36; + public static final int KEY_MULTIPLY = 0x37; /* * on numeric keypad */ + public static final int KEY_LMENU = 0x38; /* left Alt */ + public static final int KEY_SPACE = 0x39; + public static final int KEY_CAPITAL = 0x3A; + public static final int KEY_F1 = 0x3B; + public static final int KEY_F2 = 0x3C; + public static final int KEY_F3 = 0x3D; + public static final int KEY_F4 = 0x3E; + public static final int KEY_F5 = 0x3F; + public static final int KEY_F6 = 0x40; + public static final int KEY_F7 = 0x41; + public static final int KEY_F8 = 0x42; + public static final int KEY_F9 = 0x43; + public static final int KEY_F10 = 0x44; + public static final int KEY_NUMLOCK = 0x45; + public static final int KEY_SCROLL = 0x46; /* Scroll Lock */ + public static final int KEY_NUMPAD7 = 0x47; + public static final int KEY_NUMPAD8 = 0x48; + public static final int KEY_NUMPAD9 = 0x49; + public static final int KEY_SUBTRACT = 0x4A; /* - on numeric keypad */ + public static final int KEY_NUMPAD4 = 0x4B; + public static final int KEY_NUMPAD5 = 0x4C; + public static final int KEY_NUMPAD6 = 0x4D; + public static final int KEY_ADD = 0x4E; /* + on numeric keypad */ + public static final int KEY_NUMPAD1 = 0x4F; + public static final int KEY_NUMPAD2 = 0x50; + public static final int KEY_NUMPAD3 = 0x51; + public static final int KEY_NUMPAD0 = 0x52; + public static final int KEY_DECIMAL = 0x53; /* . on numeric keypad */ + public static final int KEY_F11 = 0x57; + public static final int KEY_F12 = 0x58; + public static final int KEY_F13 = 0x64; /* (NEC PC98) */ + public static final int KEY_F14 = 0x65; /* (NEC PC98) */ + public static final int KEY_F15 = 0x66; /* (NEC PC98) */ + public static final int KEY_F16 = 0x67; /* Extended Function keys - (Mac) */ + public static final int KEY_F17 = 0x68; + public static final int KEY_F18 = 0x69; + public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */ + public static final int KEY_F19 = 0x71; /* Extended Function keys - (Mac) */ + public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */ + public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */ + public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */ + public static final int KEY_NUMPADEQUALS = 0x8D; /* = on numeric keypad (NEC PC98) */ + public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */ + public static final int KEY_AT = 0x91; /* (NEC PC98) */ + public static final int KEY_COLON = 0x92; /* (NEC PC98) */ + public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */ + public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */ + public static final int KEY_STOP = 0x95; /* (NEC PC98) */ + public static final int KEY_AX = 0x96; /* (Japan AX) */ + public static final int KEY_UNLABELED = 0x97; /* (J3100) */ + public static final int KEY_NUMPADENTER = 0x9C; /* Enter on numeric keypad */ + public static final int KEY_RCONTROL = 0x9D; + public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */ + public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */ + public static final int KEY_DIVIDE = 0xB5; /* / on numeric keypad */ + public static final int KEY_SYSRQ = 0xB7; + public static final int KEY_RMENU = 0xB8; /* right Alt */ + public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */ + public static final int KEY_PAUSE = 0xC5; /* Pause */ + public static final int KEY_HOME = 0xC7; /* Home on arrow keypad */ + public static final int KEY_UP = 0xC8; /* UpArrow on arrow keypad */ + public static final int KEY_PRIOR = 0xC9; /* PgUp on arrow keypad */ + public static final int KEY_LEFT = 0xCB; /* LeftArrow on arrow keypad */ + public static final int KEY_RIGHT = 0xCD; /* RightArrow on arrow keypad */ + public static final int KEY_END = 0xCF; /* End on arrow keypad */ + public static final int KEY_DOWN = 0xD0; /* DownArrow on arrow keypad */ + public static final int KEY_NEXT = 0xD1; /* PgDn on arrow keypad */ + public static final int KEY_INSERT = 0xD2; /* Insert on arrow keypad */ + public static final int KEY_DELETE = 0xD3; /* Delete on arrow keypad */ + public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */ + public static final int KEY_LMETA = 0xDB; /* Left Windows/Option key */ + public static final int KEY_LWIN = KEY_LMETA; /* Left Windows key */ + public static final int KEY_RMETA = 0xDC; /* Right Windows/Option key */ + public static final int KEY_RWIN = KEY_RMETA; /* Right Windows key */ + public static final int KEY_APPS = 0xDD; /* AppMenu key */ + public static final int KEY_POWER = 0xDE; + public static final int KEY_SLEEP = 0xDF; + + + private static EventQueue queue = new EventQueue(32); + //private static int maxEvents = 32; + + //private static int eventCount = 0; + //private static int currentEventPos = -1; + //private static int nextEventPos = 0; + + private static int[] keyEvents = new int[queue.getMaxEvents()]; + private static boolean[] keyEventStates = new boolean[queue.getMaxEvents()]; + private static long[] nanoTimeEvents = new long[queue.getMaxEvents()]; + private static char[] keyEventChars = new char[256]; + + public static final int KEYBOARD_SIZE = 256; + + private static final String[] keyName = new String[KEYBOARD_SIZE]; + private static final Map keyMap = new HashMap(253); + + static { + // Use reflection to find out key names + Field[] fields = Keyboard.class.getFields(); + try { + for ( Field field : fields ) { + if ( Modifier.isStatic(field.getModifiers()) + && Modifier.isPublic(field.getModifiers()) + && Modifier.isFinal(field.getModifiers()) + && field.getType().equals(int.class) + && field.getName().startsWith("KEY_") + && !field.getName().endsWith("WIN") ) { /* Don't use deprecated names */ + + int key = field.getInt(null); + String name = field.getName().substring(4); + keyName[key] = name; + keyMap.put(name, key); + } + + } + } catch (Exception e) { + } + + } + + public static void addKeyEvent(int key, boolean pressed) { + //eventCount++; + //if (eventCount > maxEvents) eventCount = maxEvents; + + keyEvents[queue.getNextPos()] = KeyCodes.toLwjglKey(key); + keyEventStates[queue.getNextPos()] = pressed; + + nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime(); + + queue.add(); + /*nextEventPos++; + if (nextEventPos == maxEvents) nextEventPos = 0; + + if (currentEventPos == nextEventPos) currentEventPos++; + if (currentEventPos == maxEvents) currentEventPos = 0;*/ + } + + public static void addCharEvent(int key, char c) { + int index = KeyCodes.toLwjglKey(key); + keyEventChars[index] = c; + } + + public static void create() throws LWJGLException { + + } + + public static boolean isKeyDown(int key) { + return GLFW.glfwGetKey(Display.getWindow(), KeyCodes.toGlfwKey(key)) == GLFW.GLFW_PRESS; + } + + public static void poll() { + // TODO + } + + public static void enableRepeatEvents(boolean enable) { + // TODO + System.out.println("TODO: Implement Keyboad.enableRepeatEvents(boolean)"); + } + + public static boolean isRepeatEvent() { + // TODO + return false; + } + + public static boolean next() { + return queue.next(); + /*if (eventCount == 0) return false; + + eventCount--; + currentEventPos++; + if (currentEventPos == maxEvents) currentEventPos = 0; + + return true;*/ + } + + public static int getEventKey() { + return keyEvents[queue.getCurrentPos()]; + } + + public static char getEventCharacter() { + return keyEventChars[getEventKey()]; + } + + public static boolean getEventKeyState() { + return keyEventStates[queue.getCurrentPos()]; + } + + public static long getEventNanoseconds() { + return nanoTimeEvents[queue.getCurrentPos()]; + } + + public static String getKeyName(int key) { + return keyName[key]; + } + + public static int getKeyIndex(java.lang.String keyName) { + Integer ret = keyMap.get(keyName); + if (ret == null) + return KEY_NONE; + else + return ret; + } + + public static boolean isCreated() { + return Display.isCreated(); + } + + public static void destroy() { + + } +} diff --git a/src/main/java/org/lwjglx/input/Mouse.java b/src/main/java/org/lwjglx/input/Mouse.java new file mode 100644 index 0000000..33fccf4 --- /dev/null +++ b/src/main/java/org/lwjglx/input/Mouse.java @@ -0,0 +1,183 @@ +package org.lwjglx.input; + +import org.lwjgl.glfw.GLFW; +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; +import org.lwjglx.opengl.Display; + +public class Mouse { + + private static boolean grabbed = false; + + private static int lastX = 0; + private static int lastY = 0; + + private static int latestX = 0; + private static int latestY = 0; + + private static int x = 0; + private static int y = 0; + + private static EventQueue queue = new EventQueue(32); + + private static int[] buttonEvents = new int[queue.getMaxEvents()]; + private static boolean[] buttonEventStates = new boolean[queue.getMaxEvents()]; + private static int[] xEvents = new int[queue.getMaxEvents()]; + private static int[] yEvents = new int[queue.getMaxEvents()]; + private static int[] lastxEvents = new int[queue.getMaxEvents()]; + private static int[] lastyEvents = new int[queue.getMaxEvents()]; + private static long[] nanoTimeEvents = new long[queue.getMaxEvents()]; + + private static boolean clipPostionToDisplay = true; + + public static void addMoveEvent(double mouseX, double mouseY) { + latestX = (int)mouseX; + latestY = Display.getHeight() - (int)mouseY; + + lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()]; + lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()]; + + xEvents[queue.getNextPos()] = latestX; + yEvents[queue.getNextPos()] = latestY; + + buttonEvents[queue.getNextPos()] = -1; + buttonEventStates[queue.getNextPos()] = false; + + nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime(); + + queue.add(); + } + + public static void addButtonEvent(int button, boolean pressed) { + lastxEvents[queue.getNextPos()] = xEvents[queue.getNextPos()]; + lastyEvents[queue.getNextPos()] = yEvents[queue.getNextPos()]; + + xEvents[queue.getNextPos()] = latestX; + yEvents[queue.getNextPos()] = latestY; + + buttonEvents[queue.getNextPos()] = button; + buttonEventStates[queue.getNextPos()] = pressed; + + nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime(); + + queue.add(); + } + + public static void poll() { + lastX = x; + lastY = y; + + if (!grabbed && clipPostionToDisplay) { + if (latestX < 0) latestX = 0; + if (latestY < 0) latestY = 0; + if (latestX > Display.getWidth()-1) latestX = Display.getWidth() - 1; + if (latestY > Display.getHeight()-1) latestY = Display.getHeight() - 1; + } + + x = latestX; + y = latestY; + } + + public static void create() throws LWJGLException { + + } + + public static boolean isCreated() { + return Display.isCreated(); + } + + public static void setGrabbed(boolean grab) { + GLFW.glfwSetInputMode(Display.getWindow(), + GLFW.GLFW_CURSOR, + grab ? GLFW.GLFW_CURSOR_DISABLED : GLFW.GLFW_CURSOR_NORMAL); + grabbed = grab; + } + + public static boolean isGrabbed() { + return grabbed; + } + + public static boolean isButtonDown(int button) { + return GLFW.glfwGetMouseButton(Display.getWindow(), button) == GLFW.GLFW_PRESS; + } + + public static boolean next() { + return queue.next(); + } + + public static int getEventX() { + return xEvents[queue.getCurrentPos()]; + } + + public static int getEventY() { + return yEvents[queue.getCurrentPos()]; + } + + public static int getEventDX() { + return xEvents[queue.getCurrentPos()] - lastxEvents[queue.getCurrentPos()]; + } + + public static int getEventDY() { + return yEvents[queue.getCurrentPos()] - lastyEvents[queue.getCurrentPos()]; + } + + public static long getEventNanoseconds() { + return nanoTimeEvents[queue.getCurrentPos()]; + } + + public static int getEventButton() { + return buttonEvents[queue.getCurrentPos()]; + } + + public static boolean getEventButtonState() { + return buttonEventStates[queue.getCurrentPos()]; + } + + public static int getEventDWheel() { + return 0; // TODO + } + + public static int getX() { + return x; + } + + public static int getY() { + return y; + } + + public static int getDX() { + return x - lastX; + } + + public static int getDY() { + return y - lastY; + } + + public static int getDWheel() { + // TODO + return 0; + } + + public static int getButtonCount() { + return 8; // max mouse buttons supported by GLFW + } + + public static void setClipMouseCoordinatesToWindow(boolean clip) { + clipPostionToDisplay = clip; + } + + public static void setCursorPosition(int new_x, int new_y) { + GLFW.glfwSetCursorPos(Display.getWindow(), new_x, new_y); + } + + public static Cursor setNativeCursor(Cursor cursor) throws LWJGLException { + // TODO + System.out.println("TODO: Implement Mouse.setNativeCursor(Cursor)"); + return null; + } + + public static void destroy() { + + } + +} diff --git a/src/main/java/org/lwjglx/openal/AL.java b/src/main/java/org/lwjglx/openal/AL.java new file mode 100644 index 0000000..74b7e95 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/AL.java @@ -0,0 +1,65 @@ +package org.lwjglx.openal; + +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; +import org.lwjgl.openal.ALContext; +import org.lwjgl.openal.ALDevice; +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; + +public class AL { + + static ALContext alContext; + static ALCdevice alcDevice; + + private static boolean created = false; + + static { + Sys.initialize(); // init using dummy sys method + } + + public static void create() throws LWJGLException { + if (alContext == null) { + ALDevice alDevice = ALDevice.create(); + + IntBuffer attribs = BufferUtils.createIntBuffer(16); + + attribs.put(org.lwjgl.openal.ALC10.ALC_FREQUENCY); + attribs.put(44100); + + attribs.put(org.lwjgl.openal.ALC10.ALC_REFRESH); + attribs.put(60); + + attribs.put(org.lwjgl.openal.ALC10.ALC_SYNC); + attribs.put(org.lwjgl.openal.ALC10.ALC_FALSE); + + attribs.put(0); + attribs.flip(); + + long contextHandle = org.lwjgl.openal.ALC10.alcCreateContext(alDevice.getPointer(), attribs); + + alContext = new ALContext(alDevice, contextHandle); + + alcDevice = new ALCdevice(contextHandle); + + created = true; + } + } + + public static boolean isCreated() { + return created; + } + + public static void destroy() { + org.lwjgl.openal.AL.destroy(alContext); + alContext = null; + alcDevice = null; + created = false; + } + + public static ALCdevice getDevice() { + return alcDevice; + } + +} diff --git a/src/main/java/org/lwjglx/openal/AL10.java b/src/main/java/org/lwjglx/openal/AL10.java new file mode 100644 index 0000000..eb0f972 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/AL10.java @@ -0,0 +1,75 @@ +package org.lwjglx.openal; + +public class AL10 { + + public static final int AL_NO_ERROR = org.lwjgl.openal.AL10.AL_NO_ERROR; + public static final int AL_BUFFER = org.lwjgl.openal.AL10.AL_BUFFER; + public static final int AL_SOURCE_STATE = org.lwjgl.openal.AL10.AL_SOURCE_STATE; + public static final int AL_PLAYING = org.lwjgl.openal.AL10.AL_PLAYING; + public static final int AL_LOOPING = org.lwjgl.openal.AL10.AL_LOOPING; + public static final int AL_TRUE = org.lwjgl.openal.AL10.AL_TRUE; + public static final int AL_REFERENCE_DISTANCE = org.lwjgl.openal.AL10.AL_REFERENCE_DISTANCE; + public static final int AL_ROLLOFF_FACTOR = org.lwjgl.openal.AL10.AL_ROLLOFF_FACTOR; + public static final int AL_POSITION = org.lwjgl.openal.AL10.AL_POSITION; + + public static void alGenBuffers(java.nio.IntBuffer buffers) { + org.lwjgl.openal.AL10.alGenBuffers(buffers); + } + + public static void alGenSources(java.nio.IntBuffer sources) { + org.lwjgl.openal.AL10.alGenSources(sources); + } + + public static void alBufferData(int buffer, int format, java.nio.ByteBuffer data, int freq) { + org.lwjgl.openal.AL10.alBufferData(buffer, format, data, freq); + } + + public static void alSourcei(int source, int pname, int value) { + org.lwjgl.openal.AL10.alSourcei(source, pname, value); + } + + public static int alGetSourcei(int source, int pname) { + return org.lwjgl.openal.AL10.alGetSourcei(source, pname); + } + + public static String alGetString(int pname) { + return org.lwjgl.openal.AL10.alGetString(pname); + } + + public static int alGetError() { + return org.lwjgl.openal.AL10.alGetError(); + } + + public static void alSourcef(int source, int pname, float value) { + org.lwjgl.openal.AL10.alSourcef(source, pname, value); + } + + public static void alSourcePlay(int source) { + org.lwjgl.openal.AL10.alSourcePlay(source); + } + + public static void alSourceStop(java.nio.IntBuffer sources) { + org.lwjgl.openal.AL10.alSourceStop(sources); + } + + public static void alDeleteSources(java.nio.IntBuffer sources) { + org.lwjgl.openal.AL10.alDeleteSources(sources); + } + + public static void alDeleteBuffers(java.nio.IntBuffer buffers) { + org.lwjgl.openal.AL10.alDeleteBuffers(buffers); + } + + public static void alListener3f(int pname, float v1, float v2, float v3) { + org.lwjgl.openal.AL10.alListener3f(pname, v1, v2, v3); + } + + public static void alSource3f(int source, int pname, float v1, float v2, float v3) { + org.lwjgl.openal.AL10.alSource3f(source, pname, v1, v2, v3); + } + + public static void alSourceStop(int source) { + org.lwjgl.openal.AL10.alSourceStop(source); + } + +} diff --git a/src/main/java/org/lwjglx/openal/ALC10.java b/src/main/java/org/lwjglx/openal/ALC10.java new file mode 100644 index 0000000..83dc06e --- /dev/null +++ b/src/main/java/org/lwjglx/openal/ALC10.java @@ -0,0 +1,56 @@ +package org.lwjglx.openal; + +public class ALC10 { + + static ALCcontext alcContext; + + public static final int ALC_FREQUENCY = org.lwjgl.openal.ALC10.ALC_FREQUENCY; + public static final int ALC_REFRESH = org.lwjgl.openal.ALC10.ALC_REFRESH; + public static final int ALC_SYNC = org.lwjgl.openal.ALC10.ALC_SYNC; + public static final int ALC_NO_ERROR = org.lwjgl.openal.ALC10.ALC_NO_ERROR; + public static final int ALC_DEFAULT_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEFAULT_DEVICE_SPECIFIER; + public static final int ALC_DEVICE_SPECIFIER = org.lwjgl.openal.ALC10.ALC_DEVICE_SPECIFIER; + + public static int alcGetError(ALCdevice device) { + if (device == null) { + return org.lwjgl.openal.ALC10.alcGetError(AL.alcDevice.device); + } + + return org.lwjgl.openal.ALC10.alcGetError(device.device); + } + + public static java.lang.String alcGetString(ALCdevice device, int pname) { + if (device == null) { + return org.lwjgl.openal.ALC10.alcGetString(AL.alcDevice.device, pname); + } + + return org.lwjgl.openal.ALC10.alcGetString(device.device, pname); + } + + public static boolean alcIsExtensionPresent(ALCdevice device, java.lang.String extName) { + if (device == null) { + return org.lwjgl.openal.ALC10.alcIsExtensionPresent(AL.alcDevice.device, extName); + } + + return org.lwjgl.openal.ALC10.alcIsExtensionPresent(device.device, extName); + } + + public static ALCcontext alcCreateContext(ALCdevice device, java.nio.IntBuffer attrList) { + long alContextHandle = org.lwjgl.openal.ALC10.alcCreateContext(device.device, attrList); + alcContext = new ALCcontext(alContextHandle); + return alcContext; + } + + public static ALCcontext alcGetCurrentContext() { + return alcContext; + } + + public static ALCdevice alcGetContextsDevice(ALCcontext context) { + return AL.alcDevice; + } + + public static void alcGetInteger(ALCdevice device, int pname, java.nio.IntBuffer integerdata) { + org.lwjgl.openal.ALC10.alcGetInteger(device.device, pname, integerdata); + } + +} diff --git a/src/main/java/org/lwjglx/openal/ALCcontext.java b/src/main/java/org/lwjglx/openal/ALCcontext.java new file mode 100644 index 0000000..3582e8e --- /dev/null +++ b/src/main/java/org/lwjglx/openal/ALCcontext.java @@ -0,0 +1,115 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.openal; + +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; + +/** + * The ALCcontext class represents a context opened in OpenAL space. + * + * All operations of the AL core API affect a current AL context. Within the scope of AL, + * the ALC is implied - it is not visible as a handle or function parameter. Only one AL + * Context per process can be current at a time. Applications maintaining multiple AL + * Contexts, whether threaded or not, have to set the current context accordingly. + * Applications can have multiple threads that share one more or contexts. In other words, + * AL and ALC are threadsafe. + * + * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +public final class ALCcontext { + + /** Address of actual context */ + final long context; + + /** Whether this context is valid */ + private boolean valid; + + /** + * Creates a new instance of ALCcontext + * + * @param context address of actual context + */ + ALCcontext(long context) { + this.context = context; + this.valid = true; + } + + /* + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object context) { + if(context instanceof ALCcontext) { + return ((ALCcontext)context).context == this.context; + } + return super.equals(context); + } + + /** + * Creates an attribute list in a ByteBuffer + * @param contextFrequency Frequency to add + * @param contextRefresh Refresh rate to add + * @param contextSynchronized Whether to synchronize the context + * @return + */ + static IntBuffer createAttributeList(int contextFrequency, int contextRefresh, int contextSynchronized) { + IntBuffer attribList = BufferUtils.createIntBuffer(7); + + attribList.put(ALC10.ALC_FREQUENCY); + attribList.put(contextFrequency); + attribList.put(ALC10.ALC_REFRESH); + attribList.put(contextRefresh); + attribList.put(ALC10.ALC_SYNC); + attribList.put(contextSynchronized); + attribList.put(0); //terminating int + + return attribList; + } + + /** + * Marks this context as invalid + * + */ + void setInvalid() { + valid = false; + } + + /** + * @return true if this context is still valid + */ + public boolean isValid() { + return valid; + } +} diff --git a/src/main/java/org/lwjglx/openal/ALCdevice.java b/src/main/java/org/lwjglx/openal/ALCdevice.java new file mode 100644 index 0000000..d8822f3 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/ALCdevice.java @@ -0,0 +1,121 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.openal; + +import java.util.HashMap; + +/** + * The ALCdevice class represents a device opened in OpenAL space. + * + * ALC introduces the notion of a Device. A Device can be, depending on the + * implementation, a hardware device, or a daemon/OS service/actual server. This + * mechanism also permits different drivers (and hardware) to coexist within the same + * system, as well as allowing several applications to share system resources for audio, + * including a single hardware output device. The details are left to the implementation, + * which has to map the available backends to unique device specifiers. + * + * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +public final class ALCdevice { + + /** Address of actual device */ + final long device; + + /** Whether this device is valid */ + private boolean valid; + + /** List of contexts belonging to the device */ + private final HashMap contexts = new HashMap(); + + /** + * Creates a new instance of ALCdevice + * + * @param device address of actual device + */ + ALCdevice(long device) { + this.device = device; + this.valid = true; + } + + /* + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object device) { + if(device instanceof ALCdevice) { + return ((ALCdevice)device).device == this.device; + } + return super.equals(device); + } + + /** + * Adds a context to the device + * + * @param context context to add to the list of contexts for this device + */ + void addContext(ALCcontext context) { + synchronized (contexts) { + contexts.put(context.context, context); + } + } + + /** + * Remove context associated with device + * + * @param context Context to disassociate with device + */ + void removeContext(ALCcontext context) { + synchronized (contexts) { + contexts.remove(context.context); + } + } + + /** + * Marks this device and all of its contexts invalid + */ + void setInvalid() { + valid = false; + synchronized (contexts) { + for ( ALCcontext context : contexts.values() ) + context.setInvalid(); + } + contexts.clear(); + } + + /** + * @return true if this device is still valid + */ + public boolean isValid() { + return valid; + } +} diff --git a/src/main/java/org/lwjglx/openal/EFX10.java b/src/main/java/org/lwjglx/openal/EFX10.java new file mode 100644 index 0000000..9fb489a --- /dev/null +++ b/src/main/java/org/lwjglx/openal/EFX10.java @@ -0,0 +1,143 @@ +package org.lwjglx.openal; + +import java.nio.IntBuffer; + +import org.lwjgl.openal.EXTEfx; + +public class EFX10 { + + public static final int AL_EFFECT_TYPE = EXTEfx.AL_EFFECT_TYPE; + public static final int AL_EFFECTSLOT_EFFECT = EXTEfx.AL_EFFECTSLOT_EFFECT; + public static final int AL_EFFECT_ECHO = EXTEfx.AL_EFFECT_ECHO; + public static final float AL_ECHO_MIN_DAMPING = EXTEfx.AL_ECHO_MIN_DAMPING; + public static final int AL_ECHO_DAMPING = EXTEfx.AL_ECHO_DAMPING; + public static final float AL_ECHO_MAX_DAMPING = EXTEfx.AL_ECHO_MAX_DAMPING; + public static final float AL_ECHO_MIN_DELAY = EXTEfx.AL_ECHO_MIN_DELAY; + public static final int AL_ECHO_DELAY = EXTEfx.AL_ECHO_DELAY; + public static final float AL_ECHO_MAX_DELAY = EXTEfx.AL_ECHO_MAX_DELAY; + public static final float AL_ECHO_MIN_FEEDBACK = EXTEfx.AL_ECHO_MIN_FEEDBACK; + public static final int AL_ECHO_FEEDBACK = EXTEfx.AL_ECHO_FEEDBACK; + public static final float AL_ECHO_MAX_FEEDBACK = EXTEfx.AL_ECHO_MAX_FEEDBACK; + public static final float AL_ECHO_MIN_LRDELAY = EXTEfx.AL_ECHO_MIN_LRDELAY; + public static final int AL_ECHO_LRDELAY = EXTEfx.AL_ECHO_LRDELAY; + public static final float AL_ECHO_MAX_LRDELAY = EXTEfx.AL_ECHO_MAX_LRDELAY; + public static final float AL_ECHO_MIN_SPREAD = EXTEfx.AL_ECHO_MIN_SPREAD; + public static final int AL_ECHO_SPREAD = EXTEfx.AL_ECHO_SPREAD; + public static final float AL_ECHO_MAX_SPREAD = EXTEfx.AL_ECHO_MAX_SPREAD; + public static final int AL_EFFECT_REVERB = EXTEfx.AL_EFFECT_REVERB; + public static final int AL_RING_MODULATOR_SINUSOID = EXTEfx.AL_RING_MODULATOR_SINUSOID; + public static final int AL_RING_MODULATOR_SAWTOOTH = EXTEfx.AL_RING_MODULATOR_SAWTOOTH; + public static final int AL_RING_MODULATOR_SQUARE = EXTEfx.AL_RING_MODULATOR_SQUARE; + public static final int AL_EFFECT_RING_MODULATOR = EXTEfx.AL_EFFECT_RING_MODULATOR; + public static final float AL_RING_MODULATOR_MAX_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MAX_FREQUENCY; + public static final int AL_RING_MODULATOR_FREQUENCY = EXTEfx.AL_RING_MODULATOR_FREQUENCY; + public static final float AL_RING_MODULATOR_MIN_FREQUENCY = EXTEfx.AL_RING_MODULATOR_MIN_FREQUENCY; + public static final float AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF; + public static final int AL_RING_MODULATOR_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_HIGHPASS_CUTOFF; + public static final float AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF = EXTEfx.AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF; + public static final int AL_RING_MODULATOR_WAVEFORM = EXTEfx.AL_RING_MODULATOR_WAVEFORM; + public static final int AL_FILTER_TYPE = EXTEfx.AL_FILTER_TYPE; + public static final int AL_FILTER_LOWPASS = EXTEfx.AL_FILTER_LOWPASS; + public static final int AL_LOWPASS_GAIN = EXTEfx.AL_LOWPASS_GAIN; + public static final int AL_LOWPASS_GAINHF = EXTEfx.AL_LOWPASS_GAINHF; + public static final int AL_EFFECTSLOT_NULL = EXTEfx.AL_EFFECTSLOT_NULL; + public static final int AL_FILTER_NULL = EXTEfx.AL_FILTER_NULL; + public static final int AL_AUXILIARY_SEND_FILTER = EXTEfx.AL_AUXILIARY_SEND_FILTER; + public static final int AL_DIRECT_FILTER = EXTEfx.AL_DIRECT_FILTER; + public static final int ALC_MAX_AUXILIARY_SENDS = EXTEfx.ALC_MAX_AUXILIARY_SENDS; + public static final int ALC_EFX_MAJOR_VERSION = EXTEfx.ALC_EFX_MAJOR_VERSION; + public static final int AL_REVERB_DECAY_TIME = EXTEfx.AL_REVERB_DECAY_TIME; + public static final int AL_FILTER_HIGHPASS = EXTEfx.AL_FILTER_HIGHPASS; + public static final int AL_FILTER_BANDPASS = EXTEfx.AL_FILTER_BANDPASS; + public static final int AL_EFFECT_NULL = EXTEfx.AL_EFFECT_NULL; + public static final int AL_EFFECT_EAXREVERB = EXTEfx.AL_EFFECT_EAXREVERB; + public static final int AL_EFFECT_CHORUS = EXTEfx.AL_EFFECT_CHORUS; + public static final int AL_EFFECT_DISTORTION = EXTEfx.AL_EFFECT_DISTORTION; + public static final int AL_EFFECT_FLANGER = EXTEfx.AL_EFFECT_FLANGER; + public static final int AL_EFFECT_FREQUENCY_SHIFTER = EXTEfx.AL_EFFECT_FREQUENCY_SHIFTER; + public static final int AL_EFFECT_VOCAL_MORPHER = EXTEfx.AL_EFFECT_VOCAL_MORPHER; + public static final int AL_EFFECT_PITCH_SHIFTER = EXTEfx.AL_EFFECT_PITCH_SHIFTER; + public static final int AL_EFFECT_AUTOWAH = EXTEfx.AL_EFFECT_AUTOWAH; + public static final int AL_EFFECT_COMPRESSOR = EXTEfx.AL_EFFECT_COMPRESSOR; + public static final int AL_EFFECT_EQUALIZER = EXTEfx.AL_EFFECT_EQUALIZER; + + public static int alGenAuxiliaryEffectSlots() { + return EXTEfx.alGenAuxiliaryEffectSlots(); + } + + public static int alGenFilters() { + return EXTEfx.alGenFilters(); + } + + public static void alDeleteFilters(int filter) { + EXTEfx.alDeleteFilters(filter); + } + + public static void alFilteri(int filter, int param, int value) { + EXTEfx.alFilteri(filter, param, value); + } + + public static void alFilterf(int filter, int param, float value) { + EXTEfx.alFilterf(filter, param, value); + } + + public static float alGetFilterf(int filter, int param) { + return EXTEfx.alGetFilterf(filter, param); + } + + public static int alGenEffects() { + return EXTEfx.alGenEffects(); + } + + public static void alDeleteEffects(int effect) { + EXTEfx.alDeleteAuxiliaryEffectSlots(effect); + } + + public static void alDeleteAuxiliaryEffectSlots(int effectSlot) { + EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlot); + } + + public static void alEffecti(int effect, int param, int value) { + EXTEfx.alEffecti(effect, param, value); + } + + public static float alGetEffectf(int effect, int param) { + return EXTEfx.alGetEffectf(effect, param); + } + + public static int alGetEffecti(int effect, int param) { + return EXTEfx.alGetEffecti(effect, param); + } + + public static void alEffectf(int effect, int param, float value) { + EXTEfx.alEffectf(effect, param, value); + } + + public static void alAuxiliaryEffectSloti(int effectSlot, int param, int value) { + EXTEfx.alAuxiliaryEffectSloti(effectSlot, param, value); + } + + public static void alGenAuxiliaryEffectSlots(IntBuffer effectSlots) { + EXTEfx.alGenAuxiliaryEffectSlots(effectSlots); + } + + public static void alGenEffects(IntBuffer effects) { + EXTEfx.alGenEffects(effects); + } + + public static void alDeleteEffects(IntBuffer effects) { + EXTEfx.alDeleteEffects(effects); + } + + public static void alDeleteAuxiliaryEffectSlots(IntBuffer effectSlots) { + EXTEfx.alDeleteAuxiliaryEffectSlots(effectSlots); + } + + public static void alGenFilters(IntBuffer filters) { + EXTEfx.alGenFilters(filters); + } + + public static void alDeleteFilters(IntBuffer filters) { + EXTEfx.alDeleteFilters(filters); + } +} diff --git a/src/main/java/org/lwjglx/openal/EFXUtil.java b/src/main/java/org/lwjglx/openal/EFXUtil.java new file mode 100644 index 0000000..08faf29 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/EFXUtil.java @@ -0,0 +1,208 @@ +/* + * Copyright LWJGL. All rights reserved. + * License terms: http://lwjgl.org/license.php + */ +package org.lwjglx.openal; + +import static org.lwjgl.openal.AL10.*; +import static org.lwjgl.openal.EXTEfx.*; + +import org.lwjgl.openal.ALC; + +/** + * Utility class for the OpenAL extension AL_EXT_EFX. Provides functions to check for the extension + * and support of various effects and filters. + *

+ * Currently supports AL_EXT_EFX version 1.0 effects and filters. + * + * @author Ciardhubh + */ +public final class EFXUtil { + + /** Constant for testSupportGeneric to check an effect. */ + private static final int EFFECT = 1111; + /** Constant for testSupportGeneric to check a filter. */ + private static final int FILTER = 2222; + + /** Utility class, hidden contructor. */ + private EFXUtil() { + } + + /** + * Checks if OpenAL implementation is loaded and supports AL_EXT_EFX. + * + * @return True if AL_EXT_EFX is supported, false if not. + * + * @throws org.lwjgl.openal.OpenALException + * If OpenAL has not been created yet. + */ + public static boolean isEfxSupported() { + return ALC.getCapabilities().ALC_EXT_EFX; + } + + /** + * Tests OpenAL to see whether the given effect type is supported. This is done by creating an + * effect of the given type. If creation succeeds the effect is supported. + * + * @param effectType Type of effect whose support is to be tested, e.g. AL_EFFECT_REVERB. + * + * @return True if it is supported, false if not. + * + * @throws org.lwjgl.openal.OpenALException + * If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has + * not been created yet. + * @throws IllegalArgumentException effectType is not a valid effect type. + */ + public static boolean isEffectSupported(int effectType) { + // Make sure type is a real effect. + switch ( effectType ) { + case AL_EFFECT_NULL: + case AL_EFFECT_EAXREVERB: + case AL_EFFECT_REVERB: + case AL_EFFECT_CHORUS: + case AL_EFFECT_DISTORTION: + case AL_EFFECT_ECHO: + case AL_EFFECT_FLANGER: + case AL_EFFECT_FREQUENCY_SHIFTER: + case AL_EFFECT_VOCAL_MORPHER: + case AL_EFFECT_PITCH_SHIFTER: + case AL_EFFECT_RING_MODULATOR: + case AL_EFFECT_AUTOWAH: + case AL_EFFECT_COMPRESSOR: + case AL_EFFECT_EQUALIZER: + break; + default: + throw new IllegalArgumentException("Unknown or invalid effect type: " + effectType); + } + + return testSupportGeneric(EFFECT, effectType); + } + + /** + * Tests OpenAL to see whether the given filter type is supported. This is done by creating a + * filter of the given type. If creation succeeds the filter is supported. + * + * @param filterType Type of filter whose support is to be tested, e.g. AL_FILTER_LOWPASS. + * + * @return True if it is supported, false if not. + * + * @throws org.lwjgl.openal.OpenALException + * If the request fails due to an AL_OUT_OF_MEMORY error or OpenAL has + * not been created yet. + * @throws IllegalArgumentException filterType is not a valid filter type. + */ + public static boolean isFilterSupported(int filterType) { + // Make sure type is a real filter. + switch ( filterType ) { + case AL_FILTER_NULL: + case AL_FILTER_LOWPASS: + case AL_FILTER_HIGHPASS: + case AL_FILTER_BANDPASS: + break; + default: + throw new IllegalArgumentException("Unknown or invalid filter type: " + filterType); + } + + return testSupportGeneric(FILTER, filterType); + } + + /** + * Generic test function to see if an EFX object supports a given kind of type. Works for + * effects and filters. + * + * @param objectType Type of object to test. Must be either EFXUtil.EFFECT or EFXUtil.FILTER. + * @param typeValue OpenAL type the object should be tested for support, e.g. AL_FILTER_LOWPASS + * or AL_EFFECT_REVERB. + * + * @return True if object supports typeValue, false else. + */ + private static boolean testSupportGeneric(int objectType, int typeValue) { + // Check for supported objectType. + switch ( objectType ) { + case EFFECT: + case FILTER: + break; + default: + throw new IllegalArgumentException("Invalid objectType: " + objectType); + } + + boolean supported = false; + if ( isEfxSupported() ) { + + // Try to create object in order to check AL's response. + alGetError(); + int genError; + int testObject = 0; + try { + switch ( objectType ) { // Create object based on type + case EFFECT: + testObject = alGenEffects(); + break; + case FILTER: + testObject = alGenFilters(); + break; + default: + throw new IllegalArgumentException("Invalid objectType: " + objectType); + } + genError = alGetError(); + } catch (OpenALException debugBuildException) { + // Hack because OpenALException hides the original error code (short of parsing the + // error message String which would break if it gets changed). + if ( debugBuildException.getMessage().contains("AL_OUT_OF_MEMORY") ) { + genError = AL_OUT_OF_MEMORY; + } else { + genError = AL_INVALID_OPERATION; + } + } + + if ( genError == AL_NO_ERROR ) { + // Successfully created, now try to set type. + alGetError(); + int setError; + try { + switch ( objectType ) { // Set based on object type + case EFFECT: + alEffecti(testObject, AL_EFFECT_TYPE, typeValue); + break; + case FILTER: + alFilteri(testObject, AL_FILTER_TYPE, typeValue); + break; + default: + throw new IllegalArgumentException("Invalid objectType: " + objectType); + } + setError = alGetError(); + } catch (OpenALException debugBuildException) { + // Hack because OpenALException hides the original error code (short of parsing + // the error message String which would break when it gets changed). + setError = AL_INVALID_VALUE; + } + + if ( setError == AL_NO_ERROR ) { + supported = true; + } + + // Cleanup + try { + switch ( objectType ) { // Set based on object type + case EFFECT: + alDeleteEffects(testObject); + break; + case FILTER: + alDeleteFilters(testObject); + break; + default: + throw new IllegalArgumentException("Invalid objectType: " + objectType); + } + } catch (OpenALException debugBuildException) { + // Don't care about cleanup errors. + } + + } else if ( genError == AL_OUT_OF_MEMORY ) { + throw new OpenALException(AL10.alGetString(genError)); + } + } + + return supported; + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/openal/OpenALException.java b/src/main/java/org/lwjglx/openal/OpenALException.java new file mode 100644 index 0000000..a2642a9 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/OpenALException.java @@ -0,0 +1,85 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.openal; + +/** + *
+ * Thrown by the debug build library of the LWJGL if any OpenAL operation + * causes an error. + * + * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +public class OpenALException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor for OpenALException. + */ + public OpenALException() { + super(); + } + + /** + * Constructor that takes an AL error number + */ + public OpenALException(int error_code) { + super("OpenAL error: " + org.lwjgl.openal.AL10.alGetString(error_code) + " (" + error_code + ")"); + } + + /** + * Constructor for OpenALException. + * @param message + */ + public OpenALException(String message) { + super(message); + } + + /** + * Constructor for OpenALException. + * @param message + * @param cause + */ + public OpenALException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor for OpenALException. + * @param cause + */ + public OpenALException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/org/lwjglx/openal/Util.java b/src/main/java/org/lwjglx/openal/Util.java new file mode 100644 index 0000000..9b03ce1 --- /dev/null +++ b/src/main/java/org/lwjglx/openal/Util.java @@ -0,0 +1,86 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.openal; + + +/** + * Simple utility class for checking AL/ALC errors + * + * @author cix_foo + * @author Brian Matzon + * @version $Revision$ + */ + +public final class Util { + /** No c'tor */ + private Util() { + } + + /** + * Checks for any ALC errors and throws an unchecked exception on errors + * @param device Device for which to check ALC errors + */ + public static void checkALCError(ALCdevice device) { + int err = ALC10.alcGetError(device); + if (err != ALC10.ALC_NO_ERROR) + throw new OpenALException(ALC10.alcGetString(AL.getDevice(), err)); + } + + /** + * Checks for any AL errors and throws an unchecked exception on errors + */ + public static void checkALError() { + int err = AL10.alGetError(); + if (err != AL10.AL_NO_ERROR) + throw new OpenALException(err); + } + + /** + * Checks for a valid device + * @param device ALCdevice to check the validity of + */ + public static void checkALCValidDevice(ALCdevice device) { + if(!device.isValid()) { + throw new OpenALException("Invalid device: " + device); + } + } + + /** + * Checks for a valid context + * @param context ALCcontext to check the validity of + */ + public static void checkALCValidContext(ALCcontext context) { + if(!context.isValid()) { + throw new OpenALException("Invalid context: " + context); + } + } +} diff --git a/src/main/java/org/lwjglx/opengl/AWTGLCanvas.java b/src/main/java/org/lwjglx/opengl/AWTGLCanvas.java new file mode 100644 index 0000000..bc07278 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/AWTGLCanvas.java @@ -0,0 +1,195 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; +import org.lwjglx.PointerBuffer; + +import java.awt.*; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; + +public class AWTGLCanvas extends Canvas implements Drawable, ComponentListener, HierarchyListener { + + private static final long serialVersionUID = 1L; + + public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException { + throw new UnsupportedOperationException(); + } + + public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException { + throw new UnsupportedOperationException(); + } + + public PixelFormatLWJGL getPixelFormat() { + return null; + } + + public ContextGL getContext() { + return null; + } + + public ContextGL createSharedContext() throws LWJGLException { + return null; + } + + public void checkGLError() { + + } + + public void initContext(final float r, final float g, final float b) { + + } + + public AWTGLCanvas() throws LWJGLException { + + } + + public AWTGLCanvas(PixelFormat pixel_format) throws LWJGLException { + + } + + public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException { + + } + + public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable) throws LWJGLException { + + } + + public AWTGLCanvas(GraphicsDevice device, PixelFormat pixel_format, Drawable drawable, ContextAttribs attribs) throws LWJGLException { + + } + + public void addNotify() { + + } + + public void removeNotify() { + + } + + public void setSwapInterval(int swap_interval) { + + } + + public void setVSyncEnabled(boolean enabled) { + + } + + public void swapBuffers() throws LWJGLException { + + } + + public boolean isCurrent() throws LWJGLException { + return false; + } + + public void makeCurrent() throws LWJGLException { + + } + + public void releaseContext() throws LWJGLException { + + } + + public final void destroy() { + + } + + public final void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException { + + } + + protected void initGL() { + + } + + protected void paintGL() { + + } + + public final void paint(Graphics g) { + + } + + protected void exceptionOccurred(LWJGLException exception) { + + } + + public void update(Graphics g) { + + } + + public void componentShown(ComponentEvent e) { + + } + + public void componentHidden(ComponentEvent e) { + + } + + public void componentResized(ComponentEvent e) { + + } + + public void componentMoved(ComponentEvent e) { + + } + + public void setLocation(int x, int y) { + + } + + public void setLocation(Point p) { + + } + + public void setSize(Dimension d) { + + } + + public void setSize(int width, int height) { + + } + + public void setBounds(int x, int y, int width, int height) { + + } + + public void hierarchyChanged(HierarchyEvent e) { + + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/Context.java b/src/main/java/org/lwjglx/opengl/Context.java new file mode 100644 index 0000000..1896a3b --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Context.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2002-2011 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; + +/** + * @author Spasi + * @since 14/5/2011 + */ +interface Context { + + boolean isCurrent() throws LWJGLException; + + void makeCurrent() throws LWJGLException; + + void releaseCurrent() throws LWJGLException; + + void releaseDrawable() throws LWJGLException; + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/ContextAttribs.java b/src/main/java/org/lwjglx/opengl/ContextAttribs.java new file mode 100644 index 0000000..f57be2e --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/ContextAttribs.java @@ -0,0 +1,112 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +public final class ContextAttribs { + + public ContextAttribs() { + + } + + public ContextAttribs(final int majorVersion, final int minorVersion) { + + } + + public int getMajorVersion() { + return 0; + } + + public int getMinorVersion() { + return 0; + } + + public int getLayerPlane() { + return 0; + } + + public boolean isDebug() { + return false; + } + + public boolean isForwardCompatible() { + return false; + } + + public boolean isProfileCore() { + return false; + } + + public boolean isProfileCompatibility() { + return false; + } + + public boolean isProfileES() { + return false; + } + + public ContextAttribs withLayer(final int layerPlane) { + return null; + } + + public ContextAttribs withDebug(final boolean debug) { + return null; + } + + public ContextAttribs withForwardCompatible(final boolean forwardCompatible) { + return null; + } + + public ContextAttribs withProfileCore(final boolean profileCore) { + return null; + } + + public ContextAttribs withProfileCompatibility(final boolean profileCompatibility) { + return null; + } + + public ContextAttribs withProfileES(final boolean profileES) { + return null; + } + + public ContextAttribs withLoseContextOnReset(final boolean loseContextOnReset) { + return null; + } + + public ContextAttribs withContextResetIsolation(final boolean contextResetIsolation) { + return null; + } + + public String toString() { + return null; + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/ContextCapabilities.java b/src/main/java/org/lwjglx/opengl/ContextCapabilities.java new file mode 100644 index 0000000..feacd01 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/ContextCapabilities.java @@ -0,0 +1,402 @@ +package org.lwjglx.opengl; + +import java.lang.reflect.Field; + +public class ContextCapabilities { + + org.lwjgl.opengl.ContextCapabilities cap = org.lwjgl.opengl.GLContext.createFromCurrent().getCapabilities(); + + public ContextCapabilities() { + + Field[] fields = org.lwjgl.opengl.ContextCapabilities.class.getFields(); + + try { + for ( Field field : fields ) { + + String name = field.getName(); + + if (name.startsWith("GL_") || name.startsWith("OpenGL")) { + + boolean value = field.getBoolean(cap); + + try { + Field f = this.getClass().getField(name); + f.setBoolean(this, value); + } catch (Exception e) { + } + } + } + } catch (Exception e) { + System.out.println(e); + } + } + + public boolean GL_AMD_blend_minmax_factor; + public boolean GL_AMD_conservative_depth; + public boolean GL_AMD_debug_output; + public boolean GL_AMD_depth_clamp_separate; + public boolean GL_AMD_draw_buffers_blend; + public boolean GL_AMD_interleaved_elements; + public boolean GL_AMD_multi_draw_indirect; + public boolean GL_AMD_name_gen_delete; + public boolean GL_AMD_performance_monitor; + public boolean GL_AMD_pinned_memory; + public boolean GL_AMD_query_buffer_object; + public boolean GL_AMD_sample_positions; + public boolean GL_AMD_seamless_cubemap_per_texture; + public boolean GL_AMD_shader_atomic_counter_ops; + public boolean GL_AMD_shader_stencil_export; + public boolean GL_AMD_shader_trinary_minmax; + public boolean GL_AMD_sparse_texture; + public boolean GL_AMD_stencil_operation_extended; + public boolean GL_AMD_texture_texture4; + public boolean GL_AMD_transform_feedback3_lines_triangles; + public boolean GL_AMD_vertex_shader_layer; + public boolean GL_AMD_vertex_shader_tessellator; + public boolean GL_AMD_vertex_shader_viewport_index; + public boolean GL_APPLE_aux_depth_stencil; + public boolean GL_APPLE_client_storage; + public boolean GL_APPLE_element_array; + public boolean GL_APPLE_fence; + public boolean GL_APPLE_float_pixels; + public boolean GL_APPLE_flush_buffer_range; + public boolean GL_APPLE_object_purgeable; + public boolean GL_APPLE_packed_pixels; + public boolean GL_APPLE_rgb_422; + public boolean GL_APPLE_row_bytes; + public boolean GL_APPLE_texture_range; + public boolean GL_APPLE_vertex_array_object; + public boolean GL_APPLE_vertex_array_range; + public boolean GL_APPLE_vertex_program_evaluators; + public boolean GL_APPLE_ycbcr_422; + public boolean GL_ARB_ES2_compatibility; + public boolean GL_ARB_ES3_compatibility; + public boolean GL_ARB_arrays_of_arrays; + public boolean GL_ARB_base_instance; + public boolean GL_ARB_bindless_texture; + public boolean GL_ARB_blend_func_extended; + public boolean GL_ARB_buffer_storage; + public boolean GL_ARB_cl_event; + public boolean GL_ARB_clear_buffer_object; + public boolean GL_ARB_clear_texture; + public boolean GL_ARB_color_buffer_float; + public boolean GL_ARB_compatibility; + public boolean GL_ARB_compressed_texture_pixel_storage; + public boolean GL_ARB_compute_shader; + public boolean GL_ARB_compute_variable_group_size; + public boolean GL_ARB_conservative_depth; + public boolean GL_ARB_copy_buffer; + public boolean GL_ARB_copy_image; + public boolean GL_ARB_debug_output; + public boolean GL_ARB_depth_buffer_float; + public boolean GL_ARB_depth_clamp; + public boolean GL_ARB_depth_texture; + public boolean GL_ARB_draw_buffers; + public boolean GL_ARB_draw_buffers_blend; + public boolean GL_ARB_draw_elements_base_vertex; + public boolean GL_ARB_draw_indirect; + public boolean GL_ARB_draw_instanced; + public boolean GL_ARB_enhanced_layouts; + public boolean GL_ARB_explicit_attrib_location; + public boolean GL_ARB_explicit_uniform_location; + public boolean GL_ARB_fragment_coord_conventions; + public boolean GL_ARB_fragment_layer_viewport; + public boolean GL_ARB_fragment_program; + public boolean GL_ARB_fragment_program_shadow; + public boolean GL_ARB_fragment_shader; + public boolean GL_ARB_framebuffer_no_attachments; + public boolean GL_ARB_framebuffer_object; + public boolean GL_ARB_framebuffer_sRGB; + public boolean GL_ARB_geometry_shader4; + public boolean GL_ARB_get_program_binary; + public boolean GL_ARB_gpu_shader5; + public boolean GL_ARB_gpu_shader_fp64; + public boolean GL_ARB_half_float_pixel; + public boolean GL_ARB_half_float_vertex; + public boolean GL_ARB_imaging; + public boolean GL_ARB_indirect_parameters; + public boolean GL_ARB_instanced_arrays; + public boolean GL_ARB_internalformat_query; + public boolean GL_ARB_internalformat_query2; + public boolean GL_ARB_invalidate_subdata; + public boolean GL_ARB_map_buffer_alignment; + public boolean GL_ARB_map_buffer_range; + public boolean GL_ARB_matrix_palette; + public boolean GL_ARB_multi_bind; + public boolean GL_ARB_multi_draw_indirect; + public boolean GL_ARB_multisample; + public boolean GL_ARB_multitexture; + public boolean GL_ARB_occlusion_query; + public boolean GL_ARB_occlusion_query2; + public boolean GL_ARB_pixel_buffer_object; + public boolean GL_ARB_point_parameters; + public boolean GL_ARB_point_sprite; + public boolean GL_ARB_program_interface_query; + public boolean GL_ARB_provoking_vertex; + public boolean GL_ARB_query_buffer_object; + public boolean GL_ARB_robust_buffer_access_behavior; + public boolean GL_ARB_robustness; + public boolean GL_ARB_robustness_isolation; + public boolean GL_ARB_sample_shading; + public boolean GL_ARB_sampler_objects; + public boolean GL_ARB_seamless_cube_map; + public boolean GL_ARB_seamless_cubemap_per_texture; + public boolean GL_ARB_separate_shader_objects; + public boolean GL_ARB_shader_atomic_counters; + public boolean GL_ARB_shader_bit_encoding; + public boolean GL_ARB_shader_draw_parameters; + public boolean GL_ARB_shader_group_vote; + public boolean GL_ARB_shader_image_load_store; + public boolean GL_ARB_shader_image_size; + public boolean GL_ARB_shader_objects; + public boolean GL_ARB_shader_precision; + public boolean GL_ARB_shader_stencil_export; + public boolean GL_ARB_shader_storage_buffer_object; + public boolean GL_ARB_shader_subroutine; + public boolean GL_ARB_shader_texture_lod; + public boolean GL_ARB_shading_language_100; + public boolean GL_ARB_shading_language_420pack; + public boolean GL_ARB_shading_language_include; + public boolean GL_ARB_shading_language_packing; + public boolean GL_ARB_shadow; + public boolean GL_ARB_shadow_ambient; + public boolean GL_ARB_sparse_texture; + public boolean GL_ARB_stencil_texturing; + public boolean GL_ARB_sync; + public boolean GL_ARB_tessellation_shader; + public boolean GL_ARB_texture_border_clamp; + public boolean GL_ARB_texture_buffer_object; + public boolean GL_ARB_texture_buffer_object_rgb32; + public boolean GL_ARB_texture_buffer_range; + public boolean GL_ARB_texture_compression; + public boolean GL_ARB_texture_compression_bptc; + public boolean GL_ARB_texture_compression_rgtc; + public boolean GL_ARB_texture_cube_map; + public boolean GL_ARB_texture_cube_map_array; + public boolean GL_ARB_texture_env_add; + public boolean GL_ARB_texture_env_combine; + public boolean GL_ARB_texture_env_crossbar; + public boolean GL_ARB_texture_env_dot3; + public boolean GL_ARB_texture_float;; + public boolean GL_ARB_texture_gather; + public boolean GL_ARB_texture_mirror_clamp_to_edge; + public boolean GL_ARB_texture_mirrored_repeat; + public boolean GL_ARB_texture_multisample; + public boolean GL_ARB_texture_non_power_of_two; + public boolean GL_ARB_texture_query_levels; + public boolean GL_ARB_texture_query_lod; + public boolean GL_ARB_texture_rectangle; + public boolean GL_ARB_texture_rg; + public boolean GL_ARB_texture_rgb10_a2ui; + public boolean GL_ARB_texture_stencil8; + public boolean GL_ARB_texture_storage; + public boolean GL_ARB_texture_storage_multisample; + public boolean GL_ARB_texture_swizzle; + public boolean GL_ARB_texture_view; + public boolean GL_ARB_timer_query; + public boolean GL_ARB_transform_feedback2; + public boolean GL_ARB_transform_feedback3; + public boolean GL_ARB_transform_feedback_instanced; + public boolean GL_ARB_transpose_matrix; + public boolean GL_ARB_uniform_buffer_object; + public boolean GL_ARB_vertex_array_bgra; + public boolean GL_ARB_vertex_array_object; + public boolean GL_ARB_vertex_attrib_64bit; + public boolean GL_ARB_vertex_attrib_binding; + public boolean GL_ARB_vertex_blend; + public boolean GL_ARB_vertex_buffer_object; + public boolean GL_ARB_vertex_program; + public boolean GL_ARB_vertex_shader; + public boolean GL_ARB_vertex_type_10f_11f_11f_rev; + public boolean GL_ARB_vertex_type_2_10_10_10_rev; + public boolean GL_ARB_viewport_array; + public boolean GL_ARB_window_pos; + public boolean GL_ATI_draw_buffers; + public boolean GL_ATI_element_array; + public boolean GL_ATI_envmap_bumpmap; + public boolean GL_ATI_fragment_shader; + public boolean GL_ATI_map_object_buffer; + public boolean GL_ATI_meminfo; + public boolean GL_ATI_pn_triangles; + public boolean GL_ATI_separate_stencil; + public boolean GL_ATI_shader_texture_lod; + public boolean GL_ATI_text_fragment_shader; + public boolean GL_ATI_texture_compression_3dc; + public boolean GL_ATI_texture_env_combine3; + public boolean GL_ATI_texture_float; + public boolean GL_ATI_texture_mirror_once; + public boolean GL_ATI_vertex_array_object; + public boolean GL_ATI_vertex_attrib_array_object; + public boolean GL_ATI_vertex_streams; + public boolean GL_EXT_abgr; + public boolean GL_EXT_bgra; + public boolean GL_EXT_bindable_uniform; + public boolean GL_EXT_blend_color; + public boolean GL_EXT_blend_equation_separate; + public boolean GL_EXT_blend_func_separate; + public boolean GL_EXT_blend_minmax; + public boolean GL_EXT_blend_subtract; + public boolean GL_EXT_Cg_shader; + public boolean GL_EXT_compiled_vertex_array; + public boolean GL_EXT_depth_bounds_test; + public boolean GL_EXT_direct_state_access; + public boolean GL_EXT_draw_buffers2; + public boolean GL_EXT_draw_instanced; + public boolean GL_EXT_draw_range_elements; + public boolean GL_EXT_fog_coord; + public boolean GL_EXT_framebuffer_blit; + public boolean GL_EXT_framebuffer_multisample; + public boolean GL_EXT_framebuffer_multisample_blit_scaled; + public boolean GL_EXT_framebuffer_object; + public boolean GL_EXT_framebuffer_sRGB; + public boolean GL_EXT_geometry_shader4; + public boolean GL_EXT_gpu_program_parameters; + public boolean GL_EXT_gpu_shader4; + public boolean GL_EXT_multi_draw_arrays; + public boolean GL_EXT_packed_depth_stencil; + public boolean GL_EXT_packed_float; + public boolean GL_EXT_packed_pixels; + public boolean GL_EXT_paletted_texture; + public boolean GL_EXT_pixel_buffer_object; + public boolean GL_EXT_point_parameters; + public boolean GL_EXT_provoking_vertex; + public boolean GL_EXT_rescale_normal; + public boolean GL_EXT_secondary_color; + public boolean GL_EXT_separate_shader_objects; + public boolean GL_EXT_separate_specular_color; + public boolean GL_EXT_shader_image_load_store; + public boolean GL_EXT_shadow_funcs; + public boolean GL_EXT_shared_texture_palette; + public boolean GL_EXT_stencil_clear_tag; + public boolean GL_EXT_stencil_two_side; + public boolean GL_EXT_stencil_wrap; + public boolean GL_EXT_texture_3d; + public boolean GL_EXT_texture_array; + public boolean GL_EXT_texture_buffer_object; + public boolean GL_EXT_texture_compression_latc; + public boolean GL_EXT_texture_compression_rgtc; + public boolean GL_EXT_texture_compression_s3tc; + public boolean GL_EXT_texture_env_combine; + public boolean GL_EXT_texture_env_dot3; + public boolean GL_EXT_texture_filter_anisotropic; + public boolean GL_EXT_texture_integer; + public boolean GL_EXT_texture_lod_bias; + public boolean GL_EXT_texture_mirror_clamp; + public boolean GL_EXT_texture_rectangle; + public boolean GL_EXT_texture_sRGB; + public boolean GL_EXT_texture_sRGB_decode; + public boolean GL_EXT_texture_shared_exponent; + public boolean GL_EXT_texture_snorm; + public boolean GL_EXT_texture_swizzle; + public boolean GL_EXT_timer_query; + public boolean GL_EXT_transform_feedback; + public boolean GL_EXT_vertex_array_bgra; + public boolean GL_EXT_vertex_attrib_64bit; + public boolean GL_EXT_vertex_shader; + public boolean GL_EXT_vertex_weighting; + public boolean OpenGL11; + public boolean OpenGL12; + public boolean OpenGL13; + public boolean OpenGL14; + public boolean OpenGL15; + public boolean OpenGL20; + public boolean OpenGL21; + public boolean OpenGL30; + public boolean OpenGL31; + public boolean OpenGL32; + public boolean OpenGL33; + public boolean OpenGL40; + public boolean OpenGL41; + public boolean OpenGL42; + public boolean OpenGL43; + public boolean OpenGL44; + public boolean GL_GREMEDY_frame_terminator; + public boolean GL_GREMEDY_string_marker; + public boolean GL_HP_occlusion_test; + public boolean GL_IBM_rasterpos_clip; + public boolean GL_INTEL_map_texture; + public boolean GL_KHR_debug; + public boolean GL_KHR_texture_compression_astc_ldr; + public boolean GL_NVX_gpu_memory_info; + public boolean GL_NV_bindless_multi_draw_indirect; + public boolean GL_NV_bindless_texture; + public boolean GL_NV_blend_equation_advanced; + public boolean GL_NV_blend_square; + public boolean GL_NV_compute_program5; + public boolean GL_NV_conditional_render; + public boolean GL_NV_copy_depth_to_color; + public boolean GL_NV_copy_image; + public boolean GL_NV_deep_texture3D; + public boolean GL_NV_depth_buffer_float; + public boolean GL_NV_depth_clamp; + public boolean GL_NV_draw_texture; + public boolean GL_NV_evaluators; + public boolean GL_NV_explicit_multisample; + public boolean GL_NV_fence; + public boolean GL_NV_float_buffer; + public boolean GL_NV_fog_distance; + public boolean GL_NV_fragment_program; + public boolean GL_NV_fragment_program2; + public boolean GL_NV_fragment_program4; + public boolean GL_NV_fragment_program_option; + public boolean GL_NV_framebuffer_multisample_coverage; + public boolean GL_NV_geometry_program4; + public boolean GL_NV_geometry_shader4; + public boolean GL_NV_gpu_program4; + public boolean GL_NV_gpu_program5; + public boolean GL_NV_gpu_program5_mem_extended; + public boolean GL_NV_gpu_shader5; + public boolean GL_NV_half_float; + public boolean GL_NV_light_max_exponent; + public boolean GL_NV_multisample_coverage; + public boolean GL_NV_multisample_filter_hint; + public boolean GL_NV_occlusion_query; + public boolean GL_NV_packed_depth_stencil; + public boolean GL_NV_parameter_buffer_object; + public boolean GL_NV_parameter_buffer_object2; + public boolean GL_NV_path_rendering; + public boolean GL_NV_pixel_data_range; + public boolean GL_NV_point_sprite; + public boolean GL_NV_present_video; + public boolean GL_NV_primitive_restart; + public boolean GL_NV_register_combiners; + public boolean GL_NV_register_combiners2; + public boolean GL_NV_shader_atomic_counters; + public boolean GL_NV_shader_atomic_float; + public boolean GL_NV_shader_buffer_load; + public boolean GL_NV_shader_buffer_store; + public boolean GL_NV_shader_storage_buffer_object; + public boolean GL_NV_tessellation_program5; + public boolean GL_NV_texgen_reflection; + public boolean GL_NV_texture_barrier; + public boolean GL_NV_texture_compression_vtc; + public boolean GL_NV_texture_env_combine4; + public boolean GL_NV_texture_expand_normal; + public boolean GL_NV_texture_multisample; + public boolean GL_NV_texture_rectangle; + public boolean GL_NV_texture_shader; + public boolean GL_NV_texture_shader2; + public boolean GL_NV_texture_shader3; + public boolean GL_NV_transform_feedback; + public boolean GL_NV_transform_feedback2; + public boolean GL_NV_vertex_array_range; + public boolean GL_NV_vertex_array_range2; + public boolean GL_NV_vertex_attrib_integer_64bit; + public boolean GL_NV_vertex_buffer_unified_memory; + public boolean GL_NV_vertex_program; + public boolean GL_NV_vertex_program1_1; + public boolean GL_NV_vertex_program2; + public boolean GL_NV_vertex_program2_option; + public boolean GL_NV_vertex_program3; + public boolean GL_NV_vertex_program4; + public boolean GL_NV_video_capture; + public boolean GL_SGIS_generate_mipmap; + public boolean GL_SGIS_texture_lod; + public boolean GL_SUN_slice_accum; + + public static void main(String[] arg) { + System.out.println("START!"); + new ContextCapabilities(); + } + +} diff --git a/src/main/java/org/lwjglx/opengl/ContextGL.java b/src/main/java/org/lwjglx/opengl/ContextGL.java new file mode 100644 index 0000000..a226bab --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/ContextGL.java @@ -0,0 +1,90 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; +import org.lwjglx.PointerBuffer; + +/** + *

+ * Context encapsulates an OpenGL context. + *

+ *

+ * This class is thread-safe. + * + * @author elias_naur + * @version $Revision$ + * $Id$ + */ +final class ContextGL implements Context { + + public void releaseCurrent() throws LWJGLException { + + } + + public synchronized void releaseDrawable() throws LWJGLException { + + } + + public synchronized void update() { + + } + + public static void swapBuffers() throws LWJGLException { + + } + + public synchronized void makeCurrent() throws LWJGLException { + + } + + public synchronized boolean isCurrent() throws LWJGLException { + return false; + } + + public static void setSwapInterval(int value) { + + } + + public synchronized void forceDestroy() throws LWJGLException { + + } + + public synchronized void destroy() throws LWJGLException { + + } + + public synchronized void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException { + + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/Display.java b/src/main/java/org/lwjglx/opengl/Display.java new file mode 100644 index 0000000..aaf668e --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Display.java @@ -0,0 +1,502 @@ +package org.lwjglx.opengl; + +import static org.lwjgl.opengl.GL11.GL_FALSE; +import static org.lwjgl.opengl.GL11.GL_TRUE; +import static org.lwjgl.system.MemoryUtil.NULL; +import static org.lwjgl.glfw.GLFW.GLFW_OPENGL_DEBUG_CONTEXT; +import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; +import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE; +import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE; +import static org.lwjgl.glfw.GLFW.glfwCreateWindow; +import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints; +import static org.lwjgl.glfw.GLFW.glfwDestroyWindow; +import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor; +import static org.lwjgl.glfw.GLFW.glfwGetVideoMode; +import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent; +import static org.lwjgl.glfw.GLFW.glfwPollEvents; +import static org.lwjgl.glfw.GLFW.glfwSetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwShowWindow; +import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; +import static org.lwjgl.glfw.GLFW.glfwSwapInterval; +import static org.lwjgl.glfw.GLFW.glfwWindowHint; +import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose; +import static org.lwjgl.glfw.Callbacks.*; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.glfw.GLFWCharCallback; +import org.lwjgl.glfw.GLFWCursorPosCallback; +import org.lwjgl.glfw.GLFWKeyCallback; +import org.lwjgl.glfw.GLFWMouseButtonCallback; +import org.lwjgl.glfw.GLFWvidmode; +import org.lwjgl.glfw.GLFWWindowFocusCallback; +import org.lwjgl.glfw.GLFWWindowIconifyCallback; +import org.lwjgl.glfw.GLFWWindowPosCallback; +import org.lwjgl.glfw.GLFWWindowRefreshCallback; +import org.lwjgl.glfw.*; +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; +import org.lwjglx.input.Keyboard; +import org.lwjglx.input.Mouse; + +public class Display { + + private static String windowTitle = "Game"; + + private static org.lwjgl.opengl.GLContext context; + + private static boolean displayCreated = false; + private static boolean displayFocused = false; + private static boolean displayVisible = true; + private static boolean displayDirty = false; + private static boolean displayResizable = false; + + private static DisplayMode mode = new DisplayMode(640, 480); + private static DisplayMode desktopDisplayMode = new DisplayMode(640, 480); + + private static int latestEventKey = 0; + + private static int displayX = 0; + private static int displayY = 0; + + private static boolean displayResized = false; + private static int displayWidth = 0; + private static int displayHeight = 0; + private static int displayFramebufferWidth = 0; + private static int displayFramebufferHeight = 0; + + private static boolean latestResized = false; + private static int latestWidth = 0; + private static int latestHeight = 0; + + static { + Sys.initialize(); // init using dummy sys method + + long monitor = glfwGetPrimaryMonitor(); + ByteBuffer vidmode = glfwGetVideoMode(monitor); + + int monitorWidth = GLFWvidmode.width(vidmode); + int monitorHeight = GLFWvidmode.height(vidmode); + int monitorBitPerPixel = GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode); + int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode); + + desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate); + } + + public static void create(PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException { + System.out.println("TODO: Implement Display.create(PixelFormat, Drawable)"); // TODO + create(); + } + + public static void create(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException { + System.out.println("TODO: Implement Display.create(PixelFormat, ContextAttribs)"); // TODO + create(); + } + + public static void create(PixelFormat pixel_format) throws LWJGLException { + System.out.println("TODO: Implement Display.create(PixelFormat)"); // TODO + create(); + } + + public static void create() throws LWJGLException { + long monitor = glfwGetPrimaryMonitor(); + ByteBuffer vidmode = glfwGetVideoMode(monitor); + + int monitorWidth = GLFWvidmode.width(vidmode); + int monitorHeight = GLFWvidmode.height(vidmode); + int monitorBitPerPixel = GLFWvidmode.redBits(vidmode) + GLFWvidmode.greenBits(vidmode) + GLFWvidmode.blueBits(vidmode); + int monitorRefreshRate = GLFWvidmode.refreshRate(vidmode); + + desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate); + + glfwDefaultWindowHints(); + glfwWindowHint(GLFW_VISIBLE, GL_FALSE); + glfwWindowHint(GLFW_RESIZABLE, displayResizable ? GL_TRUE : GL_FALSE); + glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); + + + Window.handle = glfwCreateWindow(mode.getWidth(), mode.getHeight(), windowTitle, NULL, NULL); + if ( Window.handle == 0L ) + throw new IllegalStateException("Failed to create Display window"); + + + Window.keyCallback = new GLFWKeyCallback() { + @Override + public void invoke(long window, int key, int scancode, int action, int mods) { + latestEventKey = key; + + if (action == GLFW_RELEASE || action == GLFW.GLFW_PRESS) { + Keyboard.addKeyEvent(key, action == GLFW.GLFW_PRESS ? true : false); + } + } + }; + + Window.charCallback = new GLFWCharCallback() { + @Override + public void invoke(long window, int codepoint) { + Keyboard.addCharEvent(latestEventKey, (char)codepoint); + } + }; + + Window.cursorPosCallback = new GLFWCursorPosCallback() { + @Override + public void invoke(long window, double xpos, double ypos) { + Mouse.addMoveEvent(xpos, ypos); + } + }; + + Window.mouseButtonCallback = new GLFWMouseButtonCallback() { + @Override + public void invoke(long window, int button, int action, int mods) { + Mouse.addButtonEvent(button, action == GLFW.GLFW_PRESS ? true : false); + } + }; + + Window.windowFocusCallback = new GLFWWindowFocusCallback() { + @Override + public void invoke(long window, int focused) { + displayFocused = focused == GL11.GL_TRUE; + } + }; + + Window.windowIconifyCallback = new GLFWWindowIconifyCallback() { + @Override + public void invoke(long window, int iconified) { + displayVisible = iconified == GL11.GL_FALSE; + } + }; + + Window.windowSizeCallback = new GLFWWindowSizeCallback() { + @Override + public void invoke(long window, int width, int height) { + latestResized = true; + latestWidth = width; + latestHeight = height; + } + }; + + Window.windowPosCallback = new GLFWWindowPosCallback() { + @Override + public void invoke(long window, int xpos, int ypos) { + displayX = xpos; + displayY = ypos; + } + }; + + Window.windowRefreshCallback = new GLFWWindowRefreshCallback() { + @Override + public void invoke(long window) { + displayDirty = true; + } + }; + + Window.framebufferSizeCallback = new GLFWFramebufferSizeCallback() { + @Override + public void invoke(long window, int width, int height) { + displayFramebufferWidth = width; + displayFramebufferHeight = height; + } + }; + + Window.setCallbacks(); + + displayWidth = mode.getWidth(); + displayHeight = mode.getHeight(); + + IntBuffer fbw = BufferUtils.createIntBuffer(1); + IntBuffer fbh = BufferUtils.createIntBuffer(1); + GLFW.glfwGetFramebufferSize(Window.handle, fbw, fbh); + displayFramebufferWidth = fbw.get(0); + displayFramebufferHeight = fbh.get(0); + + glfwSetWindowPos( + Window.handle, + (monitorWidth - mode.getWidth()) / 2, + (monitorHeight - mode.getHeight()) / 2 + ); + + displayX = (monitorWidth - mode.getWidth()) / 2; + displayY = (monitorHeight - mode.getHeight()) / 2; + + glfwMakeContextCurrent(Window.handle); + context = org.lwjgl.opengl.GLContext.createFromCurrent(); + + glfwSwapInterval(1); + glfwShowWindow(Window.handle); + + displayCreated = true; + } + + public static boolean isCreated() { + return displayCreated; + } + + public static boolean isActive() { + return displayFocused; + } + + public static boolean isVisible() { + return displayVisible; + } + + public static org.lwjgl.opengl.GLContext getContext() { + return context; + } + + public static void setLocation(int new_x, int new_y) { + System.out.println("TODO: Implement Display.setLocation(int, int)"); + } + + public static void setVSyncEnabled(boolean sync) { + System.out.println("TODO: Implement Display.setVSyncEnabled(boolean)");// TODO + } + + public static long getWindow() { + return Window.handle; + } + + public static void update() { + update(true); + } + + public static void update(boolean processMessages) { + try { + swapBuffers(); + displayDirty = false; + } + catch (LWJGLException e) { + throw new RuntimeException(e); + } + + if (processMessages) processMessages(); + } + + public static void processMessages() { + glfwPollEvents(); + Keyboard.poll(); + Mouse.poll(); + + if (latestResized) { + latestResized = false; + displayResized = true; + displayWidth = latestWidth; + displayHeight = latestHeight; + } + else { + displayResized = false; + } + } + + public static void swapBuffers() throws LWJGLException { + glfwSwapBuffers(Window.handle); + } + + public static void destroy() { + Window.releaseCallbacks(); + glfwDestroyWindow(Window.handle); + + /*try { + glfwTerminate(); + } catch (Throwable t) { + t.printStackTrace(); + }*/ + displayCreated = false; + } + + public static void setDisplayMode(DisplayMode dm) throws LWJGLException { + mode = dm; + } + + public static DisplayMode getDisplayMode() { + return mode; + } + + public static DisplayMode[] getAvailableDisplayModes() throws LWJGLException { + IntBuffer count = BufferUtils.createIntBuffer(1); + ByteBuffer modes = GLFW.glfwGetVideoModes(GLFW.glfwGetPrimaryMonitor(), count); + + DisplayMode[] displayModes = new DisplayMode[count.get(0)]; + + for (int i = 0; i < count.get(0); i++) { + modes.position(i * GLFWvidmode.SIZEOF); + + int w = GLFWvidmode.width(modes); + int h = GLFWvidmode.height(modes); + int b = GLFWvidmode.redBits(modes) + GLFWvidmode.greenBits(modes) + + GLFWvidmode.blueBits(modes); + int r = GLFWvidmode.refreshRate(modes); + + displayModes[i] = new DisplayMode(w, h, b, r); + } + + return displayModes; + } + + public static DisplayMode getDesktopDisplayMode() { + return desktopDisplayMode; + } + + public static boolean wasResized() { + return displayResized; + } + + public static int getX() { + return displayX; + } + + public static int getY() { + return displayY; + } + + public static int getWidth() { + return displayWidth; + } + + public static int getHeight() { + return displayHeight; + } + + public static int getFramebufferWidth() { + return displayFramebufferWidth; + } + + public static int getFramebufferHeight() { + return displayFramebufferHeight; + } + + public static void setTitle(String title) { + windowTitle = title; + } + + public static boolean isCloseRequested() { + return glfwWindowShouldClose(Window.handle) == GL_TRUE; + } + + public static boolean isDirty() { + return displayDirty; + } + + public static void setInitialBackground(float red, float green, float blue) { + // TODO + System.out.println("TODO: Implement Display.setInitialBackground(float, float, float)"); + } + + public static int setIcon(java.nio.ByteBuffer[] icons) { + // TODO + System.out.println("TODO: Implement Display.setIcon(ByteBuffer[])"); + return 0; + } + + public static void setResizable(boolean resizable) { + displayResizable = resizable; + // TODO + } + + public static boolean isResizable() { + return displayResizable; + } + + public static void setDisplayModeAndFullscreen(DisplayMode mode) throws LWJGLException { + // TODO + System.out.println("TODO: Implement Display.setDisplayModeAndFullscreen(DisplayMode)"); + } + + public static void setFullscreen(boolean fullscreen) throws LWJGLException { + // TODO + } + + public static boolean isFullscreen() { + // TODO + return false; + } + + public static void setParent(java.awt.Canvas parent) throws LWJGLException { + // Do nothing as set parent not supported + } + + public static void releaseContext() throws LWJGLException { + glfwMakeContextCurrent(0); + } + + public static boolean isCurrent() throws LWJGLException { + return context.isCurrent(); + } + + public static void makeCurrent() throws LWJGLException { + glfwMakeContextCurrent(Window.handle); + } + + public static java.lang.String getAdapter() { + // TODO + return "GeNotSupportedAdapter"; + } + + public static java.lang.String getVersion() { + // TODO + return "1.0 NOT SUPPORTED"; + } + + /** + * An accurate sync method that will attempt to run at a constant frame rate. + * It should be called once every frame. + * + * @param fps - the desired frame rate, in frames per second + */ + public static void sync(int fps) { + Sync.sync(fps); + } + + public static Drawable getDrawable() { + return null; + } + + static DisplayImplementation getImplementation() { + return null; + } + + private static class Window { + static long handle; + + static GLFWKeyCallback keyCallback; + static GLFWCharCallback charCallback; + static GLFWCursorPosCallback cursorPosCallback; + static GLFWMouseButtonCallback mouseButtonCallback; + static GLFWWindowFocusCallback windowFocusCallback; + static GLFWWindowIconifyCallback windowIconifyCallback; + static GLFWWindowSizeCallback windowSizeCallback; + static GLFWWindowPosCallback windowPosCallback; + static GLFWWindowRefreshCallback windowRefreshCallback; + static GLFWFramebufferSizeCallback framebufferSizeCallback; + + public static void setCallbacks() { + glfwSetCallback(handle, keyCallback); + glfwSetCallback(handle, charCallback); + glfwSetCallback(handle, cursorPosCallback); + glfwSetCallback(handle, mouseButtonCallback); + glfwSetCallback(handle, windowFocusCallback); + glfwSetCallback(handle, windowIconifyCallback); + glfwSetCallback(handle, windowSizeCallback); + glfwSetCallback(handle, windowPosCallback); + glfwSetCallback(handle, windowRefreshCallback); + glfwSetCallback(handle, framebufferSizeCallback); + } + + public static void releaseCallbacks() { + keyCallback.release(); + charCallback.release(); + cursorPosCallback.release(); + mouseButtonCallback.release(); + windowFocusCallback.release(); + windowIconifyCallback.release(); + windowSizeCallback.release(); + windowPosCallback.release(); + windowRefreshCallback.release(); + framebufferSizeCallback.release(); + } + } + +} diff --git a/src/main/java/org/lwjglx/opengl/DisplayImplementation.java b/src/main/java/org/lwjglx/opengl/DisplayImplementation.java new file mode 100644 index 0000000..0890cdd --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/DisplayImplementation.java @@ -0,0 +1,200 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * This is the Display implementation interface. Display delegates + * to implementors of this interface. There is one DisplayImplementation + * for each supported platform. + * @author elias_naur + */ + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.awt.Canvas; + +import org.lwjglx.LWJGLException; + +interface DisplayImplementation extends InputImplementation { + + void createWindow(DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException; + + void destroyWindow(); + + void switchDisplayMode(DisplayMode mode) throws LWJGLException; + + /** + * Reset the display mode to whatever it was when LWJGL was initialized. + * Fails silently. + */ + void resetDisplayMode(); + + /** + * Return the length of the gamma ramp arrays. Returns 0 if gamma settings are + * unsupported. + * + * @return the length of each gamma ramp array, or 0 if gamma settings are unsupported. + */ + int getGammaRampLength(); + + /** + * Method to set the gamma ramp. + */ + void setGammaRamp(FloatBuffer gammaRamp) throws LWJGLException; + + /** + * Get the driver adapter string. This is a unique string describing the actual card's hardware, eg. "Geforce2", "PS2", + * "Radeon9700". If the adapter cannot be determined, this function returns null. + * @return a String + */ + String getAdapter(); + + /** + * Get the driver version. This is a vendor/adapter specific version string. If the version cannot be determined, + * this function returns null. + * @return a String + */ + String getVersion(); + + /** + * Initialize and return the current display mode. + */ + DisplayMode init() throws LWJGLException; + + /** + * Implementation of setTitle(). This will read the window's title member + * and stash it in the native title of the window. + */ + void setTitle(String title); + + boolean isCloseRequested(); + + boolean isVisible(); + boolean isActive(); + + boolean isDirty(); + + /** + * Create the native PeerInfo. + * @throws LWJGLException + */ + PeerInfo createPeerInfo(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException; + +// void destroyPeerInfo(); + + /** + * Updates the windows internal state. This must be called at least once per video frame + * to handle window close requests, moves, paints, etc. + */ + void update(); + + void reshape(int x, int y, int width, int height); + + /** + * Method for getting displaymodes + */ + DisplayMode[] getAvailableDisplayModes() throws LWJGLException; + + /* Pbuffer */ + int getPbufferCapabilities(); + + /** + * Method to test for buffer integrity + */ + boolean isBufferLost(PeerInfo handle); + + /** + * Method to create a Pbuffer + */ + PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, ContextAttribs attribs, + IntBuffer pixelFormatCaps, + IntBuffer pBufferAttribs) throws LWJGLException; + + void setPbufferAttrib(PeerInfo handle, int attrib, int value); + + void bindTexImageToPbuffer(PeerInfo handle, int buffer); + + void releaseTexImageFromPbuffer(PeerInfo handle, int buffer); + + /** + * Sets one or more icons for the Display. + *

    + *
  • On Windows you should supply at least one 16x16 icon and one 32x32.
  • + *
  • Linux (and similar platforms) expect one 32x32 icon.
  • + *
  • Mac OS X should be supplied one 128x128 icon
  • + *
+ * The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform. + * + * @param icons Array of icons in RGBA mode + * @return number of icons used. + */ + int setIcon(ByteBuffer[] icons); + + /** + * Enable or disable the Display window to be resized. + * + * @param resizable set to true to make the Display window resizable; + * false to disable resizing on the Display window. + */ + void setResizable(boolean resizable); + + /** + * @return true if the Display window has been resized since this method was last called. + */ + boolean wasResized(); + + /** + * @return this method will return the width of the Display window. + */ + int getWidth(); + + /** + * @return this method will return the height of the Display window. + */ + int getHeight(); + + /** + * @return this method will return the top-left x position of the Display window. + */ + int getX(); + + /** + * @return this method will return the top-left y position of the Display window. + */ + int getY(); + + /** + * @return this method will return the pixel scale factor of the Display window useful for high resolution modes. + */ + float getPixelScaleFactor(); +} diff --git a/src/main/java/org/lwjglx/opengl/DisplayMode.java b/src/main/java/org/lwjglx/opengl/DisplayMode.java new file mode 100644 index 0000000..a2720da --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/DisplayMode.java @@ -0,0 +1,142 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * + * This class encapsulates the properties for a given display mode. + * This class is not instantiable, and is aquired from the Display. + * getAvailableDisplayModes() method. + * + * @author cix_foo + * @version $Revision$ + * $Id$ + */ + +public final class DisplayMode { + + /** properties of the display mode */ + private final int width, height, bpp, freq; + /** If true, this instance can be used for fullscreen modes */ + private final boolean fullscreen; + + /** + * Construct a display mode. DisplayModes constructed through the + * public constructor can only be used to specify the dimensions of + * the Display in windowed mode. To get the available DisplayModes for + * fullscreen modes, use Display.getAvailableDisplayModes(). + * + * @param width The Display width. + * @param height The Display height. + * @see Display + */ + public DisplayMode(int width, int height) { + this(width, height, 0, 0, false); + } + + DisplayMode(int width, int height, int bpp, int freq) { + this(width, height, bpp, freq, true); + } + + private DisplayMode(int width, int height, int bpp, int freq, boolean fullscreen) { + this.width = width; + this.height = height; + this.bpp = bpp; + this.freq = freq; + this.fullscreen = fullscreen; + } + + /** True if this instance can be used for fullscreen modes */ + public boolean isFullscreenCapable() { + return fullscreen; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public int getBitsPerPixel() { + return bpp; + } + + public int getFrequency() { + return freq; + } + + /** + * Tests for DisplayMode equality + * + * @see java.lang.Object#equals(Object) + */ + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof DisplayMode)) { + return false; + } + + DisplayMode dm = (DisplayMode) obj; + return dm.width == width + && dm.height == height + && dm.bpp == bpp + && dm.freq == freq; + } + + /** + * Retrieves the hashcode for this object + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return width ^ height ^ freq ^ bpp; + } + + /** + * Retrieves a String representation of this DisplayMode + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuilder sb = new StringBuilder(32); + sb.append(width); + sb.append(" x "); + sb.append(height); + sb.append(" x "); + sb.append(bpp); + sb.append(" @"); + sb.append(freq); + sb.append("Hz"); + return sb.toString(); + } +} diff --git a/src/main/java/org/lwjglx/opengl/Drawable.java b/src/main/java/org/lwjglx/opengl/Drawable.java new file mode 100644 index 0000000..a87ca25 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Drawable.java @@ -0,0 +1,77 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; +import org.lwjglx.PointerBuffer; + +/** + * The Drawable interface describes an OpenGL drawable with an associated + * Context. + * + * @author elias_naur + */ + +public interface Drawable { + + /** Returns true if the Drawable's context is current in the current thread. */ + boolean isCurrent() throws LWJGLException; + + /** + * Makes the Drawable's context current in the current thread. + * + * @throws LWJGLException + */ + void makeCurrent() throws LWJGLException; + + /** + * If the Drawable's context is current in the current thread, no context will be current after a call to this method. + * + * @throws LWJGLException + */ + void releaseContext() throws LWJGLException; + + /** Destroys the Drawable. */ + void destroy(); + + /** + * Sets the appropriate khr_gl_sharing properties in the target PointerBuffer, + * so that if it is used in a clCreateContext(FromType) call, the created CL + * context will be sharing objects with this Drawable's GL context. After a + * call to this method, the target buffer position will have advanced by 2 to 4 positions, + * depending on the implementation. + * + * @param properties The target properties buffer. It must have at least 4 positions remaining. + */ + void setCLSharingProperties(PointerBuffer properties) throws LWJGLException; + +} diff --git a/src/main/java/org/lwjglx/opengl/DrawableGL.java b/src/main/java/org/lwjglx/opengl/DrawableGL.java new file mode 100644 index 0000000..e48696e --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/DrawableGL.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2002-2011 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.PointerBuffer; + +import static org.lwjgl.opengl.GL11.*; + +/** @author Spasi */ +abstract class DrawableGL implements DrawableLWJGL { + + /** The PixelFormat used to create the drawable. */ + protected PixelFormat pixel_format; + + /** Handle to the native GL rendering context */ + protected PeerInfo peer_info; + + /** The OpenGL Context. */ + protected ContextGL context; + + protected DrawableGL() { + } + + public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException { + throw new UnsupportedOperationException(); + } + + public void setPixelFormat(final PixelFormatLWJGL pf, final ContextAttribs attribs) throws LWJGLException { + this.pixel_format = (PixelFormat)pf; + //this.peer_info = Display.getImplementation().createPeerInfo(pixel_format, attribs); + } + + public PixelFormatLWJGL getPixelFormat() { + return pixel_format; + } + + public ContextGL getContext() { + synchronized ( GlobalLock.lock ) { + return context; + } + } + + public ContextGL createSharedContext() throws LWJGLException { + synchronized ( GlobalLock.lock ) { + //checkDestroyed(); + //return new ContextGL(peer_info, context.getContextAttribs(), context); + return null; + } + } + + public void checkGLError() { + Util.checkGLError(); + } + + public void setSwapInterval(final int swap_interval) { + ContextGL.setSwapInterval(swap_interval); + } + + public void swapBuffers() throws LWJGLException { + ContextGL.swapBuffers(); + } + + public void initContext(final float r, final float g, final float b) { + // set background clear color + glClearColor(r, g, b, 0.0f); + // Clear window to avoid the desktop "showing through" + glClear(GL_COLOR_BUFFER_BIT); + } + + public boolean isCurrent() throws LWJGLException { + synchronized ( GlobalLock.lock ) { + checkDestroyed(); + return context.isCurrent(); + } + } + + public void makeCurrent() throws LWJGLException { + synchronized ( GlobalLock.lock ) { + checkDestroyed(); + context.makeCurrent(); + } + } + + public void releaseContext() throws LWJGLException { + synchronized ( GlobalLock.lock ) { + checkDestroyed(); + if ( context.isCurrent() ) + context.releaseCurrent(); + } + } + + public void destroy() { + synchronized ( GlobalLock.lock ) { + if ( context == null ) + return; + + try { + releaseContext(); + + context.forceDestroy(); + context = null; + + if ( peer_info != null ) { + peer_info.destroy(); + peer_info = null; + } + } catch (LWJGLException e) { + LWJGLUtil.log("Exception occurred while destroying Drawable: " + e); + } + } + } + + public void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException { + synchronized ( GlobalLock.lock ) { + checkDestroyed(); + context.setCLSharingProperties(properties); + } + } + + protected final void checkDestroyed() { + if ( context == null ) + throw new IllegalStateException("The Drawable has no context available."); + } + +} diff --git a/src/main/java/org/lwjglx/opengl/DrawableLWJGL.java b/src/main/java/org/lwjglx/opengl/DrawableLWJGL.java new file mode 100644 index 0000000..1f70b4f --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/DrawableLWJGL.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2002-2011 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.LWJGLException; + +/** + * [INTERNAL USE ONLY] + * + * @author Spasi + */ +interface DrawableLWJGL extends Drawable { + + void setPixelFormat(PixelFormatLWJGL pf) throws LWJGLException; + + void setPixelFormat(PixelFormatLWJGL pf, ContextAttribs attribs) throws LWJGLException; + + PixelFormatLWJGL getPixelFormat(); + + /** + * [INTERNAL USE ONLY] Returns the Drawable's Context. + * + * @return the Drawable's Context + */ + Context getContext(); + + /** + * [INTERNAL USE ONLY] Creates a new Context that is shared with the Drawable's Context. + * + * @return a Context shared with the Drawable's Context. + */ + Context createSharedContext() throws LWJGLException; + + void checkGLError(); + + void setSwapInterval(int swap_interval); + + void swapBuffers() throws LWJGLException; + + void initContext(final float r, final float g, final float b); + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/GL15x.java b/src/main/java/org/lwjglx/opengl/GL15x.java new file mode 100644 index 0000000..6611bd5 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/GL15x.java @@ -0,0 +1,20 @@ +package org.lwjglx.opengl; + +import java.nio.ByteBuffer; + +import org.lwjgl.BufferUtils; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL15; + +public class GL15x { + + public static ByteBuffer glGetBufferPointer(int target, int pname) { + int size = GL15.glGetBufferParameteri(target, GL15.GL_BUFFER_SIZE); + + PointerBuffer pb = BufferUtils.createPointerBuffer(1); + GL15.glGetBufferPointer(target, pname, pb); + + return pb.getByteBuffer(0, size); + } + +} diff --git a/src/main/java/org/lwjglx/opengl/GL20x.java b/src/main/java/org/lwjglx/opengl/GL20x.java new file mode 100644 index 0000000..a91cfca --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/GL20x.java @@ -0,0 +1,63 @@ +package org.lwjglx.opengl; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; + +import org.lwjgl.BufferUtils; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.system.MemoryUtil; + +public class GL20x { + + public static void glVertexAttribPointer(int index, int size, + boolean unsigned, boolean normalized, + int stride, ByteBuffer buffer) { + int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE; + GL20.glVertexAttribPointer(index, size, type, normalized, stride, buffer); + } + + public static void glVertexAttribPointer(int index, int size, + boolean unsigned, boolean normalized, + int stride, ShortBuffer buffer) { + int type = unsigned ? GL11.GL_UNSIGNED_SHORT : GL11.GL_SHORT; + GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer)); + } + + public static void glVertexAttribPointer(int index, int size, + boolean unsigned, boolean normalized, + int stride, IntBuffer buffer) { + int type = unsigned ? GL11.GL_UNSIGNED_INT : GL11.GL_INT; + GL20.nglVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(buffer)); +} + + public static String glGetActiveAttrib(int program, int index, int maxLength, + IntBuffer sizeType) { + //TODO check if correct + IntBuffer type = BufferUtils.createIntBuffer(1); + String s = GL20.glGetActiveAttrib(program, index, maxLength, sizeType, type); + sizeType.put(type.get(0)); + return s; + } + + public static String glGetActiveUniform(int program, int index, int maxLength, + IntBuffer sizeType) { + //TODO if correct + IntBuffer type = BufferUtils.createIntBuffer(1); + String s = GL20.glGetActiveUniform(program, index, maxLength, sizeType, type); + sizeType.put(type.get(0)); + return s; + } + + public static void glShaderSource(int shader, java.nio.ByteBuffer string) { + PointerBuffer strings = BufferUtils.createPointerBuffer(1); + IntBuffer lengths = BufferUtils.createIntBuffer(1); + + strings.put(0, string); + lengths.put(0, new String(string.array()).length());//source.length()); + org.lwjgl.opengl.GL20.glShaderSource(shader, strings, lengths); + } + +} diff --git a/src/main/java/org/lwjglx/opengl/GLContext.java b/src/main/java/org/lwjglx/opengl/GLContext.java new file mode 100644 index 0000000..cec6e19 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/GLContext.java @@ -0,0 +1,11 @@ +package org.lwjglx.opengl; + + +public class GLContext { + + private static ContextCapabilities contextCapabilities = new ContextCapabilities(); + + public static ContextCapabilities getCapabilities() { + return contextCapabilities; + } +} diff --git a/src/main/java/org/lwjglx/opengl/GLSync.java b/src/main/java/org/lwjglx/opengl/GLSync.java new file mode 100644 index 0000000..17f4f14 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/GLSync.java @@ -0,0 +1,47 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.PointerWrapperAbstract; + +/** + * This class is a wrapper around a GLsync pointer. + * + * @author spasi + */ +public final class GLSync extends PointerWrapperAbstract { + + GLSync(final long sync) { + super(sync); + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/GlobalLock.java b/src/main/java/org/lwjglx/opengl/GlobalLock.java new file mode 100644 index 0000000..2bb430d --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/GlobalLock.java @@ -0,0 +1,40 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * This class contains the global lock that LWJGL will use to + * synchronize access to Display. + */ +final class GlobalLock { + static final Object lock = new Object(); +} diff --git a/src/main/java/org/lwjglx/opengl/InputImplementation.java b/src/main/java/org/lwjglx/opengl/InputImplementation.java new file mode 100644 index 0000000..aebd147 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/InputImplementation.java @@ -0,0 +1,134 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * This is the input implementation interface. Mouse and Keyboard delegates + * to implementors of this interface. There is one InputImplementation + * for each supported platform. + * @author elias_naur + */ + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +import org.lwjglx.LWJGLException; + +public interface InputImplementation { + /* + * Mouse methods + */ + /** Query of wheel support */ + boolean hasWheel(); + + /** Query of button count */ + int getButtonCount(); + + /** + * Method to create the mouse. + */ + void createMouse() throws LWJGLException; + + /** + * Method the destroy the mouse + */ + void destroyMouse(); + + /** + * Method to poll the mouse + */ + void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons); + + /** + * Method to read the keyboard buffer + */ + void readMouse(ByteBuffer buffer); + + void grabMouse(boolean grab); + + /** + * Function to determine native cursor support + */ + int getNativeCursorCapabilities(); + + /** Method to set the native cursor position */ + void setCursorPosition(int x, int y); + + /** Method to set the native cursor */ + void setNativeCursor(Object handle) throws LWJGLException; + + /** Method returning the minimum cursor size */ + int getMinCursorSize(); + + /** Method returning the maximum cursor size */ + int getMaxCursorSize(); + + /* + * Keyboard methods + */ + + /** + * Method to create the keyboard + */ + void createKeyboard() throws LWJGLException; + + /** + * Method to destroy the keyboard + */ + void destroyKeyboard(); + + /** + * Method to poll the keyboard. + * + * @param keyDownBuffer the address of a 256-byte buffer to place + * key states in. + */ + void pollKeyboard(ByteBuffer keyDownBuffer); + + /** + * Method to read the keyboard buffer + */ + void readKeyboard(ByteBuffer buffer); + +// int isStateKeySet(int key); + + /** Native cursor handles */ + Object createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException; + + void destroyCursor(Object cursor_handle); + + int getWidth(); + + int getHeight(); + + boolean isInsideWindow(); +} diff --git a/src/main/java/org/lwjglx/opengl/OpenGLException.java b/src/main/java/org/lwjglx/opengl/OpenGLException.java new file mode 100644 index 0000000..eeb8671 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/OpenGLException.java @@ -0,0 +1,89 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + *

+ * Thrown by the debug build library of the LWJGL if any OpenGL operation causes an error. + * + * @author cix_foo + * @version $Revision$ + * $Id$ + */ +public class OpenGLException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** Constructor for OpenGLException. */ + public OpenGLException(int gl_error_code) { + this(createErrorMessage(gl_error_code)); + } + + private static String createErrorMessage(int gl_error_code) { + String error_string = Util.translateGLErrorString(gl_error_code); + return error_string + " (" + gl_error_code + ")"; + } + + /** Constructor for OpenGLException. */ + public OpenGLException() { + super(); + } + + /** + * Constructor for OpenGLException. + * + * @param message + */ + public OpenGLException(String message) { + super(message); + } + + /** + * Constructor for OpenGLException. + * + * @param message + * @param cause + */ + public OpenGLException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor for OpenGLException. + * + * @param cause + */ + public OpenGLException(Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/lwjglx/opengl/Pbuffer.java b/src/main/java/org/lwjglx/opengl/Pbuffer.java new file mode 100644 index 0000000..20b4ecb --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Pbuffer.java @@ -0,0 +1,320 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import java.nio.IntBuffer; + +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; + +/** + *

+ * Pbuffer encapsulates an OpenGL pbuffer. + *

+ * + * This class is thread-safe. + * + * @author elias_naur + * @version $Revision$ + * $Id$ + */ +public final class Pbuffer extends DrawableGL { + /** + * Indicates that Pbuffers can be created. + */ + public static final int PBUFFER_SUPPORTED = 0;// mark as not supported 1 << 0; + + /** + * Indicates that Pbuffers can be used as render-textures. + */ + public static final int RENDER_TEXTURE_SUPPORTED = 1 << 1; + + /** + * Indicates that Pbuffers can be used as non-power-of-two render-textures. + */ + public static final int RENDER_TEXTURE_RECTANGLE_SUPPORTED = 1 << 2; + + /** + * Indicates that Pbuffers can be used as depth render-textures. + */ + public static final int RENDER_DEPTH_TEXTURE_SUPPORTED = 1 << 3; + + /** + * The render-to-texture mipmap level attribute. + */ + public static final int MIPMAP_LEVEL = RenderTexture.WGL_MIPMAP_LEVEL_ARB; + + /** + * The render-to-texture cube map face attribute. + */ + public static final int CUBE_MAP_FACE = RenderTexture.WGL_CUBE_MAP_FACE_ARB; + + /** + * The render-to-texture cube map positive X face value. + */ + public static final int TEXTURE_CUBE_MAP_POSITIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB; + + /** + * The render-to-texture cube map negative X face value. + */ + public static final int TEXTURE_CUBE_MAP_NEGATIVE_X = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB; + + /** + * The render-to-texture cube map positive Y face value. + */ + public static final int TEXTURE_CUBE_MAP_POSITIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB; + + /** + * The render-to-texture cube map negative Y face value. + */ + public static final int TEXTURE_CUBE_MAP_NEGATIVE_Y = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB; + + /** + * The render-to-texture cube map positive Z face value. + */ + public static final int TEXTURE_CUBE_MAP_POSITIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB; + + /** + * The render-to-texture cube map negative Z face value. + */ + public static final int TEXTURE_CUBE_MAP_NEGATIVE_Z = RenderTexture.WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB; + + /** + * The Pbuffer front left buffer. + */ + public static final int FRONT_LEFT_BUFFER = RenderTexture.WGL_FRONT_LEFT_ARB; + + /** + * The Pbuffer front right buffer. + */ + public static final int FRONT_RIGHT_BUFFER = RenderTexture.WGL_FRONT_RIGHT_ARB; + + /** + * The Pbuffer back left buffer. + */ + public static final int BACK_LEFT_BUFFER = RenderTexture.WGL_BACK_LEFT_ARB; + + /** + * The Pbuffer back right buffer. + */ + public static final int BACK_RIGHT_BUFFER = RenderTexture.WGL_BACK_RIGHT_ARB; + + /** + * The Pbuffer depth buffer. + */ + public static final int DEPTH_BUFFER = RenderTexture.WGL_DEPTH_COMPONENT_NV; + + /** + * Width + */ + private final int width; + + /** + * Height + */ + private final int height; + + static { + Sys.initialize(); + } + + /** + * Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered. + *

+ * NOTE: The Pbuffer will have its own context that shares display lists and textures with shared_context, + * or, if shared_context is null, the Display context if it is created. The Pbuffer + * will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa. + *

+ * + * @param width Pbuffer width + * @param height Pbuffer height + * @param pixel_format Minimum Pbuffer context properties + * @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share + * with the Display context (if created). + */ + public Pbuffer(int width, int height, PixelFormat pixel_format, Drawable shared_drawable) throws LWJGLException { + this(width, height, pixel_format, null, shared_drawable); + } + + /** + * Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered. + *

+ * NOTE: The Pbuffer will have its own context that shares display lists and textures with shared_context, + * or, if shared_context is null, the Display context if it is created. The Pbuffer + * will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa. + *

+ * The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null, + * render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that + * it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object + * or similar is used if available, for maximum portability. + *

+ * + * @param width Pbuffer width + * @param height Pbuffer height + * @param pixel_format Minimum Pbuffer context properties + * @param renderTexture + * @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share + * with the Display context (if created). + */ + public Pbuffer(int width, int height, PixelFormat pixel_format, RenderTexture renderTexture, Drawable shared_drawable) throws LWJGLException { + this(width, height, pixel_format, renderTexture, shared_drawable, null); + } + + /** + * Create an instance of a Pbuffer with a unique OpenGL context. The buffer is single-buffered. + *

+ * NOTE: The Pbuffer will have its own context that shares display lists and textures with shared_context, + * or, if shared_context is null, the Display context if it is created. The Pbuffer + * will have its own OpenGL state. Therefore, state changes to a pbuffer will not be seen in the window context and vice versa. + *

+ * The renderTexture parameter defines the necessary state for enabling render-to-texture. When this parameter is null, + * render-to-texture is not available. Before using render-to-texture, the Pbuffer capabilities must be queried to ensure that + * it is supported. Currently only windows platform can support this feature, so it is recommended that EXT_framebuffer_object + * or similar is used if available, for maximum portability. + *

+ * + * @param width Pbuffer width + * @param height Pbuffer height + * @param pixel_format Minimum Pbuffer context properties + * @param renderTexture + * @param shared_drawable If non-null the Pbuffer will share display lists and textures with it. Otherwise, the Pbuffer will share + * with the Display context (if created). + * @param attribs The ContextAttribs to use when creating the context. (optional, may be null) + */ + public Pbuffer(int width, int height, PixelFormat pixel_format, RenderTexture renderTexture, Drawable shared_drawable, ContextAttribs attribs) throws LWJGLException { + if (pixel_format == null) + throw new NullPointerException("Pixel format must be non-null"); + this.width = width; + this.height = height; + this.peer_info = createPbuffer(width, height, pixel_format, attribs, renderTexture); + Context shared_context = null; + if ( shared_drawable == null ) + shared_drawable = Display.getDrawable(); // May be null + if (shared_drawable != null) + shared_context = ((DrawableLWJGL)shared_drawable).getContext(); + //this.context = new ContextGL(peer_info, attribs, (ContextGL)shared_context); + } + + private static PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, ContextAttribs attribs, RenderTexture renderTexture) throws LWJGLException { + if ( renderTexture == null ) { + // Though null is a perfectly valid argument, Matrox Parhelia drivers expect + // a 0 terminated list, or else they crash. Supplying NULL or 0, should + // cause the drivers to use default settings + IntBuffer defaultAttribs = BufferUtils.createIntBuffer(1); + return Display.getImplementation().createPbuffer(width, height, pixel_format, attribs, null, defaultAttribs); + } else + return Display.getImplementation().createPbuffer(width, height, pixel_format, attribs, + renderTexture.pixelFormatCaps, + renderTexture.pBufferAttribs); + } + + /** + * Method to test for validity of the buffer. If this function returns true, the buffer contents is lost. The buffer can still + * be used, but the results are undefined. The application is expected to release the buffer if needed, destroy it and recreate + * a new buffer. + * + * @return true if the buffer is lost and destroyed, false if the buffer is valid. + */ + public synchronized boolean isBufferLost() { + checkDestroyed(); + return Display.getImplementation().isBufferLost(peer_info); + } + + /** + * Gets the Pbuffer capabilities. + * + * @return a bitmask of Pbuffer capabilities. + */ + public static int getCapabilities() { + return Display.getImplementation().getPbufferCapabilities(); + } + + // ----------------------------------------------------------------------------------------- + // ------------------------------- Render-to-Texture Methods ------------------------------- + // ----------------------------------------------------------------------------------------- + + /** + * Sets a render-to-texture attribute. + *

+ * The attrib parameter can be one of MIPMAP_LEVEL and CUBE_MAP_FACE. When the attrib parameter is CUBE_MAP_FACE then the value + * parameter can be on of the following: + *

+ * TEXTURE_CUBE_MAP_POSITIVE_X TEXTURE_CUBE_MAP_NEGATIVE_X TEXTURE_CUBE_MAP_POSITIVE_Y TEXTURE_CUBE_MAP_NEGATIVE_Y + * TEXTURE_CUBE_MAP_POSITIVE_Z TEXTURE_CUBE_MAP_NEGATIVE_Z + * + * @param attrib + * @param value + */ + public synchronized void setAttrib(int attrib, int value) { + checkDestroyed(); + Display.getImplementation().setPbufferAttrib(peer_info, attrib, value); + } + + /** + * Binds the currently bound texture to the buffer specified. The buffer can be one of the following: + *

+ * FRONT_LEFT_BUFFER FRONT_RIGHT_BUFFER BACK_LEFT_BUFFER BACK_RIGHT_BUFFER DEPTH_BUFFER + * + * @param buffer + */ + public synchronized void bindTexImage(int buffer) { + checkDestroyed(); + Display.getImplementation().bindTexImageToPbuffer(peer_info, buffer); + } + + /** + * Releases the currently bound texture from the buffer specified. + * + * @param buffer + */ + public synchronized void releaseTexImage(int buffer) { + checkDestroyed(); + Display.getImplementation().releaseTexImageFromPbuffer(peer_info, buffer); + } + + /** + * @return Returns the height. + */ + public synchronized int getHeight() { + checkDestroyed(); + return height; + } + + /** + * @return Returns the width. + */ + public synchronized int getWidth() { + checkDestroyed(); + return width; + } +} diff --git a/src/main/java/org/lwjglx/opengl/PeerInfo.java b/src/main/java/org/lwjglx/opengl/PeerInfo.java new file mode 100644 index 0000000..91c55ff --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/PeerInfo.java @@ -0,0 +1,97 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import java.nio.ByteBuffer; + +import org.lwjglx.LWJGLException; +import org.lwjglx.LWJGLUtil; + +/** + * + * @author elias_naur + * @version $Revision$ + * $Id$ + */ +abstract class PeerInfo { + private final ByteBuffer handle; + private Thread locking_thread; // Thread that has locked this PeerInfo + private int lock_count; + + protected PeerInfo(ByteBuffer handle) { + this.handle = handle; + } + + private void lockAndInitHandle() throws LWJGLException { + doLockAndInitHandle(); + } + + public final synchronized void unlock() throws LWJGLException { + if (lock_count <= 0) + throw new IllegalStateException("PeerInfo not locked!"); + if (Thread.currentThread() != locking_thread) + throw new IllegalStateException("PeerInfo already locked by " + locking_thread); + lock_count--; + if (lock_count == 0) { + doUnlock(); + locking_thread = null; + notify(); + } + } + + protected abstract void doLockAndInitHandle() throws LWJGLException; + protected abstract void doUnlock() throws LWJGLException; + + public final synchronized ByteBuffer lockAndGetHandle() throws LWJGLException { + Thread this_thread = Thread.currentThread(); + while (locking_thread != null && locking_thread != this_thread) { + try { + wait(); + } catch (InterruptedException e) { + LWJGLUtil.log("Interrupted while waiting for PeerInfo lock: " + e); + } + } + if (lock_count == 0) { + locking_thread = this_thread; + doLockAndInitHandle(); + } + lock_count++; + return getHandle(); + } + + protected final ByteBuffer getHandle() { + return handle; + } + + public void destroy() { + } +} diff --git a/src/main/java/org/lwjglx/opengl/PixelFormat.java b/src/main/java/org/lwjglx/opengl/PixelFormat.java new file mode 100644 index 0000000..64d12ff --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/PixelFormat.java @@ -0,0 +1,424 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * This class describes pixel format properties for an OpenGL context. Instances + * of this class is used as arguments to Display.create(), Pbuffer.create() and + * AWTGLCanvas, to indicate minimum required properties. + *

+ * Instants of this class are immutable. An example of the expected way to set + * the PixelFormat property values is the following: + * PixelFormat pf = new PixelFormat().withDepthBits(24).withSamples(4).withSRGB(true); + *

+ * WARNING: Some pixel formats are known to cause troubles on certain buggy drivers. + * Example: Under Windows, specifying samples != 0 will enable the ARB + * pixel format selection path, which could trigger a crash. + * + * @author elias_naur@sourceforge.net + * @version $Revision$ + */ +public final class PixelFormat implements PixelFormatLWJGL { + + /** + * The number of bits per pixel, exluding alpha. + * This parameter is ignored in Display.create(). + */ + private int bpp; + /** The number of alpha bits. */ + private int alpha; + /** The number of depth buffer bits */ + private int depth; + /** The number of stencil bits */ + private int stencil; + /** + * The number of samples to use in anti-aliasing. + * 0 means that anti-aliasing is disabled. + */ + private int samples; + /** + * The number of COLOR_SAMPLES_NV to use for Coverage Sample Anti-aliasing (CSAA). + * When this number is greater than 0, the {@code samples} property will be treated + * as if it were the COVERAGE_SAMPLES_NV property. + *

+ * This property is currently a no-op for the MacOS implementation. + */ + private int colorSamples; + /** The number of auxiliary buffers */ + private int num_aux_buffers; + /** The number of bits per pixel in the accumulation buffer */ + private int accum_bpp; + /** The number of alpha bits in the accumulation buffer */ + private int accum_alpha; + /** Whether this format requires a stereo buffer */ + private boolean stereo; + /** Whether this format specifies a floating point format */ + private boolean floating_point; + /** + * Whether this format specifies a packed floating point format (32 bit unsigned - R11F_G11F_B10F) + * This property is currently a no-op for the MacOS implementation. + */ + private boolean floating_point_packed; + /** + * Whether this format specifies an sRGB format + * This property is currently a no-op for the MacOS implementation. + */ + private boolean sRGB; + + /** + * Default pixel format is minimum 8 bits depth, and no alpha + * nor stencil requirements. + */ + public PixelFormat() { + this(0, 8, 0); + } + + public PixelFormat(int alpha, int depth, int stencil) { + this(alpha, depth, stencil, 0); + } + + public PixelFormat(int alpha, int depth, int stencil, int samples) { + this(0, alpha, depth, stencil, samples); + } + + public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples) { + this(bpp, alpha, depth, stencil, samples, 0, 0, 0, false); + } + + public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples, int num_aux_buffers, int accum_bpp, int accum_alpha, boolean stereo) { + this(bpp, alpha, depth, stencil, samples, num_aux_buffers, accum_bpp, accum_alpha, stereo, false); + } + + public PixelFormat(int bpp, int alpha, int depth, int stencil, int samples, int num_aux_buffers, int accum_bpp, int accum_alpha, boolean stereo, boolean floating_point) { + this.bpp = bpp; + this.alpha = alpha; + this.depth = depth; + this.stencil = stencil; + + this.samples = samples; + + this.num_aux_buffers = num_aux_buffers; + + this.accum_bpp = accum_bpp; + this.accum_alpha = accum_alpha; + + this.stereo = stereo; + + this.floating_point = floating_point; + this.floating_point_packed = false; + this.sRGB = false; + } + + private PixelFormat(final PixelFormat pf) { + this.bpp = pf.bpp; + this.alpha = pf.alpha; + this.depth = pf.depth; + this.stencil = pf.stencil; + + this.samples = pf.samples; + this.colorSamples = pf.colorSamples; + + this.num_aux_buffers = pf.num_aux_buffers; + + this.accum_bpp = pf.accum_bpp; + this.accum_alpha = pf.accum_alpha; + + this.stereo = pf.stereo; + + this.floating_point = pf.floating_point; + this.floating_point_packed = pf.floating_point_packed; + this.sRGB = pf.sRGB; + } + + public int getBitsPerPixel() { + return bpp; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel value. + * + * @param bpp the new bits per pixel value. + * + * @return the new PixelFormat + */ + public PixelFormat withBitsPerPixel(final int bpp) { + if ( bpp < 0 ) + throw new IllegalArgumentException("Invalid number of bits per pixel specified: " + bpp); + + final PixelFormat pf = new PixelFormat(this); + pf.bpp = bpp; + return pf; + } + + public int getAlphaBits() { + return alpha; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits value. + * + * @param alpha the new alpha bits value. + * + * @return the new PixelFormat + */ + public PixelFormat withAlphaBits(final int alpha) { + if ( alpha < 0 ) + throw new IllegalArgumentException("Invalid number of alpha bits specified: " + alpha); + + final PixelFormat pf = new PixelFormat(this); + pf.alpha = alpha; + return pf; + } + + public int getDepthBits() { + return depth; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new depth bits value. + * + * @param depth the new depth bits value. + * + * @return the new PixelFormat + */ + public PixelFormat withDepthBits(final int depth) { + if ( depth < 0 ) + throw new IllegalArgumentException("Invalid number of depth bits specified: " + depth); + + final PixelFormat pf = new PixelFormat(this); + pf.depth = depth; + return pf; + } + + public int getStencilBits() { + return stencil; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new stencil bits value. + * + * @param stencil the new stencil bits value. + * + * @return the new PixelFormat + */ + public PixelFormat withStencilBits(final int stencil) { + if ( stencil < 0 ) + throw new IllegalArgumentException("Invalid number of stencil bits specified: " + stencil); + + final PixelFormat pf = new PixelFormat(this); + pf.stencil = stencil; + return pf; + } + + public int getSamples() { + return samples; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new samples value. + * + * @param samples the new samples value. + * + * @return the new PixelFormat + */ + public PixelFormat withSamples(final int samples) { + if ( samples < 0 ) + throw new IllegalArgumentException("Invalid number of samples specified: " + samples); + + final PixelFormat pf = new PixelFormat(this); + pf.samples = samples; + return pf; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples values. + * A value greater than 0 is valid only if the {@code samples} property is also greater than 0. Additionally, the + * color samples value needs to be lower than or equal to the {@code samples} property. + * + * @param colorSamples the new color samples value. + * + * @return the new PixelFormat + */ + public PixelFormat withCoverageSamples(final int colorSamples) { + return withCoverageSamples(colorSamples, samples); + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new color samples + * and coverage samples values. + * + * @param colorSamples the new color samples value. This value must be lower than or equal to the coverage samples value. + * @param coverageSamples the new coverage samples value. + * + * @return the new PixelFormat + */ + public PixelFormat withCoverageSamples(final int colorSamples, final int coverageSamples) { + if ( coverageSamples < 0 || colorSamples < 0 || (coverageSamples == 0 && 0 < colorSamples) || coverageSamples < colorSamples ) + throw new IllegalArgumentException("Invalid number of coverage samples specified: " + coverageSamples + " - " + colorSamples); + + final PixelFormat pf = new PixelFormat(this); + pf.samples = coverageSamples; + pf.colorSamples = colorSamples; + return pf; + } + + public int getAuxBuffers() { + return num_aux_buffers; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new auxiliary buffers value. + * + * @param num_aux_buffers the new auxiliary buffers value. + * + * @return the new PixelFormat + */ + public PixelFormat withAuxBuffers(final int num_aux_buffers) { + if ( num_aux_buffers < 0 ) + throw new IllegalArgumentException("Invalid number of auxiliary buffers specified: " + num_aux_buffers); + + final PixelFormat pf = new PixelFormat(this); + pf.num_aux_buffers = num_aux_buffers; + return pf; + } + + public int getAccumulationBitsPerPixel() { + return accum_bpp; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel in the accumulation buffer value. + * + * @param accum_bpp the new bits per pixel in the accumulation buffer value. + * + * @return the new PixelFormat + */ + public PixelFormat withAccumulationBitsPerPixel(final int accum_bpp) { + if ( accum_bpp < 0 ) + throw new IllegalArgumentException("Invalid number of bits per pixel in the accumulation buffer specified: " + accum_bpp); + + final PixelFormat pf = new PixelFormat(this); + pf.accum_bpp = accum_bpp; + return pf; + } + + public int getAccumulationAlpha() { + return accum_alpha; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits in the accumulation buffer value. + * + * @param accum_alpha the new alpha bits in the accumulation buffer value. + * + * @return the new PixelFormat + */ + public PixelFormat withAccumulationAlpha(final int accum_alpha) { + if ( accum_alpha < 0 ) + throw new IllegalArgumentException("Invalid number of alpha bits in the accumulation buffer specified: " + accum_alpha); + + final PixelFormat pf = new PixelFormat(this); + pf.accum_alpha = accum_alpha; + return pf; + } + + public boolean isStereo() { + return stereo; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new stereo value. + * + * @param stereo the new stereo value. + * + * @return the new PixelFormat + */ + public PixelFormat withStereo(final boolean stereo) { + final PixelFormat pf = new PixelFormat(this); + pf.stereo = stereo; + return pf; + } + + public boolean isFloatingPoint() { + return floating_point; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new floating point value. + * If floating_point is true, floating_point_packed will be reset to false. + * + * @param floating_point the new floating point value. + * + * @return the new PixelFormat + */ + public PixelFormat withFloatingPoint(final boolean floating_point) { + final PixelFormat pf = new PixelFormat(this); + pf.floating_point = floating_point; + if ( floating_point ) + pf.floating_point_packed = false; + return pf; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new packed floating point value. + * If floating_point_packed is true, floating_point will be reset to false. + * + * @param floating_point_packed the new packed floating point value. + * + * @return the new PixelFormat + */ + public PixelFormat withFloatingPointPacked(final boolean floating_point_packed) { + final PixelFormat pf = new PixelFormat(this); + pf.floating_point_packed = floating_point_packed; + if ( floating_point_packed ) + pf.floating_point = false; + return pf; + } + + public boolean isSRGB() { + return sRGB; + } + + /** + * Returns a new PixelFormat object with the same properties as this PixelFormat and the new sRGB value. + * + * @param sRGB the new floating point value. + * + * @return the new PixelFormat + */ + public PixelFormat withSRGB(final boolean sRGB) { + final PixelFormat pf = new PixelFormat(this); + pf.sRGB = sRGB; + return pf; + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/PixelFormatLWJGL.java b/src/main/java/org/lwjglx/opengl/PixelFormatLWJGL.java new file mode 100644 index 0000000..c3f54df --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/PixelFormatLWJGL.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2002-2011 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +/** + * [INTERNAL USE ONLY] + * + * @author Spasi + */ +public interface PixelFormatLWJGL { + // Marker interface +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/RenderTexture.java b/src/main/java/org/lwjglx/opengl/RenderTexture.java new file mode 100644 index 0000000..60dd71d --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/RenderTexture.java @@ -0,0 +1,251 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; + +import static org.lwjgl.opengl.GL11.*; + +/** This class represents the state necessary for render-to-texture. */ +public final class RenderTexture { + + // ---------------------------------------------------------------------------------- + // ----------------------------- WGL_ARB_render_texture ----------------------------- + // ---------------------------------------------------------------------------------- + + /* + Accepted by the parameter of wglGetPixelFormatAttribivARB, + wglGetPixelFormatAttribfvARB, and the and + parameters of wglChoosePixelFormatARB: + */ + private static final int WGL_BIND_TO_TEXTURE_RGB_ARB = 0x2070; + private static final int WGL_BIND_TO_TEXTURE_RGBA_ARB = 0x2071; + + /* + Accepted by the parameter of wglCreatePbufferARB and + by the parameter of wglQueryPbufferARB: + */ + private static final int WGL_TEXTURE_FORMAT_ARB = 0x2072; + private static final int WGL_TEXTURE_TARGET_ARB = 0x2073; + private static final int WGL_MIPMAP_TEXTURE_ARB = 0x2074; + + /* + Accepted as a value in the parameter of + wglCreatePbufferARB and returned in the value parameter of + wglQueryPbufferARB when is WGL_TEXTURE_FORMAT_ARB: + */ + private static final int WGL_TEXTURE_RGB_ARB = 0x2075; + private static final int WGL_TEXTURE_RGBA_ARB = 0x2076; + + /* + Accepted as a value in the parameter of + wglCreatePbufferARB and returned in the value parameter of + wglQueryPbufferARB when is WGL_TEXTURE_TARGET_ARB: + */ + private static final int WGL_TEXTURE_CUBE_MAP_ARB = 0x2078; + private static final int WGL_TEXTURE_1D_ARB = 0x2079; + private static final int WGL_TEXTURE_2D_ARB = 0x207A; + private static final int WGL_NO_TEXTURE_ARB = 0x2077; + + /* + Accepted by the parameter of wglSetPbufferAttribARB and + by the parameter of wglQueryPbufferARB: + */ + static final int WGL_MIPMAP_LEVEL_ARB = 0x207B; + static final int WGL_CUBE_MAP_FACE_ARB = 0x207C; + + /* + Accepted as a value in the parameter of + wglSetPbufferAttribARB and returned in the value parameter of + wglQueryPbufferARB when is WGL_CUBE_MAP_FACE_ARB: + */ + static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 0x207D; + static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 0x207E; + static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 0x207F; + static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 0x2080; + static final int WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 0x2081; + static final int WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 0x2082; + + /* + Accepted by the parameter of wglBindTexImageARB and + wglReleaseTexImageARB: + */ + static final int WGL_FRONT_LEFT_ARB = 0x2083; + static final int WGL_FRONT_RIGHT_ARB = 0x2084; + static final int WGL_BACK_LEFT_ARB = 0x2085; + static final int WGL_BACK_RIGHT_ARB = 0x2086; + + /* + private static final int WGL_AUX0_ARB = 0x2087; + private static final int WGL_AUX1_ARB = 0x2088; + private static final int WGL_AUX2_ARB = 0x2089; + private static final int WGL_AUX3_ARB = 0x208A; + private static final int WGL_AUX4_ARB = 0x208B; + private static final int WGL_AUX5_ARB = 0x208C; + private static final int WGL_AUX6_ARB = 0x208D; + private static final int WGL_AUX7_ARB = 0x208E; + private static final int WGL_AUX8_ARB = 0x208F; + private static final int WGL_AUX9_ARB = 0x2090; + */ + + // ------------------------------------------------------------------------------------------- + // ----------------------------- WGL_NV_render_texture_rectangle ----------------------------- + // ------------------------------------------------------------------------------------------- + + /* + Accepted by the parameter of wglGetPixelFormatAttribivARB, + wglGetPixelFormatAttribfvARB, and the and + parameters of wglChoosePixelFormatARB: + */ + private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV = 0x20A0; + private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV = 0x20A1; + + /* + Accepted as a value in the parameter of wglCreatePbufferARB + and returned in the value parameter of wglQueryPbufferARB when + is WGL_TEXTURE_TARGET_ARB: + */ + private static final int WGL_TEXTURE_RECTANGLE_NV = 0x20A2; + + // --------------------------------------------------------------------------------------- + // ----------------------------- WGL_NV_render_depth_texture ----------------------------- + // --------------------------------------------------------------------------------------- + + /* + Accepted by the parameter of wglGetPixelFormatAttribivARB, + wglGetPixelFormatAttribfvARB, and the and + parameters of wglChoosePixelFormatARB: + */ + private static final int WGL_BIND_TO_TEXTURE_DEPTH_NV = 0x20A3; + private static final int WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV = 0x20A4; + + /* + Accepted by the parameter of wglCreatePbufferARB and + by the parameter of wglQueryPbufferARB: + */ + private static final int WGL_DEPTH_TEXTURE_FORMAT_NV = 0x20A5; + + /* + Accepted as a value in the parameter of wglCreatePbufferARB + and returned in the value parameter of wglQueryPbufferARB when + is WGL_DEPTH_TEXTURE_FORMAT_NV: + */ + private static final int WGL_TEXTURE_DEPTH_COMPONENT_NV = 0x20A6; + + /* + Accepted by the parameter of wglBindTexImageARB: + */ + static final int WGL_DEPTH_COMPONENT_NV = 0x20A7; + + /** The TEXTURE_1D target. */ + public static final int RENDER_TEXTURE_1D = WGL_TEXTURE_1D_ARB; + + /** The TEXTURE_2D target. */ + public static final int RENDER_TEXTURE_2D = WGL_TEXTURE_2D_ARB; + + /** The TEXTURE_RECTANGLE target. */ + public static final int RENDER_TEXTURE_RECTANGLE = WGL_TEXTURE_RECTANGLE_NV; + + /** The TEXTURE_CUBE_MAP target. */ + public static final int RENDER_TEXTURE_CUBE_MAP = WGL_TEXTURE_CUBE_MAP_ARB; + + IntBuffer pixelFormatCaps; + IntBuffer pBufferAttribs; + + /** + * Creates a RenderTexture object for enabling render-to-texture on a P-buffer. + *

+ * NOTE: Only one of useRGB and useRGBA can be true at the same time. + *

+ * NOTE: useRGB(A) and useDepth can be true at the same time, thus allowing two different render textures. + *

+ * NOTE: The target parameter can be one of the following: + *

+ * RENDER_TEXTURE_1D RENDER_TEXTURE_2D RENDER_TEXTURE_RECTANGLE RENDER_TEXTURE_CUBE_MAP + * + * @param useRGB - When true the P-buffer can be used as an RGB render texture. + * @param useRGBA - When true the P-buffer can be used as an RGBA render texture. + * @param useDepth - When true the P-buffer can be used as a depth render texture. + * @param isRectangle - When true rectangle textures will be allowed on the P-buffer. + * @param target - The texture target of the render texture. + * @param mipmaps - How many mipmap levels to allocate on the P-buffer. + */ + public RenderTexture(boolean useRGB, boolean useRGBA, boolean useDepth, boolean isRectangle, int target, int mipmaps) { + if ( useRGB && useRGBA ) + throw new IllegalArgumentException("A RenderTexture can't be both RGB and RGBA."); + + if ( mipmaps < 0 ) + throw new IllegalArgumentException("The mipmap levels can't be negative."); + + if ( isRectangle && target != RENDER_TEXTURE_RECTANGLE ) + throw new IllegalArgumentException("When the RenderTexture is rectangle the target must be RENDER_TEXTURE_RECTANGLE."); + + pixelFormatCaps = BufferUtils.createIntBuffer(4); + pBufferAttribs = BufferUtils.createIntBuffer(8); + + if ( useRGB ) { + pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV : WGL_BIND_TO_TEXTURE_RGB_ARB); + pixelFormatCaps.put(GL_TRUE); + + pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB); + pBufferAttribs.put(WGL_TEXTURE_RGB_ARB); + } else if ( useRGBA ) { + pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV : WGL_BIND_TO_TEXTURE_RGBA_ARB); + pixelFormatCaps.put(GL_TRUE); + + pBufferAttribs.put(WGL_TEXTURE_FORMAT_ARB); + pBufferAttribs.put(WGL_TEXTURE_RGBA_ARB); + } + + if ( useDepth ) { + pixelFormatCaps.put(isRectangle ? WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV : WGL_BIND_TO_TEXTURE_DEPTH_NV); + pixelFormatCaps.put(GL_TRUE); + + pBufferAttribs.put(WGL_DEPTH_TEXTURE_FORMAT_NV); + pBufferAttribs.put(WGL_TEXTURE_DEPTH_COMPONENT_NV); + } + + pBufferAttribs.put(WGL_TEXTURE_TARGET_ARB); + pBufferAttribs.put(target); + + if ( mipmaps != 0 ) { + pBufferAttribs.put(WGL_MIPMAP_TEXTURE_ARB); + pBufferAttribs.put(mipmaps); + } + + pixelFormatCaps.flip(); + pBufferAttribs.flip(); + } + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/Sync.java b/src/main/java/org/lwjglx/opengl/Sync.java new file mode 100644 index 0000000..3c65321 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Sync.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2002-2012 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import org.lwjglx.Sys; + +/** +* A highly accurate sync method that continually adapts to the system +* it runs on to provide reliable results. +* +* @author Riven +* @author kappaOne +*/ +class Sync { + + /** number of nano seconds in a second */ + private static final long NANOS_IN_SECOND = 1000L * 1000L * 1000L; + + /** The time to sleep/yield until the next frame */ + private static long nextFrame = 0; + + /** whether the initialisation code has run */ + private static boolean initialised = false; + + /** for calculating the averages the previous sleep/yield times are stored */ + private static RunningAvg sleepDurations = new RunningAvg(10); + private static RunningAvg yieldDurations = new RunningAvg(10); + + + /** + * An accurate sync method that will attempt to run at a constant frame rate. + * It should be called once every frame. + * + * @param fps - the desired frame rate, in frames per second + */ + public static void sync(int fps) { + if (fps <= 0) return; + if (!initialised) initialise(); + + try { + // sleep until the average sleep time is greater than the time remaining till nextFrame + for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) { + Thread.sleep(1); + sleepDurations.add((t1 = getTime()) - t0); // update average sleep time + } + + // slowly dampen sleep average if too high to avoid yielding too much + sleepDurations.dampenForLowResTicker(); + + // yield until the average yield time is greater than the time remaining till nextFrame + for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) { + Thread.yield(); + yieldDurations.add((t1 = getTime()) - t0); // update average yield time + } + } catch (InterruptedException e) { + + } + + // schedule next frame, drop frame(s) if already too late for next frame + nextFrame = Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime()); + } + + /** + * This method will initialise the sync method by setting initial + * values for sleepDurations/yieldDurations and nextFrame. + * + * If running on windows it will start the sleep timer fix. + */ + private static void initialise() { + initialised = true; + + sleepDurations.init(1000 * 1000); + yieldDurations.init((int) (-(getTime() - getTime()) * 1.333)); + + nextFrame = getTime(); + + String osName = System.getProperty("os.name"); + + if (osName.startsWith("Win")) { + // On windows the sleep functions can be highly inaccurate by + // over 10ms making in unusable. However it can be forced to + // be a bit more accurate by running a separate sleeping daemon + // thread. + Thread timerAccuracyThread = new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(Long.MAX_VALUE); + } catch (Exception e) {} + } + }); + + timerAccuracyThread.setName("LWJGL Timer"); + timerAccuracyThread.setDaemon(true); + timerAccuracyThread.start(); + } + } + + /** + * Get the system time in nano seconds + * + * @return will return the current time in nano's + */ + private static long getTime() { + return (Sys.getTime() * NANOS_IN_SECOND) / Sys.getTimerResolution(); + } + + private static class RunningAvg { + private final long[] slots; + private int offset; + + private static final long DAMPEN_THRESHOLD = 10 * 1000L * 1000L; // 10ms + private static final float DAMPEN_FACTOR = 0.9f; // don't change: 0.9f is exactly right! + + public RunningAvg(int slotCount) { + this.slots = new long[slotCount]; + this.offset = 0; + } + + public void init(long value) { + while (this.offset < this.slots.length) { + this.slots[this.offset++] = value; + } + } + + public void add(long value) { + this.slots[this.offset++ % this.slots.length] = value; + this.offset %= this.slots.length; + } + + public long avg() { + long sum = 0; + for (int i = 0; i < this.slots.length; i++) { + sum += this.slots[i]; + } + return sum / this.slots.length; + } + + public void dampenForLowResTicker() { + if (this.avg() > DAMPEN_THRESHOLD) { + for (int i = 0; i < this.slots.length; i++) { + this.slots[i] *= DAMPEN_FACTOR; + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/opengl/Util.java b/src/main/java/org/lwjglx/opengl/Util.java new file mode 100644 index 0000000..3811fe0 --- /dev/null +++ b/src/main/java/org/lwjglx/opengl/Util.java @@ -0,0 +1,90 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.opengl; + +import static org.lwjgl.opengl.ARBImaging.*; +import static org.lwjgl.opengl.GL11.*; +import static org.lwjgl.opengl.GL30.*; + +import org.lwjgl.opengl.GLContext; + +/** + * Simple utility class. + * + * @author cix_foo + * @version $Revision$ + */ + +public final class Util { + + static org.lwjgl.opengl.GLContext glContext = GLContext.createFromCurrent(); + + /** No c'tor */ + private Util() { + } + + /** + * Throws OpenGLException if glGetError() returns anything else than GL_NO_ERROR + * + */ + public static void checkGLError() throws OpenGLException { + glContext.checkGLError(); + } + + /** + * Translate a GL error code to a String describing the error + */ + public static String translateGLErrorString(int error_code) { + switch (error_code) { + case GL_NO_ERROR: + return "No error"; + case GL_INVALID_ENUM: + return "Invalid enum"; + case GL_INVALID_VALUE: + return "Invalid value"; + case GL_INVALID_OPERATION: + return "Invalid operation"; + case GL_STACK_OVERFLOW: + return "Stack overflow"; + case GL_STACK_UNDERFLOW: + return "Stack underflow"; + case GL_OUT_OF_MEMORY: + return "Out of memory"; + case GL_TABLE_TOO_LARGE: + return "Table too large"; + case GL_INVALID_FRAMEBUFFER_OPERATION: + return "Invalid framebuffer operation"; + default: + return null; + } + } +} diff --git a/src/main/java/org/lwjglx/test/opengl/Gears.java b/src/main/java/org/lwjglx/test/opengl/Gears.java new file mode 100644 index 0000000..b786237 --- /dev/null +++ b/src/main/java/org/lwjglx/test/opengl/Gears.java @@ -0,0 +1,343 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* + * 3-D gear wheels. Originally by Brian Paul + */ +package org.lwjglx.test.opengl; + +import java.nio.FloatBuffer; + +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLException; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.Sys; +import org.lwjglx.opengl.Display; +import org.lwjglx.opengl.DisplayMode; +import org.lwjglx.opengl.GLContext; + +import static org.lwjgl.opengl.ARBTransposeMatrix.*; +import static org.lwjgl.opengl.GL11.*; + +/** + *

+ * This is the OpenGL "standard" Gears demo, originally by Brian Paul + *

+ * @author Brian Matzon + * @version $Revision: 3418 $ + * $Id: Gears.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public class Gears { + + private float view_rotx = 20.0f; + + private float view_roty = 30.0f; + + private float view_rotz; + + private int gear1; + + private int gear2; + + private int gear3; + + private float angle; + + public static void main(String[] args) { + new Gears().execute(); + System.exit(0); + } + + /** + * + */ + private void execute() { + try { + init(); + } catch (LWJGLException le) { + le.printStackTrace(); + System.out.println("Failed to initialize Gears."); + return; + } + + loop(); + + destroy(); + } + + /** + * + */ + private void destroy() { + Display.destroy(); + } + + /** + * + */ + private void loop() { + long startTime = System.currentTimeMillis() + 5000; + long fps = 0; + + while (!Display.isCloseRequested()) { + angle += 2.0f; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glPushMatrix(); + glRotatef(view_rotx, 1.0f, 0.0f, 0.0f); + glRotatef(view_roty, 0.0f, 1.0f, 0.0f); + glRotatef(view_rotz, 0.0f, 0.0f, 1.0f); + + glPushMatrix(); + glTranslatef(-3.0f, -2.0f, 0.0f); + glRotatef(angle, 0.0f, 0.0f, 1.0f); + glCallList(gear1); + glPopMatrix(); + + glPushMatrix(); + glTranslatef(3.1f, -2.0f, 0.0f); + glRotatef(-2.0f * angle - 9.0f, 0.0f, 0.0f, 1.0f); + glCallList(gear2); + glPopMatrix(); + + glPushMatrix(); + glTranslatef(-3.1f, 4.2f, 0.0f); + glRotatef(-2.0f * angle - 25.0f, 0.0f, 0.0f, 1.0f); + glCallList(gear3); + glPopMatrix(); + + glPopMatrix(); + + Display.update(); + if (startTime > System.currentTimeMillis()) { + fps++; + } else { + long timeUsed = 5000 + (startTime - System.currentTimeMillis()); + startTime = System.currentTimeMillis() + 5000; + System.out.println(fps + " frames in " + timeUsed / 1000f + " seconds = " + + (fps / (timeUsed / 1000f))); + fps = 0; + } + } + } + + /** + * + */ + private void init() throws LWJGLException { + // create Window of size 300x300 + Display.setLocation((Display.getDisplayMode().getWidth() - 300) / 2, + (Display.getDisplayMode().getHeight() - 300) / 2); + Display.setDisplayMode(new DisplayMode(300, 300)); + Display.setTitle("Gears"); + Display.create(); + + // setup ogl + FloatBuffer pos = BufferUtils.createFloatBuffer(4).put(new float[] { 5.0f, 5.0f, 10.0f, 0.0f}); + FloatBuffer red = BufferUtils.createFloatBuffer(4).put(new float[] { 0.8f, 0.1f, 0.0f, 1.0f}); + FloatBuffer green = BufferUtils.createFloatBuffer(4).put(new float[] { 0.0f, 0.8f, 0.2f, 1.0f}); + FloatBuffer blue = BufferUtils.createFloatBuffer(4).put(new float[] { 0.2f, 0.2f, 1.0f, 1.0f}); + + pos.flip(); + red.flip(); + green.flip(); + blue.flip(); + + glLight(GL_LIGHT0, GL_POSITION, pos); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glEnable(GL_DEPTH_TEST); + + /* make the gears */ + gear1 = glGenLists(1); + glNewList(gear1, GL_COMPILE); + glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red); + gear(1.0f, 4.0f, 1.0f, 20, 0.7f); + glEndList(); + + gear2 = glGenLists(1); + glNewList(gear2, GL_COMPILE); + glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green); + gear(0.5f, 2.0f, 2.0f, 10, 0.7f); + glEndList(); + + gear3 = glGenLists(1); + glNewList(gear3, GL_COMPILE); + glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue); + gear(1.3f, 2.0f, 0.5f, 10, 0.7f); + glEndList(); + + glEnable(GL_NORMALIZE); + + glMatrixMode(GL_PROJECTION); + + System.err.println("LWJGL: " + Sys.getVersion() + " / " + LWJGLUtil.getPlatformName()); + System.err.println("GL_VENDOR: " + glGetString(GL_VENDOR)); + System.err.println("GL_RENDERER: " + glGetString(GL_RENDERER)); + System.err.println("GL_VERSION: " + glGetString(GL_VERSION)); + System.err.println(); + System.err.println("glLoadTransposeMatrixfARB() supported: " + GLContext.getCapabilities().GL_ARB_transpose_matrix); + if (!GLContext.getCapabilities().GL_ARB_transpose_matrix) { + // --- not using extensions + glLoadIdentity(); + } else { + // --- using extensions + final FloatBuffer identityTranspose = BufferUtils.createFloatBuffer(16).put( + new float[] { 1, 0, 0, 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, 0, 0, 1}); + identityTranspose.flip(); + glLoadTransposeMatrixARB(identityTranspose); + } + + float h = (float) 300 / (float) 300; + glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0.0f, 0.0f, -40.0f); + } + + /** + * Draw a gear wheel. You'll probably want to call this function when + * building a display list since we do a lot of trig here. + * + * @param inner_radius radius of hole at center + * @param outer_radius radius at center of teeth + * @param width width of gear + * @param teeth number of teeth + * @param tooth_depth depth of tooth + */ + private void gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth) { + int i; + float r0, r1, r2; + float angle, da; + float u, v, len; + + r0 = inner_radius; + r1 = outer_radius - tooth_depth / 2.0f; + r2 = outer_radius + tooth_depth / 2.0f; + + da = 2.0f * (float) Math.PI / teeth / 4.0f; + + glShadeModel(GL_FLAT); + + glNormal3f(0.0f, 0.0f, 1.0f); + + /* draw front face */ + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f); + if (i < teeth) { + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle + 3.0f * da), r1 * (float) Math.sin(angle + 3.0f * da), + width * 0.5f); + } + } + glEnd(); + + /* draw front sides of teeth */ + glBegin(GL_QUADS); + for (i = 0; i < teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + 2.0f * da), r2 * (float) Math.sin(angle + 2.0f * da), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle + 3.0f * da), r1 * (float) Math.sin(angle + 3.0f * da), width * 0.5f); + } + glEnd(); + + /* draw back face */ + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f); + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f); + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f); + } + glEnd(); + + /* draw back sides of teeth */ + glBegin(GL_QUADS); + for (i = 0; i < teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f); + } + glEnd(); + + /* draw outward faces of teeth */ + glBegin(GL_QUAD_STRIP); + for (i = 0; i < teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle), r1 * (float) Math.sin(angle), -width * 0.5f); + u = r2 * (float) Math.cos(angle + da) - r1 * (float) Math.cos(angle); + v = r2 * (float) Math.sin(angle + da) - r1 * (float) Math.sin(angle); + len = (float) Math.sqrt(u * u + v * v); + u /= len; + v /= len; + glNormal3f(v, -u, 0.0f); + glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + da), r2 * (float) Math.sin(angle + da), -width * 0.5f); + glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f); + glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), width * 0.5f); + glVertex3f(r2 * (float) Math.cos(angle + 2 * da), r2 * (float) Math.sin(angle + 2 * da), -width * 0.5f); + u = r1 * (float) Math.cos(angle + 3 * da) - r2 * (float) Math.cos(angle + 2 * da); + v = r1 * (float) Math.sin(angle + 3 * da) - r2 * (float) Math.sin(angle + 2 * da); + glNormal3f(v, -u, 0.0f); + glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(angle + 3 * da), r1 * (float) Math.sin(angle + 3 * da), -width * 0.5f); + glNormal3f((float) Math.cos(angle), (float) Math.sin(angle), 0.0f); + } + glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), width * 0.5f); + glVertex3f(r1 * (float) Math.cos(0), r1 * (float) Math.sin(0), -width * 0.5f); + glEnd(); + + glShadeModel(GL_SMOOTH); + + /* draw inside radius cylinder */ + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= teeth; i++) { + angle = i * 2.0f * (float) Math.PI / teeth; + glNormal3f(-(float) Math.cos(angle), -(float) Math.sin(angle), 0.0f); + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), -width * 0.5f); + glVertex3f(r0 * (float) Math.cos(angle), r0 * (float) Math.sin(angle), width * 0.5f); + } + glEnd(); + } +} diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/AlienEntity.java b/src/main/java/org/lwjglx/test/spaceinvaders/AlienEntity.java new file mode 100644 index 0000000..6d75a57 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/AlienEntity.java @@ -0,0 +1,157 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +/** + * An entity which represents one of our space invader aliens. + * + * @author Kevin Glass + * @author Brian Matzon + */ +public class AlienEntity extends Entity { + + /** Movement made downwards when a border is hit */ + private static final int DOWNWARD_MOVEMENT = 10; + + /** Border at which player dies */ + private static final int BOTTOM_BORDER = 570; + + /** Right border at which to shift direction */ + private static final int RIGHT_BORDER = 750; + + /** Left border at which to shift direction */ + private static final int LEFT_BORDER = 10; + + /** The speed at which the alient moves horizontally */ + private float moveSpeed = 75; + + /** The game in which the entity exists */ + private Game game; + + /** The animation frames */ + private Sprite[] frames = new Sprite[4]; + + /** The time since the last frame change took place */ + private long lastFrameChange; + + /** The frame duration in milliseconds, i.e. how long any given frame of animation lasts */ + private long frameDuration = 250; + + /** The current frame of animation being displayed */ + private int frameNumber; + + /** + * Create a new alien entity + * + * @param game The game in which this entity is being created + * @param x The intial x location of this alien + * @param y The intial y location of this alient + */ + public AlienEntity(Game game, int x, int y) { + super(game.getSprite("alien.gif"), x, y); + + // setup the animatin frames + frames[0] = sprite; + frames[1] = game.getSprite("alien2.gif"); + frames[2] = sprite; + frames[3] = game.getSprite("alien3.gif"); + + this.game = game; + dx = -moveSpeed; + } + + /** + * Request that this alien moved based on time elapsed + * + * @param delta The time that has elapsed since last move + */ + public void move(long delta) { + // since the move tells us how much time has passed + // by we can use it to drive the animation, however + // its the not the prettiest solution + lastFrameChange += delta; + + // if we need to change the frame, update the frame number + // and flip over the sprite in use + if (lastFrameChange > frameDuration) { + // reset our frame change time counter + lastFrameChange = 0; + + // update the frame + frameNumber++; + if (frameNumber >= frames.length) { + frameNumber = 0; + } + + sprite = frames[frameNumber]; + } + + // if we have reached the left hand side of the screen and + // are moving left then request a logic update + if ((dx < 0) && (x < LEFT_BORDER)) { + game.updateLogic(); + } + // and vice vesa, if we have reached the right hand side of + // the screen and are moving right, request a logic update + if ((dx > 0) && (x > RIGHT_BORDER)) { + game.updateLogic(); + } + + // proceed with normal move + super.move(delta); + } + + /** + * Update the game logic related to aliens + */ + public void doLogic() { + // swap over horizontal movement and move down the + // screen a bit + dx = -dx; + y += DOWNWARD_MOVEMENT; + + // if we've reached the bottom of the screen then the player + // dies + if (y > BOTTOM_BORDER) { + game.notifyDeath(); + } + } + + /** + * Notification that this alien has collided with another entity + * + * @param other The other entity + */ + public void collidedWith(Entity other) { + // collisions with aliens are handled elsewhere + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/Entity.java b/src/main/java/org/lwjglx/test/spaceinvaders/Entity.java new file mode 100644 index 0000000..30ad4a8 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/Entity.java @@ -0,0 +1,184 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +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 { + + /** The current x location of this entity */ + protected float x; + + /** The current y location of this entity */ + protected float y; + + /** The sprite that represents this entity */ + protected Sprite sprite; + + /** The current speed of this entity horizontally (pixels/sec) */ + protected float dx; + + /** The current speed of this entity vertically (pixels/sec) */ + protected float dy; + + /** The rectangle used for this entity during collisions resolution */ + private Rectangle me = new Rectangle(); + + /** The rectangle used for other entities during collision resolution */ + private Rectangle him = new Rectangle(); + + /** + * Construct a entity based on a sprite image and a location. + * + * @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 + */ + protected Entity(Sprite sprite, int x, int y) { + this.sprite = sprite; + this.x = x; + this.y = y; + } + + /** + * 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) { + // update the location of the entity based on move speeds + x += (delta * dx) / 1000; + y += (delta * dy) / 1000; + } + + /** + * Set the horizontal speed of this entity + * + * @param dx The horizontal speed of this entity (pixels/sec) + */ + public void setHorizontalMovement(float dx) { + this.dx = dx; + } + + /** + * Set the vertical speed of this entity + * + * @param dy The vertical speed of this entity (pixels/sec) + */ + public void setVerticalMovement(float dy) { + this.dy = dy; + } + + /** + * Get the horizontal speed of this entity + * + * @return The horizontal speed of this entity (pixels/sec) + */ + public float getHorizontalMovement() { + return dx; + } + + /** + * Get the vertical speed of this entity + * + * @return The vertical speed of this entity (pixels/sec) + */ + public float getVerticalMovement() { + return dy; + } + + /** + * Draw this entity to the graphics context provided + */ + public void draw() { + sprite.draw((int) x, (int) y); + } + + /** + * Do the logic associated with this entity. This method + * will be called periodically based on game events + */ + public void doLogic() { + } + + /** + * Get the x location of this entity + * + * @return The x location of this entity + */ + public int getX() { + return (int) x; + } + + /** + * Get the y location of this entity + * + * @return The y location of this entity + */ + public int getY() { + return (int) y; + } + + /** + * 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 + */ + public boolean collidesWith(Entity other) { + me.setBounds((int) x, (int) y, sprite.getWidth(), sprite.getHeight()); + him.setBounds((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight()); + + return me.intersects(him); + } + + /** + * Notification that this entity collided with another. + * + * @param other The entity with which this entity collided. + */ + public abstract void collidedWith(Entity other); +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/Game.java b/src/main/java/org/lwjglx/test/spaceinvaders/Game.java new file mode 100644 index 0000000..ca0f528 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/Game.java @@ -0,0 +1,609 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +import java.util.ArrayList; + +import org.lwjglx.LWJGLException; +import org.lwjglx.Sys; +import org.lwjglx.input.Keyboard; +import org.lwjglx.input.Mouse; +import org.lwjglx.opengl.Display; +import org.lwjglx.opengl.DisplayMode; + +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. + * + * 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. + * + *

+ * NOTE:
+ * This game is a LWJGLized implementation of the Space Invaders game by Kevin + * 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, + * at the time of writing). + * You can find the original article here:
+ * http://www.cokeandcode.com + *

+ * + * @author Kevin Glass + * @author Brian Matzon + */ +public class Game { + + /** The normal title of the window */ + private String WINDOW_TITLE = "Space Invaders 104 (for LWJGL)"; + + /** The width of the game display area */ + private int width = 800; + + /** The height of the game display area */ + private int height = 600; + + /** The loader responsible for converting images into OpenGL textures */ + private TextureLoader textureLoader; + + /** The list of all the entities that exist in our game */ + private ArrayList entities = new ArrayList(); + + /** The list of entities that need to be removed from the game this loop */ + private ArrayList removeList = new ArrayList(); + + /** The entity representing the player */ + private ShipEntity ship; + + /** List of shots */ + private ShotEntity[] shots; + + /** The message to display which waiting for a key press */ + private Sprite message; + + /** The sprite containing the "Press Any Key" message */ + private Sprite pressAnyKey; + + /** The sprite containing the "You win!" message */ + private Sprite youWin; + + /** The sprite containing the "You lose!" message */ + private Sprite gotYou; + + /** Last shot index */ + private int shotIndex; + + /** The speed at which the player's ship should move (pixels/sec) */ + private float moveSpeed = 300; + + /** The time at which last fired a shot */ + private long lastFire; + + /** The interval between our players shot (ms) */ + private long firingInterval = 500; + + /** The number of aliens left on the screen */ + private int alienCount; + + /** True if we're holding up game play until a key has been pressed */ + 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; + + /** 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; + + /** The time since the last record of fps */ + private long lastFpsTime; + + /** The recorded fps */ + private int fps; + + private static long timerTicksPerSecond = Sys.getTimerResolution(); + + /** True if the game is currently "running", i.e. the game loop is looping */ + public static boolean gameRunning = true; + + /** SoundManager to make sound with */ + private SoundManager soundManager; + + /** Whether we're running in fullscreen mode */ + private boolean fullscreen; + + /** ID of shot effect */ + private int SOUND_SHOT; + + /** ID of hit effect */ + private int SOUND_HIT; + + /** ID of start sound */ + private int SOUND_START; + + /** ID of win sound */ + private int SOUND_WIN; + + /** ID of loose sound */ + private int SOUND_LOOSE; + + /** Mouse movement on x axis */ + private int mouseX; + + /** Is this an application or applet */ + private static boolean isApplication; + + /** + * Construct our game and set it running. + * @param fullscreen + * + */ + public Game(boolean fullscreen) { + this.fullscreen = fullscreen; + initialize(); + } + + /** + * Get the high resolution time in milliseconds + * + * @return The high resolution time in milliseconds + */ + public static long getTime() { + // we get the "timer ticks" from the high resolution timer + // multiply by 1000 so our end result is in milliseconds + // then divide by the number of ticks in a second giving + // us a nice clear time in milliseconds + return (Sys.getTime() * 1000) / timerTicksPerSecond; + } + + /** + * Sleep for a fixed number of milliseconds. + * + * @param duration The amount of time in milliseconds to sleep for + */ + public static void sleep(long duration) { + try { + Thread.sleep((duration * timerTicksPerSecond) / 1000); + } catch (InterruptedException inte) { + } + } + + /** + * Intialise the common elements for the game + */ + public void initialize() { + // initialize the window beforehand + try { + setDisplayMode(); + Display.setTitle(WINDOW_TITLE); + Display.setFullscreen(fullscreen); + Display.create(); + + // grab the mouse, dont want that hideous cursor when we're playing! + if (isApplication) { + Mouse.setGrabbed(true); + } + + // enable textures since we're going to use these for our sprites + glEnable(GL_TEXTURE_2D); + + // disable the OpenGL depth test since we're rendering 2D graphics + glDisable(GL_DEPTH_TEST); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + glOrtho(0, width, height, 0, -1, 1); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glViewport(0, 0, Display.getFramebufferWidth(), Display.getFramebufferHeight()); + + textureLoader = new TextureLoader(); + + // create our sound manager, and initialize it with 7 channels + // 1 channel for sounds, 6 for effects - this should be enough + // since we have a most 4 shots on screen at any one time, which leaves + // us with 2 channels for explosions. + soundManager = new SoundManager(); + soundManager.initialize(8); + + // load our sound data + SOUND_SHOT = soundManager.addSound("shot.wav"); + SOUND_HIT = soundManager.addSound("hit.wav"); + SOUND_START = soundManager.addSound("start.wav"); + SOUND_WIN = soundManager.addSound("win.wav"); + SOUND_LOOSE = soundManager.addSound("loose.wav"); + } catch (LWJGLException le) { + System.out.println("Game exiting - exception in initialization:"); + le.printStackTrace(); + Game.gameRunning = false; + return; + } + + // get our sprites + gotYou = getSprite("gotyou.gif"); + pressAnyKey = getSprite("pressanykey.gif"); + youWin = getSprite("youwin.gif"); + + message = pressAnyKey; + + // setup 5 shots + shots = new ShotEntity[5]; + for (int i = 0; i < shots.length; i++) { + shots[i] = new ShotEntity(this, "shot.gif", 0, 0); + } + + // setup the initial game state + startGame(); + } + + /** + * Sets the display mode for fullscreen mode + */ + private boolean setDisplayMode() { + try { + // get modes + DisplayMode[] dm = org.lwjglx.util.Display.getAvailableDisplayModes(width, height, -1, -1, -1, -1, 60, 60); + + org.lwjglx.util.Display.setDisplayMode(dm, new String[] { + "width=" + width, + "height=" + height, + "freq=" + 60, + "bpp=" + org.lwjglx.opengl.Display.getDisplayMode().getBitsPerPixel() + }); + return true; + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Unable to enter fullscreen, continuing in windowed mode"); + } + + return false; + } + + /** + * Start a fresh game, this should clear out any old data and + * create a new set. + */ + private void startGame() { + // clear out any existing entities and intialise a new set + entities.clear(); + initEntities(); + } + + /** + * Initialise the starting state of the entities (ship and aliens). Each + * entitiy will be added to the overall list of entities in the game. + */ + private void initEntities() { + // create the player ship and place it roughly in the center of the screen + ship = new ShipEntity(this, "ship.gif", 370, 550); + entities.add(ship); + + // create a block of aliens (5 rows, by 12 aliens, spaced evenly) + alienCount = 0; + for (int row = 0; row < 5; row++) { + for (int x = 0; x < 12; x++) { + Entity alien = new AlienEntity(this, 100 + (x * 50), (50) + row * 30); + entities.add(alien); + alienCount++; + } + } + } + + /** + * Notification from a game entity that the logic of the game + * should be run at the next opportunity (normally as a result of some + * game event) + */ + public void updateLogic() { + logicRequiredThisLoop = true; + } + + /** + * 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) { + removeList.add(entity); + } + + /** + * Notification that the player has died. + */ + public void notifyDeath() { + if (!waitingForKeyPress) { + soundManager.playSound(SOUND_LOOSE); + } + message = gotYou; + waitingForKeyPress = true; + } + + /** + * Notification that the player has won since all the aliens + * are dead. + */ + public void notifyWin() { + message = youWin; + waitingForKeyPress = true; + soundManager.playSound(SOUND_WIN); + } + + /** + * Notification that an alien has been killed + */ + public void notifyAlienKilled() { + // reduce the alient count, if there are none left, the player has won! + alienCount--; + + if (alienCount == 0) { + notifyWin(); + } + + // if there are still some aliens left then they all need to get faster, so + // speed up all the existing aliens + for ( Entity entity : entities ) { + if ( entity instanceof AlienEntity ) { + // speed up by 2% + entity.setHorizontalMovement(entity.getHorizontalMovement() * 1.02f); + } + } + + soundManager.playEffect(SOUND_HIT); + } + + /** + * Attempt to fire a shot from the player. Its called "try" + * 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() { + // check that we have waiting long enough to fire + if (System.currentTimeMillis() - lastFire < firingInterval) { + return; + } + + // if we waited long enough, create the shot entity, and record the time. + lastFire = System.currentTimeMillis(); + ShotEntity shot = shots[shotIndex++ % shots.length]; + shot.reinitialize(ship.getX() + 10, ship.getY() - 30); + entities.add(shot); + + soundManager.playEffect(SOUND_SHOT); + } + + /** + * Run the main game loop. This method keeps rendering the scene + * and requesting that the callback update its screen. + */ + private void gameLoop() { + while (Game.gameRunning) { + // clear screen + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + // let subsystem paint + frameRendering(); + + // update window contents + Display.update(); + } + + // clean up + soundManager.destroy(); + Display.destroy(); + } + + /** + * Notification that a frame is being rendered. Responsible for + * running game logic and rendering the scene. + */ + public void frameRendering() { + //SystemTimer.sleep(lastLoopTime+10-SystemTimer.getTime()); + Display.sync(60); + + // work out how long its been since the last update, this + // will be used to calculate how far the entities should + // move this loop + long delta = getTime() - lastLoopTime; + lastLoopTime = getTime(); + lastFpsTime += delta; + fps++; + + // update our FPS counter if a second has passed + if (lastFpsTime >= 1000) { + Display.setTitle(WINDOW_TITLE + " (FPS: " + fps + ")"); + lastFpsTime = 0; + fps = 0; + } + + // cycle round asking each entity to move itself + if (!waitingForKeyPress && !soundManager.isPlayingSound()) { + for ( Entity entity : entities ) { + entity.move(delta); + } + } + + // cycle round drawing all the entities we have in the game + for ( Entity entity : entities ) { + entity.draw(); + } + + // brute force collisions, compare every entity against + // 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 = entities.get(p); + Entity him = entities.get(s); + + if (me.collidesWith(him)) { + me.collidedWith(him); + him.collidedWith(me); + } + } + } + + // remove any entity that has been marked for clear up + entities.removeAll(removeList); + removeList.clear(); + + // if a game event has indicated that game logic should + // be resolved, cycle round every entity requesting that + // their personal logic should be considered. + if (logicRequiredThisLoop) { + for ( Entity entity : entities ) { + entity.doLogic(); + } + + logicRequiredThisLoop = false; + } + + // 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 + // isn't moving. If either cursor key is pressed then + // update the movement appropraitely + ship.setHorizontalMovement(0); + + // get mouse movement on x axis. We need to get it now, since + // we can only call getDX ONCE! - secondary calls will yield 0, since + // there haven't been any movement since last call. + mouseX = Mouse.getDX(); + + // we delegate input checking to submethod since we want to check + // for keyboard, mouse & controller + boolean leftPressed = hasInput(Keyboard.KEY_LEFT); + boolean rightPressed = hasInput(Keyboard.KEY_RIGHT); + boolean firePressed = hasInput(Keyboard.KEY_SPACE); + + if (!waitingForKeyPress && !soundManager.isPlayingSound()) { + if ((leftPressed) && (!rightPressed)) { + ship.setHorizontalMovement(-moveSpeed); + } else if ((rightPressed) && (!leftPressed)) { + ship.setHorizontalMovement(moveSpeed); + } + + // if we're pressing fire, attempt to fire + if (firePressed) { + tryToFire(); + } + } else { + if (!firePressed) { + fireHasBeenReleased = true; + } + if ((firePressed) && (fireHasBeenReleased) && !soundManager.isPlayingSound()) { + waitingForKeyPress = false; + fireHasBeenReleased = false; + startGame(); + soundManager.playSound(SOUND_START); + } + } + + // if escape has been pressed, stop the game + if ((Display.isCloseRequested() || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) && isApplication) { + Game.gameRunning = false; + } + } + + /** + * @param direction + * @return + */ + private boolean hasInput(int direction) { + switch(direction) { + case Keyboard.KEY_LEFT: + return + Keyboard.isKeyDown(Keyboard.KEY_LEFT) || + mouseX < 0; + + case Keyboard.KEY_RIGHT: + return + Keyboard.isKeyDown(Keyboard.KEY_RIGHT) || + mouseX > 0; + + case Keyboard.KEY_SPACE: + return + Keyboard.isKeyDown(Keyboard.KEY_SPACE) || + Mouse.isButtonDown(0); + } + return false; + } + + /** + * 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 && "-fullscreen".equalsIgnoreCase(argv[0]))).execute(); + System.exit(0); + } + + /** + * + */ + public void execute() { + gameLoop(); + } + + /** + * 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. + */ + public Sprite getSprite(String ref) { + return new Sprite(textureLoader, ref); + } +} diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/ShipEntity.java b/src/main/java/org/lwjglx/test/spaceinvaders/ShipEntity.java new file mode 100644 index 0000000..d773e81 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/ShipEntity.java @@ -0,0 +1,98 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +/** + * The entity that represents the players ship + * + * @author Kevin Glass + * @author Brian Matzon + */ +public class ShipEntity extends Entity { + + /** Right border at which to disallow further movement */ + private static final int RIGHT_BORDER = 750; + + /** Left border at which to disallow further movement */ + private static final int LEFT_BORDER = 10; + + /** The game in which the ship exists */ + private Game game; + + /** + * Create a new entity to represent the players ship + * + * @param game The game in which the ship is being created + * @param ref The reference to the sprite to show for the ship + * @param x The initial x location of the player's ship + * @param y The initial y location of the player's ship + */ + public ShipEntity(Game game,String ref,int x,int y) { + super(game.getSprite(ref), x, y); + + this.game = game; + } + + /** + * Request that the ship move itself based on an elapsed ammount of + * time + * + * @param delta The time that has elapsed since last move (ms) + */ + public void move(long delta) { + // if we're moving left and have reached the left hand side + // of the screen, don't move + if ((dx < 0) && (x < LEFT_BORDER)) { + return; + } + // if we're moving right and have reached the right hand side + // of the screen, don't move + if ((dx > 0) && (x > RIGHT_BORDER)) { + return; + } + + super.move(delta); + } + + /** + * Notification that the player's ship has collided with something + * + * @param other The entity with which the ship has collided + */ + public void collidedWith(Entity other) { + // if its an alien, notify the game that the player + // is dead + if (other instanceof AlienEntity) { + game.notifyDeath(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/ShotEntity.java b/src/main/java/org/lwjglx/test/spaceinvaders/ShotEntity.java new file mode 100644 index 0000000..4c1f4e5 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/ShotEntity.java @@ -0,0 +1,120 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +/** + * An entity representing a shot fired by the player's ship + * + * @author Kevin Glass + * @author Brian Matzon + */ +public class ShotEntity extends Entity { + + /** Top border at which shots are outside */ + private static final int TOP_BORDER = -100; + + /** The vertical speed at which the players shot moves */ + private float moveSpeed = -300; + + /** The game in which this entity exists */ + private Game game; + + /** True if this shot has been "used", i.e. its hit something */ + 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 + * @param y The initial y location of the shot + */ + public ShotEntity(Game game, String sprite, int x, int y) { + super(game.getSprite(sprite), x, y); + + this.game = game; + dy = moveSpeed; + } + + /** + * Reinitializes this entity, for reuse + * + * @param x new x coordinate + * @param y new y coordinate + */ + public void reinitialize(int x, int y) { + this.x = x; + this.y = y; + used = false; + } + + /** + * Request that this shot moved based on time elapsed + * + * @param delta The time that has elapsed since last move + */ + public void move(long delta) { + // proceed with normal move + super.move(delta); + + // if we shot off the screen, remove ourselfs + if (y < TOP_BORDER) { + game.removeEntity(this); + } + } + + /** + * Notification that this shot has collided with another + * entity + * + * @param other The other entity with which we've collided + */ + public void collidedWith(Entity other) { + // prevents double kills, if we've already hit something, + // don't collide + if (used) { + return; + } + + // if we've hit an alien, kill it! + if (other instanceof AlienEntity) { + // remove the affected entities + game.removeEntity(this); + game.removeEntity(other); + + // notify the game that the alien has been killed + game.notifyAlienKilled(); + used = true; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/SoundManager.java b/src/main/java/org/lwjglx/test/spaceinvaders/SoundManager.java new file mode 100644 index 0000000..eca0c9b --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/SoundManager.java @@ -0,0 +1,189 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; +import org.lwjglx.LWJGLException; +import org.lwjglx.openal.AL; +import org.lwjglx.openal.AL10; +import org.lwjglx.util.WaveData; + + +/** + *

+ * Simple sound manager for OpenAL using n sources accessed in + * a round robin schedule. Source n is reserved for a single buffer and checking for + * whether it's playing. + *

+ * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +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 + */ + public SoundManager() { + } + + /** + * Plays a sound effect + * @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); + } + } + + /** + * Plays a sound on last source + * @param buffer Buffer index to play gotten from addSound + */ + public void playSound(int buffer) { + if(soundOutput) { + AL10.alSourcei(sources[sources.length-1], AL10.AL_BUFFER, buffers[buffer]); + 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 + */ + public boolean isPlayingSound() { + return AL10.alGetSourcei(sources[sources.length-1], AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING; + } + + /** + * Initializes the SoundManager + * + * @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) { + le.printStackTrace(); + 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 + */ + public int addSound(String path) { + // Generate 1 buffer entry + 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(); + + // 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(); + AL10.alSourceStop(scratchBuffer); + + // 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(); + } + } +} diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/Sprite.java b/src/main/java/org/lwjglx/test/spaceinvaders/Sprite.java new file mode 100644 index 0000000..6bd0089 --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/Sprite.java @@ -0,0 +1,127 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +import java.io.IOException; + +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 + */ +public class Sprite { + + /** The texture that stores the image for this sprite */ + private Texture texture; + + /** The width in pixels of this sprite */ + private int width; + + /** The height in pixels of this sprite */ + private int height; + + /** + * Create a new sprite from a specified image. + * + * @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) { + try { + texture = loader.getTexture("spaceinvaders/" + ref); + width = texture.getImageWidth(); + height = texture.getImageHeight(); + } catch (IOException ioe) { + ioe.printStackTrace(); + System.exit(-1); + } + } + + /** + * Get the width of this sprite in pixels + * + * @return The width of this sprite in pixels + */ + public int getWidth() { + return texture.getImageWidth(); + } + + /** + * Get the height of this sprite in pixels + * + * @return The height of this sprite in pixels + */ + public int getHeight() { + return texture.getImageHeight(); + } + + /** + * 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 + glPushMatrix(); + + // bind to the appropriate texture for this sprite + texture.bind(); + + // translate to the right location and prepare to draw + glTranslatef(x, y, 0); + + // draw a quad textured to match the sprite + glBegin(GL_QUADS); + { + glTexCoord2f(0, 0); + glVertex2f(0, 0); + + glTexCoord2f(0, texture.getHeight()); + glVertex2f(0, height); + + glTexCoord2f(texture.getWidth(), texture.getHeight()); + glVertex2f(width, height); + + glTexCoord2f(texture.getWidth(), 0); + glVertex2f(width, 0); + } + glEnd(); + + // restore the model view matrix to prevent contamination + glPopMatrix(); + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/Texture.java b/src/main/java/org/lwjglx/test/spaceinvaders/Texture.java new file mode 100644 index 0000000..d272fcc --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/Texture.java @@ -0,0 +1,188 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +import static org.lwjgl.opengl.GL11.*; + +/** + * 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 + * sprite against the texture. + * + * @author Kevin Glass + * @author Brian Matzon + */ +public class Texture { + + /** The GL target type */ + private int target; + + /** The GL texture ID */ + private int textureID; + + /** The height of the image */ + private int height; + + /** The width of the image */ + private int width; + + /** The width of the texture */ + private int texWidth; + + /** The height of the texture */ + private int texHeight; + + /** The ratio of the width of the image to the texture */ + private float widthRatio; + + /** The ratio of the height of the image to the texture */ + private float heightRatio; + + /** + * Create a new texture + * + * @param target The GL target + * @param textureID The GL texture ID + */ + public Texture(int target, int textureID) { + this.target = target; + this.textureID = textureID; + } + + /** + * Bind the specified GL context to a texture + */ + public void bind() { + glBindTexture(target, textureID); + } + + /** + * Set the height of the image + * + * @param height The height of the image + */ + public void setHeight(int height) { + this.height = height; + setHeight(); + } + + /** + * Set the width of the image + * + * @param width The width of the image + */ + public void setWidth(int width) { + this.width = width; + setWidth(); + } + + /** + * Get the height of the original image + * + * @return The height of the original image + */ + public int getImageHeight() { + return height; + } + + /** + * Get the width of the original image + * + * @return The width of the original image + */ + public int getImageWidth() { + return width; + } + + /** + * Get the height of the physical texture + * + * @return The height of physical texture + */ + public float getHeight() { + return heightRatio; + } + + /** + * Get the width of the physical texture + * + * @return The width of physical texture + */ + public float getWidth() { + return widthRatio; + } + + /** + * Set the height of this texture + * + * @param texHeight The height of the texture + */ + public void setTextureHeight(int texHeight) { + this.texHeight = texHeight; + setHeight(); + } + + /** + * Set the width of this texture + * + * @param texWidth The width of the texture + */ + public void setTextureWidth(int texWidth) { + this.texWidth = texWidth; + setWidth(); + } + + /** + * Set the height of the texture. This will update the + * ratio also. + */ + private void setHeight() { + if (texHeight != 0) { + heightRatio = ((float) height) / texHeight; + } + } + + /** + * Set the width of the texture. This will update the + * ratio also. + */ + private void setWidth() { + if (texWidth != 0) { + widthRatio = ((float) width) / texWidth; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/test/spaceinvaders/TextureLoader.java b/src/main/java/org/lwjglx/test/spaceinvaders/TextureLoader.java new file mode 100644 index 0000000..6012f9b --- /dev/null +++ b/src/main/java/org/lwjglx/test/spaceinvaders/TextureLoader.java @@ -0,0 +1,291 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.test.spaceinvaders; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.color.ColorSpace; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.ComponentColorModel; +import java.awt.image.DataBuffer; +import java.awt.image.DataBufferByte; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.util.HashMap; +import java.util.Hashtable; + +import javax.swing.ImageIcon; + +import org.lwjgl.BufferUtils; + +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 + * 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. + * + * @author Kevin Glass + * @author Brian Matzon + */ +public class TextureLoader { + /** The table of textures that have been loaded in this loader */ + private HashMap table = new HashMap(); + + /** 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); + + /** + * Create a new texture loader based on the game panel + */ + public TextureLoader() { + glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), + new int[] {8,8,8,8}, + true, + false, + ComponentColorModel.TRANSLUCENT, + DataBuffer.TYPE_BYTE); + + glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), + new int[] {8,8,8,0}, + false, + false, + ComponentColorModel.OPAQUE, + DataBuffer.TYPE_BYTE); + } + + /** + * Create a new texture ID + * + * @return A new texture ID + */ + private int createTextureID() { + glGenTextures(textureIDBuffer); + return textureIDBuffer.get(0); + } + + /** + * Load a texture + * + * @param resourceName The location of the resource to load + * @return The loaded texture + * @throws IOException Indicates a failure to access the resource + */ + public Texture getTexture(String resourceName) throws IOException { + Texture tex = table.get(resourceName); + + if (tex != null) { + return tex; + } + + tex = getTexture(resourceName, + 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. + * + * @param resourceName The location of the resource to load + * @param target The GL target to load the texture against + * @param dstPixelFormat The pixel format of the screen + * @param minFilter The minimising filter + * @param magFilter The magnification filter + * @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; + + // 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 = GL_RGBA; + } else { + 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); + } + + // produce a texture from the byte buffer + 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 static int get2Fold(int fold) { + int ret = 2; + while (ret < fold) { + ret *= 2; + } + return ret; + } + + /** + * Convert the buffered image to a texture + * + * @param bufferedImage The image to convert to a texture + * @param texture The texture to store the data into + * @return A buffer containing the data + */ + 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()) { + texWidth *= 2; + } + 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()) { + raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,4,null); + texImage = new BufferedImage(glAlphaColorModel,raster,false,new Hashtable()); + } else { + 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); + imageBuffer.flip(); + + 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 { + URL url = TextureLoader.class.getClassLoader().getResource(ref); + + if (url == null) { + throw new IOException("Cannot find: " + ref); + } + + // due to an issue with ImageIO and mixed signed code + // we are now using good oldfashioned ImageIcon to load + // images and the paint it on top of a new BufferedImage + Image img = new ImageIcon(url).getImage(); + BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); + Graphics g = bufferedImage.getGraphics(); + g.drawImage(img, 0, 0, null); + g.dispose(); + + return bufferedImage; + } +} diff --git a/src/main/java/org/lwjglx/util/Display.java b/src/main/java/org/lwjglx/util/Display.java new file mode 100644 index 0000000..cc09839 --- /dev/null +++ b/src/main/java/org/lwjglx/util/Display.java @@ -0,0 +1,243 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; + +import org.lwjglx.LWJGLException; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.opengl.DisplayMode; + +/** + * Display initialization utility, that can be used to find display modes and pick + * one for you based on your criteria. + * @author $Author: spasi $ + * @version $Revision: 3418 $ + * $Id: Display.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public final class Display { + + private static final boolean DEBUG = false; + + /** + * Determine the available display modes that match the specified minimum and maximum criteria. + * If any given criterium is specified as -1 then it is ignored. + * + * @param minWidth the minimum display resolution in pixels + * @param minHeight the minimum display resolution in pixels + * @param maxWidth the maximum display resolution in pixels + * @param maxHeight the maximum display resolution in pixels + * @param minBPP the minimum bit depth per pixel + * @param maxBPP the maximum bit depth per pixel + * @param minFreq the minimum display frequency in Hz + * @param maxFreq the maximum display frequency in Hz + * @return an array of matching display modes + */ + public static DisplayMode[] getAvailableDisplayModes(int minWidth, int minHeight, int maxWidth, int maxHeight, int minBPP, int maxBPP, + int minFreq, int maxFreq) throws LWJGLException + { + // First get the available display modes + DisplayMode[] modes = org.lwjglx.opengl.Display.getAvailableDisplayModes(); + + if (LWJGLUtil.DEBUG || DEBUG) { + System.out.println("Available screen modes:"); + for ( DisplayMode mode : modes ) { + System.out.println(mode); + } + } + + ArrayList matches = new ArrayList(modes.length); + + for (int i = 0; i < modes.length; i ++) { + assert modes[i] != null : ""+i+" "+modes.length; + if (minWidth != -1 && modes[i].getWidth() < minWidth) + continue; + if (maxWidth != -1 && modes[i].getWidth() > maxWidth) + continue; + if (minHeight != -1 && modes[i].getHeight() < minHeight) + continue; + if (maxHeight != -1 && modes[i].getHeight() > maxHeight) + continue; + if (minBPP != -1 && modes[i].getBitsPerPixel() < minBPP) + continue; + if (maxBPP != -1 && modes[i].getBitsPerPixel() > maxBPP) + continue; + //if (modes[i].bpp == 24) + // continue; + if (modes[i].getFrequency() != 0) { + if (minFreq != -1 && modes[i].getFrequency() < minFreq) + continue; + if (maxFreq != -1 && modes[i].getFrequency() > maxFreq) + continue; + } + matches.add(modes[i]); + } + + DisplayMode[] ret = new DisplayMode[matches.size()]; + matches.toArray(ret); + if (LWJGLUtil.DEBUG && DEBUG) { + System.out.println("Filtered screen modes:"); + for ( DisplayMode mode : ret ) { + System.out.println(mode); + } + } + + return ret; + } + + /** + * Create the display by choosing from a list of display modes based on an order of preference. + * You must supply a list of allowable display modes, probably by calling getAvailableDisplayModes(), + * and an array with the order in which you would like them sorted in descending order. + * This method attempts to create the topmost display mode; if that fails, it will try the next one, + * and so on, until there are no modes left. If no mode is set at the end, an exception is thrown. + * @param dm a list of display modes to choose from + * @param param the names of the DisplayMode fields in the order in which you would like them sorted. + * @return the chosen display mode + * @throws NoSuchFieldException if one of the params is not a field in DisplayMode + * @throws Exception if no display mode could be set + * @see org.lwjgl.opengl.DisplayMode + */ + public static DisplayMode setDisplayMode(DisplayMode[] dm, final String[] param) throws Exception { + + class FieldAccessor { + final String fieldName; + final int order; + final int preferred; + final boolean usePreferred; + FieldAccessor(String fieldName, int order, int preferred, boolean usePreferred) { + this.fieldName = fieldName; + this.order = order; + this.preferred = preferred; + this.usePreferred = usePreferred; + } + int getInt(DisplayMode mode) { + if ("width".equals(fieldName)) { + return mode.getWidth(); + } + if ("height".equals(fieldName)) { + return mode.getHeight(); + } + if ("freq".equals(fieldName)) { + return mode.getFrequency(); + } + if ("bpp".equals(fieldName)) { + return mode.getBitsPerPixel(); + } + throw new IllegalArgumentException("Unknown field "+fieldName); + } + } + + class Sorter implements Comparator { + + final FieldAccessor[] accessors; + + Sorter() { + accessors = new FieldAccessor[param.length]; + for (int i = 0; i < accessors.length; i ++) { + int idx = param[i].indexOf('='); + if (idx > 0) { + accessors[i] = new FieldAccessor(param[i].substring(0, idx), 0, Integer.parseInt(param[i].substring(idx + 1, param[i].length())), true); + } else if (param[i].charAt(0) == '-') { + accessors[i] = new FieldAccessor(param[i].substring(1), -1, 0, false); + } else { + accessors[i] = new FieldAccessor(param[i], 1, 0, false); + } + } + } + + /** + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + public int compare(DisplayMode dm1, DisplayMode dm2) { + for ( FieldAccessor accessor : accessors ) { + int f1 = accessor.getInt(dm1); + int f2 = accessor.getInt(dm2); + + if ( accessor.usePreferred && f1 != f2 ) { + if ( f1 == accessor.preferred ) + return -1; + else if ( f2 == accessor.preferred ) + return 1; + else { + // Score according to the difference between the values + int absf1 = Math.abs(f1 - accessor.preferred); + int absf2 = Math.abs(f2 - accessor.preferred); + if ( absf1 < absf2 ) + return -1; + else if ( absf1 > absf2 ) + return 1; + else + continue; + } + } else if ( f1 < f2 ) + return accessor.order; + else if ( f1 == f2 ) + continue; + else + return -accessor.order; + } + + return 0; + } + } + + // Sort the display modes + Arrays.sort(dm, new Sorter()); + + // Try them out in the appropriate order + if (LWJGLUtil.DEBUG || DEBUG) { + System.out.println("Sorted display modes:"); + for ( DisplayMode aDm : dm ) { + System.out.println(aDm); + } + } + for ( DisplayMode aDm : dm ) { + try { + if ( LWJGLUtil.DEBUG || DEBUG ) + System.out.println("Attempting to set displaymode: " + aDm); + org.lwjglx.opengl.Display.setDisplayMode(aDm); + return aDm; + } catch (Exception e) { + if ( LWJGLUtil.DEBUG || DEBUG ) { + System.out.println("Failed to set display mode to " + aDm); + e.printStackTrace(); + } + } + } + + throw new Exception("Failed to set display mode."); + } + +} diff --git a/src/main/java/org/lwjglx/util/WaveData.java b/src/main/java/org/lwjglx/util/WaveData.java new file mode 100644 index 0000000..5c1e4a6 --- /dev/null +++ b/src/main/java/org/lwjglx/util/WaveData.java @@ -0,0 +1,258 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ShortBuffer; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; + +import org.lwjgl.openal.AL10; + +//import com.sun.media.sound.WaveFileReader; + +/** + * + * Utitlity class for loading wavefiles. + * + * @author Brian Matzon + * @version $Revision$ + * $Id$ + */ +public class WaveData { + /** actual wave data */ + public final ByteBuffer data; + + /** format type of data */ + public final int format; + + /** sample rate of data */ + public final int samplerate; + + /** + * Creates a new WaveData + * + * @param data actual wavedata + * @param format format of wave data + * @param samplerate sample rate of data + */ + private WaveData(ByteBuffer data, int format, int samplerate) { + this.data = data; + this.format = format; + this.samplerate = samplerate; + } + + /** + * Disposes the wavedata + */ + public void dispose() { + data.clear(); + } + + /** + * Creates a WaveData container from the specified url + * + * @param path URL to file + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(URL path) { + try { + // due to an issue with AudioSystem.getAudioInputStream + // and mixing unsigned and signed code + // we will use the reader directly + return create(AudioSystem.getAudioInputStream(path)); + //WaveFileReader wfr = new WaveFileReader(); + //return create(wfr.getAudioInputStream(new BufferedInputStream(path.openStream()))); + } catch (Exception e) { + org.lwjgl.LWJGLUtil.log("Unable to create from: " + path + ", " + e.getMessage()); + return null; + } + } + + /** + * Creates a WaveData container from the specified in the classpath + * + * @param path path to file (relative, and in classpath) + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(String path) { + return create(Thread.currentThread().getContextClassLoader().getResource(path)); + } + + /** + * Creates a WaveData container from the specified inputstream + * + * @param is InputStream to read from + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(InputStream is) { + try { + return create( + AudioSystem.getAudioInputStream(is)); + } catch (Exception e) { + org.lwjgl.LWJGLUtil.log("Unable to create from inputstream, " + e.getMessage()); + return null; + } + } + + /** + * Creates a WaveData container from the specified bytes + * + * @param buffer array of bytes containing the complete wave file + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(byte[] buffer) { + try { + return create( + AudioSystem.getAudioInputStream( + new BufferedInputStream(new ByteArrayInputStream(buffer)))); + } catch (Exception e) { + org.lwjgl.LWJGLUtil.log("Unable to create from byte array, " + e.getMessage()); + return null; + } + } + + /** + * Creates a WaveData container from the specified ByetBuffer. + * If the buffer is backed by an array, it will be used directly, + * else the contents of the buffer will be copied using get(byte[]). + * + * @param buffer ByteBuffer containing sound file + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(ByteBuffer buffer) { + try { + byte[] bytes = null; + + if(buffer.hasArray()) { + bytes = buffer.array(); + } else { + bytes = new byte[buffer.capacity()]; + buffer.get(bytes); + } + return create(bytes); + } catch (Exception e) { + org.lwjgl.LWJGLUtil.log("Unable to create from ByteBuffer, " + e.getMessage()); + return null; + } + } + + /** + * Creates a WaveData container from the specified stream + * + * @param ais AudioInputStream to read from + * @return WaveData containing data, or null if a failure occured + */ + public static WaveData create(AudioInputStream ais) { + //get format of data + AudioFormat audioformat = ais.getFormat(); + + // get channels + int channels = 0; + if (audioformat.getChannels() == 1) { + if (audioformat.getSampleSizeInBits() == 8) { + channels = AL10.AL_FORMAT_MONO8; + } else if (audioformat.getSampleSizeInBits() == 16) { + channels = AL10.AL_FORMAT_MONO16; + } else { + assert false : "Illegal sample size"; + } + } else if (audioformat.getChannels() == 2) { + if (audioformat.getSampleSizeInBits() == 8) { + channels = AL10.AL_FORMAT_STEREO8; + } else if (audioformat.getSampleSizeInBits() == 16) { + channels = AL10.AL_FORMAT_STEREO16; + } else { + assert false : "Illegal sample size"; + } + } else { + assert false : "Only mono or stereo is supported"; + } + + //read data into buffer + ByteBuffer buffer = null; + try { + int available = ais.available(); + if(available <= 0) { + available = ais.getFormat().getChannels() * (int) ais.getFrameLength() * ais.getFormat().getSampleSizeInBits() / 8; + } + byte[] buf = new byte[ais.available()]; + int read = 0, total = 0; + while ((read = ais.read(buf, total, buf.length - total)) != -1 + && total < buf.length) { + total += read; + } + buffer = convertAudioBytes(buf, audioformat.getSampleSizeInBits() == 16, audioformat.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); + } catch (IOException ioe) { + return null; + } + + + //create our result + WaveData wavedata = + new WaveData(buffer, channels, (int) audioformat.getSampleRate()); + + //close stream + try { + ais.close(); + } catch (IOException ioe) { + } + + return wavedata; + } + + private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data, ByteOrder order) { + ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length); + dest.order(ByteOrder.nativeOrder()); + ByteBuffer src = ByteBuffer.wrap(audio_bytes); + src.order(order); + if (two_bytes_data) { + ShortBuffer dest_short = dest.asShortBuffer(); + ShortBuffer src_short = src.asShortBuffer(); + while (src_short.hasRemaining()) + dest_short.put(src_short.get()); + } else { + while (src.hasRemaining()) + dest.put(src.get()); + } + dest.rewind(); + return dest; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/Cylinder.java b/src/main/java/org/lwjglx/util/glu/Cylinder.java new file mode 100644 index 0000000..5499d9f --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Cylinder.java @@ -0,0 +1,201 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * Cylinder.java + * + * + * Created 23-dec-2003 + * @author Erik Duijs + */ +public class Cylinder extends Quadric { + + /** + * Constructor for Cylinder. + */ + public Cylinder() { + super(); + } + + /** + * draws a cylinder oriented along the z axis. The base of the + * cylinder is placed at z = 0, and the top at z=height. Like a sphere, a + * cylinder is subdivided around the z axis into slices, and along the z axis + * into stacks. + * + * Note that if topRadius is set to zero, then this routine will generate a + * cone. + * + * If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then + * any generated normals point away from the z axis. Otherwise, they point + * toward the z axis. + * + * If texturing is turned on (with glu.quadricTexture), then texture + * coordinates are generated so that t ranges linearly from 0.0 at z = 0 to + * 1.0 at z = height, and s ranges from 0.0 at the +y axis, to 0.25 at the +x + * axis, to 0.5 at the -y axis, to 0.75 at the -x axis, and back to 1.0 at the + * +y axis. + * + * @param baseRadius Specifies the radius of the cylinder at z = 0. + * @param topRadius Specifies the radius of the cylinder at z = height. + * @param height Specifies the height of the cylinder. + * @param slices Specifies the number of subdivisions around the z axis. + * @param stacks Specifies the number of subdivisions along the z axis. + */ + public void draw(float baseRadius, float topRadius, float height, int slices, int stacks) { + + float da, r, dr, dz; + float x, y, z, nz, nsign; + int i, j; + + if (super.orientation == GLU_INSIDE) { + nsign = -1.0f; + } else { + nsign = 1.0f; + } + + da = 2.0f * PI / slices; + dr = (topRadius - baseRadius) / stacks; + dz = height / stacks; + nz = (baseRadius - topRadius) / height; + // Z component of normal vectors + + if (super.drawStyle == GLU_POINT) { + glBegin(GL_POINTS); + for (i = 0; i < slices; i++) { + x = cos((i * da)); + y = sin((i * da)); + normal3f(x * nsign, y * nsign, nz * nsign); + + z = 0.0f; + r = baseRadius; + for (j = 0; j <= stacks; j++) { + glVertex3f((x * r), (y * r), z); + z += dz; + r += dr; + } + } + glEnd(); + } else if (super.drawStyle == GLU_LINE || super.drawStyle == GLU_SILHOUETTE) { + // Draw rings + if (super.drawStyle == GLU_LINE) { + z = 0.0f; + r = baseRadius; + for (j = 0; j <= stacks; j++) { + glBegin(GL_LINE_LOOP); + for (i = 0; i < slices; i++) { + x = cos((i * da)); + y = sin((i * da)); + normal3f(x * nsign, y * nsign, nz * nsign); + glVertex3f((x * r), (y * r), z); + } + glEnd(); + z += dz; + r += dr; + } + } else { + // draw one ring at each end + if (baseRadius != 0.0) { + glBegin(GL_LINE_LOOP); + for (i = 0; i < slices; i++) { + x = cos((i * da)); + y = sin((i * da)); + normal3f(x * nsign, y * nsign, nz * nsign); + glVertex3f((x * baseRadius), (y * baseRadius), 0.0f); + } + glEnd(); + glBegin(GL_LINE_LOOP); + for (i = 0; i < slices; i++) { + x = cos((i * da)); + y = sin((i * da)); + normal3f(x * nsign, y * nsign, nz * nsign); + glVertex3f((x * topRadius), (y * topRadius), height); + } + glEnd(); + } + } + // draw length lines + glBegin(GL_LINES); + for (i = 0; i < slices; i++) { + x = cos((i * da)); + y = sin((i * da)); + normal3f(x * nsign, y * nsign, nz * nsign); + glVertex3f((x * baseRadius), (y * baseRadius), 0.0f); + glVertex3f((x * topRadius), (y * topRadius), (height)); + } + glEnd(); + } else if (super.drawStyle == GLU_FILL) { + float ds = 1.0f / slices; + float dt = 1.0f / stacks; + float t = 0.0f; + z = 0.0f; + r = baseRadius; + for (j = 0; j < stacks; j++) { + float s = 0.0f; + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= slices; i++) { + if (i == slices) { + x = sin(0.0f); + y = cos(0.0f); + } else { + x = sin((i * da)); + y = cos((i * da)); + } + if (nsign == 1.0f) { + normal3f((x * nsign), (y * nsign), (nz * nsign)); + TXTR_COORD(s, t); + glVertex3f((x * r), (y * r), z); + normal3f((x * nsign), (y * nsign), (nz * nsign)); + TXTR_COORD(s, t + dt); + glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz)); + } else { + normal3f(x * nsign, y * nsign, nz * nsign); + TXTR_COORD(s, t); + glVertex3f((x * r), (y * r), z); + normal3f(x * nsign, y * nsign, nz * nsign); + TXTR_COORD(s, t + dt); + glVertex3f((x * (r + dr)), (y * (r + dr)), (z + dz)); + } + s += ds; + } // for slices + glEnd(); + r += dr; + t += dt; + z += dz; + } // for stacks + } + } +} diff --git a/src/main/java/org/lwjglx/util/glu/Disk.java b/src/main/java/org/lwjglx/util/glu/Disk.java new file mode 100644 index 0000000..4478cd0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Disk.java @@ -0,0 +1,214 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * Disk.java + * + * + * Created 23-dec-2003 + * @author Erik Duijs + */ +public class Disk extends Quadric { + + /** + * Constructor for Disk. + */ + public Disk() { + super(); + } + + /** + * renders a disk on the z = 0 plane. The disk has a radius of + * outerRadius, and contains a concentric circular hole with a radius of + * innerRadius. If innerRadius is 0, then no hole is generated. The disk is + * subdivided around the z axis into slices (like pizza slices), and also + * about the z axis into rings (as specified by slices and loops, + * respectively). + * + * With respect to orientation, the +z side of the disk is considered to be + * "outside" (see glu.quadricOrientation). This means that if the orientation + * is set to GLU.OUTSIDE, then any normals generated point along the +z axis. + * Otherwise, they point along the -z axis. + * + * If texturing is turned on (with glu.quadricTexture), texture coordinates are + * generated linearly such that where r=outerRadius, the value at (r, 0, 0) is + * (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5), and at + * (0, -r, 0) it is (0.5, 0). + */ + public void draw(float innerRadius, float outerRadius, int slices, int loops) + { + float da, dr; + + /* Normal vectors */ + if (super.normals != GLU_NONE) { + if (super.orientation == GLU_OUTSIDE) { + glNormal3f(0.0f, 0.0f, +1.0f); + } + else { + glNormal3f(0.0f, 0.0f, -1.0f); + } + } + + da = 2.0f * PI / slices; + dr = (outerRadius - innerRadius) / loops; + + switch (super.drawStyle) { + case GLU_FILL: + { + /* texture of a gluDisk is a cut out of the texture unit square + * x, y in [-outerRadius, +outerRadius]; s, t in [0, 1] + * (linear mapping) + */ + float dtc = 2.0f * outerRadius; + float sa, ca; + float r1 = innerRadius; + int l; + for (l = 0; l < loops; l++) { + float r2 = r1 + dr; + if (super.orientation == GLU_OUTSIDE) { + int s; + glBegin(GL_QUAD_STRIP); + for (s = 0; s <= slices; s++) { + float a; + if (s == slices) + a = 0.0f; + else + a = s * da; + sa = sin(a); + ca = cos(a); + TXTR_COORD(0.5f + sa * r2 / dtc, 0.5f + ca * r2 / dtc); + glVertex2f(r2 * sa, r2 * ca); + TXTR_COORD(0.5f + sa * r1 / dtc, 0.5f + ca * r1 / dtc); + glVertex2f(r1 * sa, r1 * ca); + } + glEnd(); + } + else { + int s; + glBegin(GL_QUAD_STRIP); + for (s = slices; s >= 0; s--) { + float a; + if (s == slices) + a = 0.0f; + else + a = s * da; + sa = sin(a); + ca = cos(a); + TXTR_COORD(0.5f - sa * r2 / dtc, 0.5f + ca * r2 / dtc); + glVertex2f(r2 * sa, r2 * ca); + TXTR_COORD(0.5f - sa * r1 / dtc, 0.5f + ca * r1 / dtc); + glVertex2f(r1 * sa, r1 * ca); + } + glEnd(); + } + r1 = r2; + } + break; + } + case GLU_LINE: + { + int l, s; + /* draw loops */ + for (l = 0; l <= loops; l++) { + float r = innerRadius + l * dr; + glBegin(GL_LINE_LOOP); + for (s = 0; s < slices; s++) { + float a = s * da; + glVertex2f(r * sin(a), r * cos(a)); + } + glEnd(); + } + /* draw spokes */ + for (s = 0; s < slices; s++) { + float a = s * da; + float x = sin(a); + float y = cos(a); + glBegin(GL_LINE_STRIP); + for (l = 0; l <= loops; l++) { + float r = innerRadius + l * dr; + glVertex2f(r * x, r * y); + } + glEnd(); + } + break; + } + case GLU_POINT: + { + int s; + glBegin(GL_POINTS); + for (s = 0; s < slices; s++) { + float a = s * da; + float x = sin(a); + float y = cos(a); + int l; + for (l = 0; l <= loops; l++) { + float r = innerRadius * l * dr; + glVertex2f(r * x, r * y); + } + } + glEnd(); + break; + } + case GLU_SILHOUETTE: + { + if (innerRadius != 0.0) { + float a; + glBegin(GL_LINE_LOOP); + for (a = 0.0f; a < 2.0 * PI; a += da) { + float x = innerRadius * sin(a); + float y = innerRadius * cos(a); + glVertex2f(x, y); + } + glEnd(); + } + { + float a; + glBegin(GL_LINE_LOOP); + for (a = 0; a < 2.0f * PI; a += da) { + float x = outerRadius * sin(a); + float y = outerRadius * cos(a); + glVertex2f(x, y); + } + glEnd(); + } + break; + } + default: + return; + } + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/GLU.java b/src/main/java/org/lwjglx/util/glu/GLU.java new file mode 100644 index 0000000..360c21f --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/GLU.java @@ -0,0 +1,430 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +import org.lwjglx.util.glu.tessellation.GLUtessellatorImpl; +import org.lwjglx.opengl.Util; + +import static org.lwjgl.opengl.GL11.*; + +/** + * GLU.java + * + * + * Created 23-dec-2003 + * @author Erik Duijs + */ +public class GLU { + static final float PI = (float)Math.PI; + + /* Errors: (return value 0 = no error) */ + public static final int GLU_INVALID_ENUM = 100900; + public static final int GLU_INVALID_VALUE = 100901; + public static final int GLU_OUT_OF_MEMORY = 100902; + public static final int GLU_INCOMPATIBLE_GL_VERSION = 100903; + + /* StringName */ + public static final int GLU_VERSION = 100800; + public static final int GLU_EXTENSIONS = 100801; + + /* Boolean */ + public static final boolean GLU_TRUE = true; + public static final boolean GLU_FALSE = false; + + + /**** Quadric constants ****/ + + /* QuadricNormal */ + public static final int GLU_SMOOTH = 100000; + public static final int GLU_FLAT = 100001; + public static final int GLU_NONE = 100002; + + /* QuadricDrawStyle */ + public static final int GLU_POINT = 100010; + public static final int GLU_LINE = 100011; + public static final int GLU_FILL = 100012; + public static final int GLU_SILHOUETTE = 100013; + + /* QuadricOrientation */ + public static final int GLU_OUTSIDE = 100020; + public static final int GLU_INSIDE = 100021; + + /* Callback types: */ + /* ERROR = 100103 */ + + + /**** Tesselation constants ****/ + + public static final double GLU_TESS_MAX_COORD = 1.0e150; + public static final double TESS_MAX_COORD = 1.0e150; + + /* TessProperty */ + public static final int GLU_TESS_WINDING_RULE = 100140; + public static final int GLU_TESS_BOUNDARY_ONLY = 100141; + public static final int GLU_TESS_TOLERANCE = 100142; + + /* TessWinding */ + public static final int GLU_TESS_WINDING_ODD = 100130; + public static final int GLU_TESS_WINDING_NONZERO = 100131; + public static final int GLU_TESS_WINDING_POSITIVE = 100132; + public static final int GLU_TESS_WINDING_NEGATIVE = 100133; + public static final int GLU_TESS_WINDING_ABS_GEQ_TWO = 100134; + + /* TessCallback */ + public static final int GLU_TESS_BEGIN = 100100; /* void (CALLBACK*)(GLenum type) */ + public static final int GLU_TESS_VERTEX = 100101; /* void (CALLBACK*)(void *data) */ + public static final int GLU_TESS_END = 100102; /* void (CALLBACK*)(void) */ + public static final int GLU_TESS_ERROR = 100103; /* void (CALLBACK*)(GLenum errno) */ + public static final int GLU_TESS_EDGE_FLAG = 100104; /* void (CALLBACK*)(GLboolean boundaryEdge) */ + public static final int GLU_TESS_COMBINE = 100105; /* void (CALLBACK*)(GLdouble coords[3], + void *data[4], + GLfloat weight[4], + void **dataOut) */ + public static final int GLU_TESS_BEGIN_DATA = 100106; /* void (CALLBACK*)(GLenum type, + void *polygon_data) */ + public static final int GLU_TESS_VERTEX_DATA = 100107; /* void (CALLBACK*)(void *data, + void *polygon_data) */ + public static final int GLU_TESS_END_DATA = 100108; /* void (CALLBACK*)(void *polygon_data) */ + public static final int GLU_TESS_ERROR_DATA = 100109; /* void (CALLBACK*)(GLenum errno, + void *polygon_data) */ + public static final int GLU_TESS_EDGE_FLAG_DATA = 100110; /* void (CALLBACK*)(GLboolean boundaryEdge, + void *polygon_data) */ + public static final int GLU_TESS_COMBINE_DATA = 100111; /* void (CALLBACK*)(GLdouble coords[3], + void *data[4], + GLfloat weight[4], + void **dataOut, + void *polygon_data) */ + + /* TessError */ + public static final int GLU_TESS_ERROR1 = 100151; + public static final int GLU_TESS_ERROR2 = 100152; + public static final int GLU_TESS_ERROR3 = 100153; + public static final int GLU_TESS_ERROR4 = 100154; + public static final int GLU_TESS_ERROR5 = 100155; + public static final int GLU_TESS_ERROR6 = 100156; + public static final int GLU_TESS_ERROR7 = 100157; + public static final int GLU_TESS_ERROR8 = 100158; + + public static final int GLU_TESS_MISSING_BEGIN_POLYGON = GLU_TESS_ERROR1; + public static final int GLU_TESS_MISSING_BEGIN_CONTOUR = GLU_TESS_ERROR2; + public static final int GLU_TESS_MISSING_END_POLYGON = GLU_TESS_ERROR3; + public static final int GLU_TESS_MISSING_END_CONTOUR = GLU_TESS_ERROR4; + public static final int GLU_TESS_COORD_TOO_LARGE = GLU_TESS_ERROR5; + public static final int GLU_TESS_NEED_COMBINE_CALLBACK = GLU_TESS_ERROR6; + + /**** NURBS constants ****/ + + /* NurbsProperty */ + public static final int GLU_AUTO_LOAD_MATRIX = 100200; + public static final int GLU_CULLING = 100201; + public static final int GLU_SAMPLING_TOLERANCE = 100203; + public static final int GLU_DISPLAY_MODE = 100204; + public static final int GLU_PARAMETRIC_TOLERANCE = 100202; + public static final int GLU_SAMPLING_METHOD = 100205; + public static final int GLU_U_STEP = 100206; + public static final int GLU_V_STEP = 100207; + + /* NurbsSampling */ + public static final int GLU_PATH_LENGTH = 100215; + public static final int GLU_PARAMETRIC_ERROR = 100216; + public static final int GLU_DOMAIN_DISTANCE = 100217; + + + /* NurbsTrim */ + public static final int GLU_MAP1_TRIM_2 = 100210; + public static final int GLU_MAP1_TRIM_3 = 100211; + + /* NurbsDisplay */ + /* FILL = 100012 */ + public static final int GLU_OUTLINE_POLYGON = 100240; + public static final int GLU_OUTLINE_PATCH = 100241; + + /* NurbsCallback */ + /* ERROR = 100103 */ + + /* NurbsErrors */ + public static final int GLU_NURBS_ERROR1 = 100251; + public static final int GLU_NURBS_ERROR2 = 100252; + public static final int GLU_NURBS_ERROR3 = 100253; + public static final int GLU_NURBS_ERROR4 = 100254; + public static final int GLU_NURBS_ERROR5 = 100255; + public static final int GLU_NURBS_ERROR6 = 100256; + public static final int GLU_NURBS_ERROR7 = 100257; + public static final int GLU_NURBS_ERROR8 = 100258; + public static final int GLU_NURBS_ERROR9 = 100259; + public static final int GLU_NURBS_ERROR10 = 100260; + public static final int GLU_NURBS_ERROR11 = 100261; + public static final int GLU_NURBS_ERROR12 = 100262; + public static final int GLU_NURBS_ERROR13 = 100263; + public static final int GLU_NURBS_ERROR14 = 100264; + public static final int GLU_NURBS_ERROR15 = 100265; + public static final int GLU_NURBS_ERROR16 = 100266; + public static final int GLU_NURBS_ERROR17 = 100267; + public static final int GLU_NURBS_ERROR18 = 100268; + public static final int GLU_NURBS_ERROR19 = 100269; + public static final int GLU_NURBS_ERROR20 = 100270; + public static final int GLU_NURBS_ERROR21 = 100271; + public static final int GLU_NURBS_ERROR22 = 100272; + public static final int GLU_NURBS_ERROR23 = 100273; + public static final int GLU_NURBS_ERROR24 = 100274; + public static final int GLU_NURBS_ERROR25 = 100275; + public static final int GLU_NURBS_ERROR26 = 100276; + public static final int GLU_NURBS_ERROR27 = 100277; + public static final int GLU_NURBS_ERROR28 = 100278; + public static final int GLU_NURBS_ERROR29 = 100279; + public static final int GLU_NURBS_ERROR30 = 100280; + public static final int GLU_NURBS_ERROR31 = 100281; + public static final int GLU_NURBS_ERROR32 = 100282; + public static final int GLU_NURBS_ERROR33 = 100283; + public static final int GLU_NURBS_ERROR34 = 100284; + public static final int GLU_NURBS_ERROR35 = 100285; + public static final int GLU_NURBS_ERROR36 = 100286; + public static final int GLU_NURBS_ERROR37 = 100287; + + /* Contours types -- obsolete! */ + public static final int GLU_CW = 100120; + public static final int GLU_CCW = 100121; + public static final int GLU_INTERIOR = 100122; + public static final int GLU_EXTERIOR = 100123; + public static final int GLU_UNKNOWN = 100124; + + /* Names without "TESS_" prefix */ + public static final int GLU_BEGIN = GLU_TESS_BEGIN; + public static final int GLU_VERTEX = GLU_TESS_VERTEX; + public static final int GLU_END = GLU_TESS_END; + public static final int GLU_ERROR = GLU_TESS_ERROR; + public static final int GLU_EDGE_FLAG = GLU_TESS_EDGE_FLAG; + + /** + * Method gluLookAt + * @param eyex + * @param eyey + * @param eyez + * @param centerx + * @param centery + * @param centerz + * @param upx + * @param upy + * @param upz + */ + public static void gluLookAt( + float eyex, + float eyey, + float eyez, + float centerx, + float centery, + float centerz, + float upx, + float upy, + float upz) { + + Project.gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz); + } + + /** + * Method gluOrtho2D + * @param left + * @param right + * @param bottom + * @param top + */ + public static void gluOrtho2D( + float left, + float right, + float bottom, + float top) { + + glOrtho(left, right, bottom, top, -1.0, 1.0); + } + + /** + * Method gluPerspective + * @param fovy + * @param aspect + * @param zNear + * @param zFar + */ + public static void gluPerspective( + float fovy, + float aspect, + float zNear, + float zFar) { + + Project.gluPerspective(fovy, aspect, zNear, zFar); + } + + /** + * Method gluProject + * @param objx + * @param objy + * @param objz + * @param modelMatrix + * @param projMatrix + * @param viewport + * @param win_pos + */ + public static boolean gluProject(float objx, float objy, float objz, + FloatBuffer modelMatrix, + FloatBuffer projMatrix, + IntBuffer viewport, + FloatBuffer win_pos) + { + return Project.gluProject(objx, objy, objz, modelMatrix, projMatrix, viewport, win_pos); + } + + /** + * Method gluUnproject + * @param winx + * @param winy + * @param winz + * @param modelMatrix + * @param projMatrix + * @param viewport + * @param obj_pos + */ + public static boolean gluUnProject(float winx, float winy, float winz, + FloatBuffer modelMatrix, + FloatBuffer projMatrix, + IntBuffer viewport, + FloatBuffer obj_pos) + { + return Project.gluUnProject(winx, winy, winz, modelMatrix, projMatrix, viewport, obj_pos); + } + + /** + * Method gluPickMatrix + * @param x + * @param y + * @param width + * @param height + * @param viewport + */ + public static void gluPickMatrix( + float x, + float y, + float width, + float height, + IntBuffer viewport) { + + Project.gluPickMatrix(x, y, width, height, viewport); + } + + /** + * Method gluGetString. + * @param name + * @return String + */ + public static String gluGetString(int name) { + return Registry.gluGetString(name); + } + + /** + * Method gluCheckExtension. + * @param extName + * @param extString + * @return boolean + */ + public static boolean gluCheckExtension(String extName, String extString) { + return Registry.gluCheckExtension(extName, extString); + } + + /** + * Method gluBuild2DMipmaps + * @param target + * @param components + * @param width + * @param height + * @param format + * @param type + * @param data + * @return int + */ + public static int gluBuild2DMipmaps( + int target, + int components, + int width, + int height, + int format, + int type, + ByteBuffer data) { + + return MipMap.gluBuild2DMipmaps(target, components, width, height, format, type, data); + } + + /** + * Method gluScaleImage. + * @param format + * @param widthIn + * @param heightIn + * @param typeIn + * @param dataIn + * @param widthOut + * @param heightOut + * @param typeOut + * @param dataOut + * @return int + */ + public static int gluScaleImage( + int format, + int widthIn, + int heightIn, + int typeIn, + ByteBuffer dataIn, + int widthOut, + int heightOut, + int typeOut, + ByteBuffer dataOut) { + + return MipMap.gluScaleImage(format, widthIn, heightIn, typeIn, dataIn, widthOut, heightOut, typeOut, dataOut); + } + + public static String gluErrorString(int error_code) { + switch (error_code) { + case GLU_INVALID_ENUM: + return "Invalid enum (glu)"; + case GLU_INVALID_VALUE: + return "Invalid value (glu)"; + case GLU_OUT_OF_MEMORY: + return "Out of memory (glu)"; + default: + return Util.translateGLErrorString(error_code); + } + } + + public static GLUtessellator gluNewTess() { + return new GLUtessellatorImpl(); + } +} diff --git a/src/main/java/org/lwjglx/util/glu/GLUtessellator.java b/src/main/java/org/lwjglx/util/glu/GLUtessellator.java new file mode 100644 index 0000000..0bb13dd --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/GLUtessellator.java @@ -0,0 +1,72 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +public interface GLUtessellator { + + void gluDeleteTess(); + + void gluTessProperty(int which, double value); + + /* Returns tessellator property */ + void gluGetTessProperty(int which, double[] value, + int value_offset); /* gluGetTessProperty() */ + + void gluTessNormal(double x, double y, double z); + + void gluTessCallback(int which, + GLUtessellatorCallback aCallback); + + void gluTessVertex(double[] coords, int coords_offset, + Object vertexData); + + void gluTessBeginPolygon(Object data); + + void gluTessBeginContour(); + + void gluTessEndContour(); + + void gluTessEndPolygon(); + + /*******************************************************/ + + /* Obsolete calls -- for backward compatibility */ + + void gluBeginPolygon(); + + /*ARGSUSED*/ + void gluNextContour(int type); + + void gluEndPolygon(); + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallback.java b/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallback.java new file mode 100644 index 0000000..e538c0b --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallback.java @@ -0,0 +1,388 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu; + +/** + * GLUtessellatorCallback interface provides methods that the user will + * override to define the callbacks for a tessellation object. + * + * @author Eric Veach, July 1994 + * @author Java Port: Pepijn Van Eeckhoudt, July 2003 + * @author Java Port: Nathan Parker Burg, August 2003 + */ +public interface GLUtessellatorCallback { + /** + * The begin callback method is invoked like + * {@link javax.media.opengl.GL#glBegin glBegin} to indicate the start of a + * (triangle) primitive. The method takes a single argument of type int. If + * the GLU_TESS_BOUNDARY_ONLY property is set to GL_FALSE, then + * the argument is set to either GL_TRIANGLE_FAN, + * GL_TRIANGLE_STRIP, or GL_TRIANGLES. If the + * GLU_TESS_BOUNDARY_ONLY property is set to GL_TRUE, then the + * argument will be set to GL_LINE_LOOP. + * + * @param type + * Specifics the type of begin/end pair being defined. The following + * values are valid: GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP, + * GL_TRIANGLES or GL_LINE_LOOP. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #end end + * @see #begin begin + */ + void begin(int type); + + /** + * The same as the {@link #begin begin} callback method except that + * it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param type + * Specifics the type of begin/end pair being defined. The following + * values are valid: GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP, + * GL_TRIANGLES or GL_LINE_LOOP. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #endData endData + * @see #begin begin + */ + void beginData(int type, Object polygonData); + + + /** + * The edgeFlag callback method is similar to + * {@link javax.media.opengl.GL#glEdgeFlag glEdgeFlag}. The method takes + * a single boolean boundaryEdge that indicates which edges lie on the + * polygon boundary. If the boundaryEdge is GL_TRUE, then each vertex + * that follows begins an edge that lies on the polygon boundary, that is, + * an edge that separates an interior region from an exterior one. If the + * boundaryEdge is GL_FALSE, then each vertex that follows begins an + * edge that lies in the polygon interior. The edge flag callback (if + * defined) is invoked before the first vertex callback.

+ * + * Since triangle fans and triangle strips do not support edge flags, the + * begin callback is not called with GL_TRIANGLE_FAN or + * GL_TRIANGLE_STRIP if a non-null edge flag callback is provided. + * (If the callback is initialized to null, there is no impact on + * performance). Instead, the fans and strips are converted to independent + * triangles. + * + * @param boundaryEdge + * Specifics which edges lie on the polygon boundary. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #edgeFlagData edgeFlagData + */ + void edgeFlag(boolean boundaryEdge); + + + /** + * The same as the {@link #edgeFlag edgeFlage} callback method + * except that it takes an additional reference argument. This + * reference is identical to the opaque reference provided when + * {@link GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param boundaryEdge + * Specifics which edges lie on the polygon boundary. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #edgeFlag edgeFlag + */ + void edgeFlagData(boolean boundaryEdge, Object polygonData); + + + /** + * The vertex callback method is invoked between the {@link + * #begin begin} and {@link #end end} callback methods. It is + * similar to {@link javax.media.opengl.GL#glVertex3f glVertex3f}, + * and it defines the vertices of the triangles created by the + * tessellation process. The method takes a reference as its only + * argument. This reference is identical to the opaque reference + * provided by the user when the vertex was described (see {@link + * GLU#gluTessVertex gluTessVertex}). + * + * @param vertexData + * Specifics a reference to the vertices of the triangles created + * byt the tessellatin process. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #vertexData vertexData + */ + void vertex(Object vertexData); + + + /** + * The same as the {@link #vertex vertex} callback method except + * that it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param vertexData + * Specifics a reference to the vertices of the triangles created + * byt the tessellatin process. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #vertex vertex + */ + void vertexData(Object vertexData, Object polygonData); + + + /** + * The end callback serves the same purpose as + * {@link javax.media.opengl.GL#glEnd glEnd}. It indicates the end of a + * primitive and it takes no arguments. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #begin begin + * @see #endData endData + */ + void end(); + + + /** + * The same as the {@link #end end} callback method except that it + * takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #beginData beginData + * @see #end end + */ + void endData(Object polygonData); + + + /** + * The combine callback method is called to create a new vertex when + * the tessellation detects an intersection, or wishes to merge features. The + * method takes four arguments: an array of three elements each of type + * double, an array of four references, an array of four elements each of + * type float, and a reference to a reference.

+ * + * The vertex is defined as a linear combination of up to four existing + * vertices, stored in data. The coefficients of the linear combination + * are given by weight; these weights always add up to 1. All vertex + * pointers are valid even when some of the weights are 0. coords gives + * the location of the new vertex.

+ * + * The user must allocate another vertex, interpolate parameters using + * data and weight, and return the new vertex pointer in + * outData. This handle is supplied during rendering callbacks. The + * user is responsible for freeing the memory some time after + * {@link GLU#gluTessEndPolygon gluTessEndPolygon} is + * called.

+ * + * For example, if the polygon lies in an arbitrary plane in 3-space, and a + * color is associated with each vertex, the GLU_TESS_COMBINE + * callback might look like this: + * + *

+   *         void myCombine(double[] coords, Object[] data,
+   *                        float[] weight, Object[] outData)
+   *         {
+   *            MyVertex newVertex = new MyVertex();
+   *
+   *            newVertex.x = coords[0];
+   *            newVertex.y = coords[1];
+   *            newVertex.z = coords[2];
+   *            newVertex.r = weight[0]*data[0].r +
+   *                          weight[1]*data[1].r +
+   *                          weight[2]*data[2].r +
+   *                          weight[3]*data[3].r;
+   *            newVertex.g = weight[0]*data[0].g +
+   *                          weight[1]*data[1].g +
+   *                          weight[2]*data[2].g +
+   *                          weight[3]*data[3].g;
+   *            newVertex.b = weight[0]*data[0].b +
+   *                          weight[1]*data[1].b +
+   *                          weight[2]*data[2].b +
+   *                          weight[3]*data[3].b;
+   *            newVertex.a = weight[0]*data[0].a +
+   *                          weight[1]*data[1].a +
+   *                          weight[2]*data[2].a +
+   *                          weight[3]*data[3].a;
+   *            outData = newVertex;
+   *         }
+ * + * @param coords + * Specifics the location of the new vertex. + * @param data + * Specifics the vertices used to create the new vertex. + * @param weight + * Specifics the weights used to create the new vertex. + * @param outData + * Reference user the put the coodinates of the new vertex. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #combineData combineData + */ + void combine(double[] coords, Object[] data, + float[] weight, Object[] outData); + + + /** + * The same as the {@link #combine combine} callback method except + * that it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param coords + * Specifics the location of the new vertex. + * @param data + * Specifics the vertices used to create the new vertex. + * @param weight + * Specifics the weights used to create the new vertex. + * @param outData + * Reference user the put the coodinates of the new vertex. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #combine combine + */ + void combineData(double[] coords, Object[] data, + float[] weight, Object[] outData, + Object polygonData); + + + /** + * The error callback method is called when an error is encountered. + * The one argument is of type int; it indicates the specific error that + * occurred and will be set to one of GLU_TESS_MISSING_BEGIN_POLYGON, + * GLU_TESS_MISSING_END_POLYGON, GLU_TESS_MISSING_BEGIN_CONTOUR, + * GLU_TESS_MISSING_END_CONTOUR, GLU_TESS_COORD_TOO_LARGE, + * GLU_TESS_NEED_COMBINE_CALLBACK or GLU_OUT_OF_MEMORY. + * Character strings describing these errors can be retrieved with the + * {@link GLU#gluErrorString gluErrorString} call.

+ * + * The GLU library will recover from the first four errors by inserting the + * missing call(s). GLU_TESS_COORD_TOO_LARGE indicates that some + * vertex coordinate exceeded the predefined constant + * GLU_TESS_MAX_COORD in absolute value, and that the value has been + * clamped. (Coordinate values must be small enough so that two can be + * multiplied together without overflow.) + * GLU_TESS_NEED_COMBINE_CALLBACK indicates that the tessellation + * detected an intersection between two edges in the input data, and the + * GLU_TESS_COMBINE or GLU_TESS_COMBINE_DATA callback was not + * provided. No output is generated. GLU_OUT_OF_MEMORY indicates that + * there is not enough memory so no output is generated. + * + * @param errnum + * Specifics the error number code. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #errorData errorData + */ + void error(int errnum); + + + /** + * The same as the {@link #error error} callback method except that + * it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param errnum + * Specifics the error number code. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #error error + */ + void errorData(int errnum, Object polygonData); + + //void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh); +} diff --git a/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallbackAdapter.java b/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallbackAdapter.java new file mode 100644 index 0000000..28facfe --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/GLUtessellatorCallbackAdapter.java @@ -0,0 +1,116 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu; + +/** + * The GLUtessellatorCallbackAdapter provides a default implementation of + * {@link GLUtessellatorCallback GLUtessellatorCallback} + * with empty callback methods. This class can be extended to provide user + * defined callback methods. + * + * @author Eric Veach, July 1994 + * @author Java Port: Pepijn Van Eechhoudt, July 2003 + * @author Java Port: Nathan Parker Burg, August 2003 + */ + +public class GLUtessellatorCallbackAdapter implements GLUtessellatorCallback { + public void begin(int type) {} + public void edgeFlag(boolean boundaryEdge) {} + public void vertex(Object vertexData) {} + public void end() {} +// public void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh) {} + public void error(int errnum) {} + public void combine(double[] coords, Object[] data, + float[] weight, Object[] outData) {} + public void beginData(int type, Object polygonData) {} + public void edgeFlagData(boolean boundaryEdge, + Object polygonData) {} + public void vertexData(Object vertexData, Object polygonData) {} + public void endData(Object polygonData) {} + public void errorData(int errnum, Object polygonData) {} + public void combineData(double[] coords, Object[] data, + float[] weight, Object[] outData, + Object polygonData) {} +} diff --git a/src/main/java/org/lwjglx/util/glu/MipMap.java b/src/main/java/org/lwjglx/util/glu/MipMap.java new file mode 100644 index 0000000..fc9003e --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/MipMap.java @@ -0,0 +1,353 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import java.nio.ByteBuffer; + +import org.lwjglx.BufferUtils; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * MipMap.java + * + * + * Created 11-jan-2004 + * @author Erik Duijs + */ +public class MipMap extends Util { + + /** + * Method gluBuild2DMipmaps + * + * @param target + * @param components + * @param width + * @param height + * @param format + * @param type + * @param data + * @return int + */ + public static int gluBuild2DMipmaps(final int target, + final int components, final int width, final int height, + final int format, final int type, final ByteBuffer data) { + if ( width < 1 || height < 1 ) return GLU_INVALID_VALUE; + + final int bpp = bytesPerPixel(format, type); + if ( bpp == 0 ) + return GLU_INVALID_ENUM; + + final int maxSize = glGetIntegerv(GL_MAX_TEXTURE_SIZE); + + int w = nearestPower(width); + if ( w > maxSize ) + w = maxSize; + + int h = nearestPower(height); + if ( h > maxSize ) + h = maxSize; + + // Get current glPixelStore state + PixelStoreState pss = new PixelStoreState(); + + // set pixel packing + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glPixelStorei(GL_PACK_SKIP_ROWS, 0); + glPixelStorei(GL_PACK_SKIP_PIXELS, 0); + + ByteBuffer image; + int retVal = 0; + boolean done = false; + + if ( w != width || h != height ) { + // must rescale image to get "top" mipmap texture image + image = BufferUtils.createByteBuffer((w + 4) * h * bpp); + int error = gluScaleImage(format, width, height, type, data, w, h, type, image); + if ( error != 0 ) { + retVal = error; + done = true; + } + + /* set pixel unpacking */ + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + } else { + image = data; + } + + ByteBuffer bufferA = null; + ByteBuffer bufferB = null; + + int level = 0; + while ( !done ) { + if (image != data) { + /* set pixel unpacking */ + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + } + + glTexImage2D(target, level, components, w, h, 0, format, type, image); + + if ( w == 1 && h == 1 ) + break; + + final int newW = (w < 2) ? 1 : w >> 1; + final int newH = (h < 2) ? 1 : h >> 1; + + final ByteBuffer newImage; + + if ( bufferA == null ) + newImage = (bufferA = BufferUtils.createByteBuffer((newW + 4) * newH * bpp)); + else if ( bufferB == null ) + newImage = (bufferB = BufferUtils.createByteBuffer((newW + 4) * newH * bpp)); + else + newImage = bufferB; + + int error = gluScaleImage(format, w, h, type, image, newW, newH, type, newImage); + if ( error != 0 ) { + retVal = error; + done = true; + } + + image = newImage; + if ( bufferB != null ) + bufferB = bufferA; + + w = newW; + h = newH; + level++; + } + + // Restore original glPixelStore state + pss.save(); + + return retVal; + } + + /** + * Method gluScaleImage. + * @param format + * @param widthIn + * @param heightIn + * @param typein + * @param dataIn + * @param widthOut + * @param heightOut + * @param typeOut + * @param dataOut + * @return int + */ + public static int gluScaleImage(int format, + int widthIn, int heightIn, int typein, ByteBuffer dataIn, + int widthOut, int heightOut, int typeOut, ByteBuffer dataOut) { + + final int components = compPerPix(format); + if ( components == -1 ) + return GLU_INVALID_ENUM; + + int i, j, k; + float[] tempIn, tempOut; + float sx, sy; + int sizein, sizeout; + int rowstride, rowlen; + + // temp image data + tempIn = new float[widthIn * heightIn * components]; + tempOut = new float[widthOut * heightOut * components]; + + // Determine bytes per input type + switch ( typein ) { + case GL_UNSIGNED_BYTE: + sizein = 1; + break; + case GL_FLOAT: + sizein = 4; + break; + default: + return GL_INVALID_ENUM; + } + + // Determine bytes per output type + switch ( typeOut ) { + case GL_UNSIGNED_BYTE: + sizeout = 1; + break; + case GL_FLOAT: + sizeout = 4; + break; + default: + return GL_INVALID_ENUM; + } + + // Get glPixelStore state + PixelStoreState pss = new PixelStoreState(); + + //Unpack the pixel data and convert to floating point + if ( pss.unpackRowLength > 0 ) + rowlen = pss.unpackRowLength; + else + rowlen = widthIn; + + if ( sizein >= pss.unpackAlignment ) + rowstride = components * rowlen; + else + rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment); + + switch ( typein ) { + case GL_UNSIGNED_BYTE: + k = 0; + dataIn.rewind(); + for ( i = 0; i < heightIn; i++ ) { + int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components; + for ( j = 0; j < widthIn * components; j++ ) { + tempIn[k++] = dataIn.get(ubptr++) & 0xff; + } + } + break; + case GL_FLOAT: + k = 0; + dataIn.rewind(); + for ( i = 0; i < heightIn; i++ ) + { + int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components); + for ( j = 0; j < widthIn * components; j++ ) + { + tempIn[k++] = dataIn.getFloat(fptr); + fptr += 4; + } + } + break; + default: + return GLU_INVALID_ENUM; + } + + // Do scaling + sx = (float)widthIn / (float)widthOut; + sy = (float)heightIn / (float)heightOut; + + float[] c = new float[components]; + int src, dst; + + for ( int iy = 0; iy < heightOut; iy++ ) { + for ( int ix = 0; ix < widthOut; ix++ ) { + int x0 = (int)(ix * sx); + int x1 = (int)((ix + 1) * sx); + int y0 = (int)(iy * sy); + int y1 = (int)((iy + 1) * sy); + + int readPix = 0; + + // reset weighted pixel + for ( int ic = 0; ic < components; ic++ ) { + c[ic] = 0; + } + + // create weighted pixel + for ( int ix0 = x0; ix0 < x1; ix0++ ) { + for ( int iy0 = y0; iy0 < y1; iy0++ ) { + + src = (iy0 * widthIn + ix0) * components; + + for ( int ic = 0; ic < components; ic++ ) { + c[ic] += tempIn[src + ic]; + } + + readPix++; + } + } + + // store weighted pixel + dst = (iy * widthOut + ix) * components; + + if ( readPix == 0 ) { + // Image is sized up, caused by non power of two texture as input + src = (y0 * widthIn + x0) * components; + for ( int ic = 0; ic < components; ic++ ) { + tempOut[dst++] = tempIn[src + ic]; + } + } else { + // sized down + for ( k = 0; k < components; k++ ) { + tempOut[dst++] = c[k] / readPix; + } + } + } + } + + + // Convert temp output + if ( pss.packRowLength > 0 ) + rowlen = pss.packRowLength; + else + rowlen = widthOut; + + if ( sizeout >= pss.packAlignment ) + rowstride = components * rowlen; + else + rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment); + + switch ( typeOut ) { + case GL_UNSIGNED_BYTE: + k = 0; + for ( i = 0; i < heightOut; i++ ) { + int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components; + + for ( j = 0; j < widthOut * components; j++ ) { + dataOut.put(ubptr++, (byte)tempOut[k++]); + } + } + break; + case GL_FLOAT: + k = 0; + for ( i = 0; i < heightOut; i++ ) { + int fptr = 4 * (i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components); + + for ( j = 0; j < widthOut * components; j++ ) { + dataOut.putFloat(fptr, tempOut[k++]); + fptr += 4; + } + } + break; + default: + return GLU_INVALID_ENUM; + } + + return 0; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/PartialDisk.java b/src/main/java/org/lwjglx/util/glu/PartialDisk.java new file mode 100644 index 0000000..2cfc612 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/PartialDisk.java @@ -0,0 +1,358 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * PartialDisk.java + * + * + * Created 23-dec-2003 + * + * @author Erik Duijs + */ +public class PartialDisk extends Quadric { + + private static final int CACHE_SIZE = 240; + + /** + * Constructor for PartialDisk. + */ + public PartialDisk() { + super(); + } + + /** + * renders a partial disk on the z=0 plane. A partial disk is similar to a + * full disk, except that only the subset of the disk from startAngle + * through startAngle + sweepAngle is included (where 0 degrees is along + * the +y axis, 90 degrees along the +x axis, 180 along the -y axis, and + * 270 along the -x axis). + * + * The partial disk has a radius of outerRadius, and contains a concentric + * circular hole with a radius of innerRadius. If innerRadius is zero, then + * no hole is generated. The partial disk is subdivided around the z axis + * into slices (like pizza slices), and also about the z axis into rings + * (as specified by slices and loops, respectively). + * + * With respect to orientation, the +z side of the partial disk is + * considered to be outside (see gluQuadricOrientation). This means that if + * the orientation is set to GLU.GLU_OUTSIDE, then any normals generated point + * along the +z axis. Otherwise, they point along the -z axis. + * + * If texturing is turned on (with gluQuadricTexture), texture coordinates + * are generated linearly such that where r=outerRadius, the value at (r, 0, 0) + * is (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5), + * and at (0, -r, 0) it is (0.5, 0). + */ + public void draw( + float innerRadius, + float outerRadius, + int slices, + int loops, + float startAngle, + float sweepAngle) { + + int i, j; + float[] sinCache = new float[CACHE_SIZE]; + float[] cosCache = new float[CACHE_SIZE]; + float angle; + float sintemp, costemp; + float deltaRadius; + float radiusLow, radiusHigh; + float texLow = 0, texHigh = 0; + float angleOffset; + int slices2; + int finish; + + if (slices >= CACHE_SIZE) + slices = CACHE_SIZE - 1; + if (slices < 2 + || loops < 1 + || outerRadius <= 0.0f + || innerRadius < 0.0f + || innerRadius > outerRadius) { + //gluQuadricError(qobj, GLU.GLU_INVALID_VALUE); + System.err.println("PartialDisk: GLU_INVALID_VALUE"); + return; + } + + if (sweepAngle < -360.0f) + sweepAngle = 360.0f; + if (sweepAngle > 360.0f) + sweepAngle = 360.0f; + if (sweepAngle < 0) { + startAngle += sweepAngle; + sweepAngle = -sweepAngle; + } + + if (sweepAngle == 360.0f) { + slices2 = slices; + } else { + slices2 = slices + 1; + } + + /* Compute length (needed for normal calculations) */ + deltaRadius = outerRadius - innerRadius; + + /* Cache is the vertex locations cache */ + + angleOffset = startAngle / 180.0f * PI; + for (i = 0; i <= slices; i++) { + angle = angleOffset + ((PI * sweepAngle) / 180.0f) * i / slices; + sinCache[i] = sin(angle); + cosCache[i] = cos(angle); + } + + if (sweepAngle == 360.0f) { + sinCache[slices] = sinCache[0]; + cosCache[slices] = cosCache[0]; + } + + switch (super.normals) { + case GLU_FLAT : + case GLU_SMOOTH : + if (super.orientation == GLU_OUTSIDE) { + glNormal3f(0.0f, 0.0f, 1.0f); + } else { + glNormal3f(0.0f, 0.0f, -1.0f); + } + break; + default : + case GLU_NONE : + break; + } + + switch (super.drawStyle) { + case GLU_FILL : + if (innerRadius == .0f) { + finish = loops - 1; + /* Triangle strip for inner polygons */ + glBegin(GL_TRIANGLE_FAN); + if (super.textureFlag) { + glTexCoord2f(0.5f, 0.5f); + } + glVertex3f(0.0f, 0.0f, 0.0f); + radiusLow = outerRadius - deltaRadius * ((float) (loops - 1) / loops); + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + } + + if (super.orientation == GLU_OUTSIDE) { + for (i = slices; i >= 0; i--) { + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + } + } else { + for (i = 0; i <= slices; i++) { + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + } + } + glEnd(); + } else { + finish = loops; + } + for (j = 0; j < finish; j++) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + radiusHigh = outerRadius - deltaRadius * ((float) (j + 1) / loops); + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + texHigh = radiusHigh / outerRadius / 2; + } + + glBegin(GL_QUAD_STRIP); + for (i = 0; i <= slices; i++) { + if (super.orientation == GLU_OUTSIDE) { + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + + if (super.textureFlag) { + glTexCoord2f( + texHigh * sinCache[i] + 0.5f, + texHigh * cosCache[i] + 0.5f); + } + glVertex3f( + radiusHigh * sinCache[i], + radiusHigh * cosCache[i], + 0.0f); + } else { + if (super.textureFlag) { + glTexCoord2f( + texHigh * sinCache[i] + 0.5f, + texHigh * cosCache[i] + 0.5f); + } + glVertex3f( + radiusHigh * sinCache[i], + radiusHigh * cosCache[i], + 0.0f); + + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + } + } + glEnd(); + } + break; + case GLU_POINT : + glBegin(GL_POINTS); + for (i = 0; i < slices2; i++) { + sintemp = sinCache[i]; + costemp = cosCache[i]; + for (j = 0; j <= loops; j++) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f); + } + } + glEnd(); + break; + case GLU_LINE : + if (innerRadius == outerRadius) { + glBegin(GL_LINE_STRIP); + + for (i = 0; i <= slices; i++) { + if (super.textureFlag) { + glTexCoord2f(sinCache[i] / 2 + 0.5f, cosCache[i] / 2 + 0.5f); + } + glVertex3f(innerRadius * sinCache[i], innerRadius * cosCache[i], 0.0f); + } + glEnd(); + break; + } + for (j = 0; j <= loops; j++) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + } + + glBegin(GL_LINE_STRIP); + for (i = 0; i <= slices; i++) { + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + } + glEnd(); + } + for (i = 0; i < slices2; i++) { + sintemp = sinCache[i]; + costemp = cosCache[i]; + glBegin(GL_LINE_STRIP); + for (j = 0; j <= loops; j++) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + } + + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f); + } + glEnd(); + } + break; + case GLU_SILHOUETTE : + if (sweepAngle < 360.0f) { + for (i = 0; i <= slices; i += slices) { + sintemp = sinCache[i]; + costemp = cosCache[i]; + glBegin(GL_LINE_STRIP); + for (j = 0; j <= loops; j++) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sintemp, radiusLow * costemp, 0.0f); + } + glEnd(); + } + } + for (j = 0; j <= loops; j += loops) { + radiusLow = outerRadius - deltaRadius * ((float) j / loops); + if (super.textureFlag) { + texLow = radiusLow / outerRadius / 2; + } + + glBegin(GL_LINE_STRIP); + for (i = 0; i <= slices; i++) { + if (super.textureFlag) { + glTexCoord2f( + texLow * sinCache[i] + 0.5f, + texLow * cosCache[i] + 0.5f); + } + glVertex3f(radiusLow * sinCache[i], radiusLow * cosCache[i], 0.0f); + } + glEnd(); + if (innerRadius == outerRadius) + break; + } + break; + default : + break; + } + } +} diff --git a/src/main/java/org/lwjglx/util/glu/PixelStoreState.java b/src/main/java/org/lwjglx/util/glu/PixelStoreState.java new file mode 100644 index 0000000..12b0595 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/PixelStoreState.java @@ -0,0 +1,84 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; + +/** + * PixelStoreState.java + * + * + * Created 11-jan-2004 + * @author Erik Duijs + */ +class PixelStoreState extends Util { + + public int unpackRowLength; + public int unpackAlignment; + public int unpackSkipRows; + public int unpackSkipPixels; + public int packRowLength; + public int packAlignment; + public int packSkipRows; + public int packSkipPixels; + + /** + * Constructor for PixelStoreState. + */ + PixelStoreState() { + super(); + load(); + } + + public void load() { + unpackRowLength = glGetIntegerv(GL_UNPACK_ROW_LENGTH); + unpackAlignment = glGetIntegerv(GL_UNPACK_ALIGNMENT); + unpackSkipRows = glGetIntegerv(GL_UNPACK_SKIP_ROWS); + unpackSkipPixels = glGetIntegerv(GL_UNPACK_SKIP_PIXELS); + packRowLength = glGetIntegerv(GL_PACK_ROW_LENGTH); + packAlignment = glGetIntegerv(GL_PACK_ALIGNMENT); + packSkipRows = glGetIntegerv(GL_PACK_SKIP_ROWS); + packSkipPixels = glGetIntegerv(GL_PACK_SKIP_PIXELS); + } + + public void save() { + glPixelStorei(GL_UNPACK_ROW_LENGTH, unpackRowLength); + glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlignment); + glPixelStorei(GL_UNPACK_SKIP_ROWS, unpackSkipRows); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, unpackSkipPixels); + glPixelStorei(GL_PACK_ROW_LENGTH, packRowLength); + glPixelStorei(GL_PACK_ALIGNMENT, packAlignment); + glPixelStorei(GL_PACK_SKIP_ROWS, packSkipRows); + glPixelStorei(GL_PACK_SKIP_PIXELS, packSkipPixels); + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/Project.java b/src/main/java/org/lwjglx/util/glu/Project.java new file mode 100644 index 0000000..50be46a --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Project.java @@ -0,0 +1,411 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; + +import static org.lwjgl.opengl.GL11.*; + +/** + * Project.java + *

+ *

+ * Created 11-jan-2004 + * + * @author Erik Duijs + */ +public class Project extends Util { + + private static final float[] IDENTITY_MATRIX = + new float[] { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; + + private static final FloatBuffer matrix = BufferUtils.createFloatBuffer(16); + private static final FloatBuffer finalMatrix = BufferUtils.createFloatBuffer(16); + + private static final FloatBuffer tempMatrix = BufferUtils.createFloatBuffer(16); + private static final float[] in = new float[4]; + private static final float[] out = new float[4]; + + private static final float[] forward = new float[3]; + private static final float[] side = new float[3]; + private static final float[] up = new float[3]; + + /** + * Make matrix an identity matrix + */ + private static void __gluMakeIdentityf(FloatBuffer m) { + int oldPos = m.position(); + m.put(IDENTITY_MATRIX); + m.position(oldPos); + } + + /** + * Method __gluMultMatrixVecf + * + * @param finalMatrix + * @param in + * @param out + */ + private static void __gluMultMatrixVecf(FloatBuffer m, float[] in, float[] out) { + for (int i = 0; i < 4; i++) { + out[i] = + in[0] * m.get(m.position() + 0*4 + i) + + in[1] * m.get(m.position() + 1*4 + i) + + in[2] * m.get(m.position() + 2*4 + i) + + in[3] * m.get(m.position() + 3*4 + i); + + } + } + + /** + * @param src + * @param inverse + * + * @return + */ + private static boolean __gluInvertMatrixf(FloatBuffer src, FloatBuffer inverse) { + int i, j, k, swap; + float t; + FloatBuffer temp = Project.tempMatrix; + + + for (i = 0; i < 16; i++) { + temp.put(i, src.get(i + src.position())); + } + __gluMakeIdentityf(inverse); + + for (i = 0; i < 4; i++) { + /* + * * Look for largest element in column + */ + swap = i; + for (j = i + 1; j < 4; j++) { + /* + * if (fabs(temp[j][i]) > fabs(temp[i][i])) { swap = j; + */ + if (Math.abs(temp.get(j*4 + i)) > Math.abs(temp.get(i* 4 + i))) { + swap = j; + } + } + + if (swap != i) { + /* + * * Swap rows. + */ + for (k = 0; k < 4; k++) { + t = temp.get(i*4 + k); + temp.put(i*4 + k, temp.get(swap*4 + k)); + temp.put(swap*4 + k, t); + + t = inverse.get(i*4 + k); + inverse.put(i*4 + k, inverse.get(swap*4 + k)); + //inverse.put((i << 2) + k, inverse.get((swap << 2) + k)); + inverse.put(swap*4 + k, t); + //inverse.put((swap << 2) + k, t); + } + } + + if (temp.get(i*4 + i) == 0) { + /* + * * No non-zero pivot. The matrix is singular, which shouldn't * + * happen. This means the user gave us a bad matrix. + */ + return false; + } + + t = temp.get(i*4 + i); + for (k = 0; k < 4; k++) { + temp.put(i*4 + k, temp.get(i*4 + k)/t); + inverse.put(i*4 + k, inverse.get(i*4 + k)/t); + } + for (j = 0; j < 4; j++) { + if (j != i) { + t = temp.get(j*4 + i); + for (k = 0; k < 4; k++) { + temp.put(j*4 + k, temp.get(j*4 + k) - temp.get(i*4 + k) * t); + inverse.put(j*4 + k, inverse.get(j*4 + k) - inverse.get(i*4 + k) * t); + /*inverse.put( + (j << 2) + k, + inverse.get((j << 2) + k) - inverse.get((i << 2) + k) * t);*/ + } + } + } + } + return true; + } + + /** + * @param a + * @param b + * @param r + */ + private static void __gluMultMatricesf(FloatBuffer a, FloatBuffer b, FloatBuffer r) { + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + r.put(r.position() + i*4 + j, + a.get(a.position() + i*4 + 0) * b.get(b.position() + 0*4 + j) + a.get(a.position() + i*4 + 1) * b.get(b.position() + 1*4 + j) + a.get(a.position() + i*4 + 2) * b.get(b.position() + 2*4 + j) + a.get(a.position() + i*4 + 3) * b.get(b.position() + 3*4 + j)); + } + } + } + + /** + * Method gluPerspective. + * + * @param fovy + * @param aspect + * @param zNear + * @param zFar + */ + public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) { + float sine, cotangent, deltaZ; + float radians = fovy / 2 * GLU.PI / 180; + + deltaZ = zFar - zNear; + sine = (float) Math.sin(radians); + + if ((deltaZ == 0) || (sine == 0) || (aspect == 0)) { + return; + } + + cotangent = (float) Math.cos(radians) / sine; + + __gluMakeIdentityf(matrix); + + matrix.put(0 * 4 + 0, cotangent / aspect); + matrix.put(1 * 4 + 1, cotangent); + matrix.put(2 * 4 + 2, - (zFar + zNear) / deltaZ); + matrix.put(2 * 4 + 3, -1); + matrix.put(3 * 4 + 2, -2 * zNear * zFar / deltaZ); + matrix.put(3 * 4 + 3, 0); + + glMultMatrix(matrix); + } + + /** + * Method gluLookAt + * + * @param eyex + * @param eyey + * @param eyez + * @param centerx + * @param centery + * @param centerz + * @param upx + * @param upy + * @param upz + */ + public static void gluLookAt( + float eyex, + float eyey, + float eyez, + float centerx, + float centery, + float centerz, + float upx, + float upy, + float upz) { + float[] forward = Project.forward; + float[] side = Project.side; + float[] up = Project.up; + + forward[0] = centerx - eyex; + forward[1] = centery - eyey; + forward[2] = centerz - eyez; + + up[0] = upx; + up[1] = upy; + up[2] = upz; + + normalize(forward); + + /* Side = forward x up */ + cross(forward, up, side); + normalize(side); + + /* Recompute up as: up = side x forward */ + cross(side, forward, up); + + __gluMakeIdentityf(matrix); + matrix.put(0 * 4 + 0, side[0]); + matrix.put(1 * 4 + 0, side[1]); + matrix.put(2 * 4 + 0, side[2]); + + matrix.put(0 * 4 + 1, up[0]); + matrix.put(1 * 4 + 1, up[1]); + matrix.put(2 * 4 + 1, up[2]); + + matrix.put(0 * 4 + 2, -forward[0]); + matrix.put(1 * 4 + 2, -forward[1]); + matrix.put(2 * 4 + 2, -forward[2]); + + glMultMatrix(matrix); + glTranslatef(-eyex, -eyey, -eyez); + } + + /** + * Method gluProject + * + * @param objx + * @param objy + * @param objz + * @param modelMatrix + * @param projMatrix + * @param viewport + * @param win_pos + */ + public static boolean gluProject( + float objx, + float objy, + float objz, + FloatBuffer modelMatrix, + FloatBuffer projMatrix, + IntBuffer viewport, + FloatBuffer win_pos) { + + float[] in = Project.in; + float[] out = Project.out; + + in[0] = objx; + in[1] = objy; + in[2] = objz; + in[3] = 1.0f; + + __gluMultMatrixVecf(modelMatrix, in, out); + __gluMultMatrixVecf(projMatrix, out, in); + + if (in[3] == 0.0) + return false; + + in[3] = (1.0f / in[3]) * 0.5f; + + // Map x, y and z to range 0-1 + in[0] = in[0] * in[3] + 0.5f; + in[1] = in[1] * in[3] + 0.5f; + in[2] = in[2] * in[3] + 0.5f; + + // Map x,y to viewport + win_pos.put(0, in[0] * viewport.get(viewport.position() + 2) + viewport.get(viewport.position() + 0)); + win_pos.put(1, in[1] * viewport.get(viewport.position() + 3) + viewport.get(viewport.position() + 1)); + win_pos.put(2, in[2]); + + return true; + } + + /** + * Method gluUnproject + * + * @param winx + * @param winy + * @param winz + * @param modelMatrix + * @param projMatrix + * @param viewport + * @param obj_pos + */ + public static boolean gluUnProject( + float winx, + float winy, + float winz, + FloatBuffer modelMatrix, + FloatBuffer projMatrix, + IntBuffer viewport, + FloatBuffer obj_pos) { + float[] in = Project.in; + float[] out = Project.out; + + __gluMultMatricesf(modelMatrix, projMatrix, finalMatrix); + + if (!__gluInvertMatrixf(finalMatrix, finalMatrix)) + return false; + + in[0] = winx; + in[1] = winy; + in[2] = winz; + in[3] = 1.0f; + + // Map x and y from window coordinates + in[0] = (in[0] - viewport.get(viewport.position() + 0)) / viewport.get(viewport.position() + 2); + in[1] = (in[1] - viewport.get(viewport.position() + 1)) / viewport.get(viewport.position() + 3); + + // Map to range -1 to 1 + in[0] = in[0] * 2 - 1; + in[1] = in[1] * 2 - 1; + in[2] = in[2] * 2 - 1; + + __gluMultMatrixVecf(finalMatrix, in, out); + + if (out[3] == 0.0) + return false; + + out[3] = 1.0f / out[3]; + + obj_pos.put(obj_pos.position() + 0, out[0] * out[3]); + obj_pos.put(obj_pos.position() + 1, out[1] * out[3]); + obj_pos.put(obj_pos.position() + 2, out[2] * out[3]); + + return true; + } + + /** + * Method gluPickMatrix + * + * @param x + * @param y + * @param deltaX + * @param deltaY + * @param viewport + */ + public static void gluPickMatrix( + float x, + float y, + float deltaX, + float deltaY, + IntBuffer viewport) { + if (deltaX <= 0 || deltaY <= 0) { + return; + } + + /* Translate and scale the picked region to the entire window */ + glTranslatef( + (viewport.get(viewport.position() + 2) - 2 * (x - viewport.get(viewport.position() + 0))) / deltaX, + (viewport.get(viewport.position() + 3) - 2 * (y - viewport.get(viewport.position() + 1))) / deltaY, + 0); + glScalef(viewport.get(viewport.position() + 2) / deltaX, viewport.get(viewport.position() + 3) / deltaY, 1.0f); + } +} diff --git a/src/main/java/org/lwjglx/util/glu/Quadric.java b/src/main/java/org/lwjglx/util/glu/Quadric.java new file mode 100644 index 0000000..5a508d3 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Quadric.java @@ -0,0 +1,199 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * Quadric.java + * + * + * Created 22-dec-2003 + * @author Erik Duijs + */ +public class Quadric { + + protected int drawStyle; + protected int orientation; + protected boolean textureFlag; + protected int normals; + + /** + * Constructor for Quadric. + */ + public Quadric() { + super(); + + drawStyle = GLU_FILL; + orientation = GLU_OUTSIDE; + textureFlag = false; + normals = GLU_SMOOTH; + } + + /** + * Call glNormal3f after scaling normal to unit length. + * + * @param x + * @param y + * @param z + */ + protected void normal3f(float x, float y, float z) { + float mag; + + mag = (float)Math.sqrt(x * x + y * y + z * z); + if (mag > 0.00001F) { + x /= mag; + y /= mag; + z /= mag; + } + glNormal3f(x, y, z); + } + + /** + * specifies the draw style for quadrics. + * + * The legal values are as follows: + * + * GLU.FILL: Quadrics are rendered with polygon primitives. The polygons + * are drawn in a counterclockwise fashion with respect to + * their normals (as defined with glu.quadricOrientation). + * + * GLU.LINE: Quadrics are rendered as a set of lines. + * + * GLU.SILHOUETTE: Quadrics are rendered as a set of lines, except that edges + * separating coplanar faces will not be drawn. + * + * GLU.POINT: Quadrics are rendered as a set of points. + * + * @param drawStyle The drawStyle to set + */ + public void setDrawStyle(int drawStyle) { + this.drawStyle = drawStyle; + } + + /** + * specifies what kind of normals are desired for quadrics. + * The legal values are as follows: + * + * GLU.NONE: No normals are generated. + * + * GLU.FLAT: One normal is generated for every facet of a quadric. + * + * GLU.SMOOTH: One normal is generated for every vertex of a quadric. This + * is the default. + * + * @param normals The normals to set + */ + public void setNormals(int normals) { + this.normals = normals; + } + + /** + * specifies what kind of orientation is desired for. + * The orientation values are as follows: + * + * GLU.OUTSIDE: Quadrics are drawn with normals pointing outward. + * + * GLU.INSIDE: Normals point inward. The default is GLU.OUTSIDE. + * + * Note that the interpretation of outward and inward depends on the quadric + * being drawn. + * + * @param orientation The orientation to set + */ + public void setOrientation(int orientation) { + this.orientation = orientation; + } + + /** + * specifies if texture coordinates should be generated for + * quadrics rendered with qobj. If the value of textureCoords is true, + * then texture coordinates are generated, and if textureCoords is false, + * they are not.. The default is false. + * + * The manner in which texture coordinates are generated depends upon the + * specific quadric rendered. + * + * @param textureFlag The textureFlag to set + */ + public void setTextureFlag(boolean textureFlag) { + this.textureFlag = textureFlag; + } + + + /** + * Returns the drawStyle. + * @return int + */ + public int getDrawStyle() { + return drawStyle; + } + + /** + * Returns the normals. + * @return int + */ + public int getNormals() { + return normals; + } + + /** + * Returns the orientation. + * @return int + */ + public int getOrientation() { + return orientation; + } + + /** + * Returns the textureFlag. + * @return boolean + */ + public boolean getTextureFlag() { + return textureFlag; + } + + protected void TXTR_COORD(float x, float y) { + if (textureFlag) glTexCoord2f(x,y); + } + + + protected float sin(float r) { + return (float)Math.sin(r); + } + + protected float cos(float r) { + return (float)Math.cos(r); + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/Registry.java b/src/main/java/org/lwjglx/util/glu/Registry.java new file mode 100644 index 0000000..e49340d --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Registry.java @@ -0,0 +1,80 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjglx.util.glu.GLU.*; + +/** + * Registry.java + * + * + * Created 11-jan-2004 + * @author Erik Duijs + */ +public class Registry extends Util { + + private static final String versionString = "1.3"; + private static final String extensionString = + "GLU_EXT_nurbs_tessellator " + "GLU_EXT_object_space_tess "; + + /** + * Method gluGetString + * @param name + * @return String + */ + public static String gluGetString(int name) { + + if (name == GLU_VERSION) { + return versionString; + } else if (name == GLU_EXTENSIONS) { + return extensionString; + } + return null; + } + + /** + * Method gluCheckExtension + * + * @param extName is an extension name. + * @param extString is a string of extensions separated by blank(s). There may or + * may not be leading or trailing blank(s) in extString. + * This works in cases of extensions being prefixes of another like + * GL_EXT_texture and GL_EXT_texture3D. + * @return boolean true if extName is found otherwise it returns false. + */ + public static boolean gluCheckExtension(String extName, String extString) { + if (extString == null || extName == null) + return false; + + return extString.indexOf(extName) != -1; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/Sphere.java b/src/main/java/org/lwjglx/util/glu/Sphere.java new file mode 100644 index 0000000..f14ac20 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Sphere.java @@ -0,0 +1,229 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +/** + * Sphere.java + * + * + * Created 23-dec-2003 + * @author Erik Duijs + */ +public class Sphere extends Quadric { + + /** + * Constructor + */ + public Sphere() { + super(); + } + + /** + * draws a sphere of the given radius centered around the origin. + * The sphere is subdivided around the z axis into slices and along the z axis + * into stacks (similar to lines of longitude and latitude). + * + * If the orientation is set to GLU.OUTSIDE (with glu.quadricOrientation), then + * any normals generated point away from the center of the sphere. Otherwise, + * they point toward the center of the sphere. + + * If texturing is turned on (with glu.quadricTexture), then texture + * coordinates are generated so that t ranges from 0.0 at z=-radius to 1.0 at + * z=radius (t increases linearly along longitudinal lines), and s ranges from + * 0.0 at the +y axis, to 0.25 at the +x axis, to 0.5 at the -y axis, to 0.75 + * at the -x axis, and back to 1.0 at the +y axis. + */ + public void draw(float radius, int slices, int stacks) { + // TODO + + float rho, drho, theta, dtheta; + float x, y, z; + float s, t, ds, dt; + int i, j, imin, imax; + boolean normals; + float nsign; + + normals = super.normals != GLU_NONE; + + if (super.orientation == GLU_INSIDE) { + nsign = -1.0f; + } else { + nsign = 1.0f; + } + + drho = PI / stacks; + dtheta = 2.0f * PI / slices; + + if (super.drawStyle == GLU_FILL) { + if (!super.textureFlag) { + // draw +Z end as a triangle fan + glBegin(GL_TRIANGLE_FAN); + glNormal3f(0.0f, 0.0f, 1.0f); + glVertex3f(0.0f, 0.0f, nsign * radius); + for (j = 0; j <= slices; j++) { + theta = (j == slices) ? 0.0f : j * dtheta; + x = -sin(theta) * sin(drho); + y = cos(theta) * sin(drho); + z = nsign * cos(drho); + if (normals) { + glNormal3f(x * nsign, y * nsign, z * nsign); + } + glVertex3f(x * radius, y * radius, z * radius); + } + glEnd(); + } + + ds = 1.0f / slices; + dt = 1.0f / stacks; + t = 1.0f; // because loop now runs from 0 + if (super.textureFlag) { + imin = 0; + imax = stacks; + } else { + imin = 1; + imax = stacks - 1; + } + + // draw intermediate stacks as quad strips + for (i = imin; i < imax; i++) { + rho = i * drho; + glBegin(GL_QUAD_STRIP); + s = 0.0f; + for (j = 0; j <= slices; j++) { + theta = (j == slices) ? 0.0f : j * dtheta; + x = -sin(theta) * sin(rho); + y = cos(theta) * sin(rho); + z = nsign * cos(rho); + if (normals) { + glNormal3f(x * nsign, y * nsign, z * nsign); + } + TXTR_COORD(s, t); + glVertex3f(x * radius, y * radius, z * radius); + x = -sin(theta) * sin(rho + drho); + y = cos(theta) * sin(rho + drho); + z = nsign * cos(rho + drho); + if (normals) { + glNormal3f(x * nsign, y * nsign, z * nsign); + } + TXTR_COORD(s, t - dt); + s += ds; + glVertex3f(x * radius, y * radius, z * radius); + } + glEnd(); + t -= dt; + } + + if (!super.textureFlag) { + // draw -Z end as a triangle fan + glBegin(GL_TRIANGLE_FAN); + glNormal3f(0.0f, 0.0f, -1.0f); + glVertex3f(0.0f, 0.0f, -radius * nsign); + rho = PI - drho; + s = 1.0f; + for (j = slices; j >= 0; j--) { + theta = (j == slices) ? 0.0f : j * dtheta; + x = -sin(theta) * sin(rho); + y = cos(theta) * sin(rho); + z = nsign * cos(rho); + if (normals) + glNormal3f(x * nsign, y * nsign, z * nsign); + s -= ds; + glVertex3f(x * radius, y * radius, z * radius); + } + glEnd(); + } + } else if ( + super.drawStyle == GLU_LINE + || super.drawStyle == GLU_SILHOUETTE) { + // draw stack lines + for (i = 1; + i < stacks; + i++) { // stack line at i==stacks-1 was missing here + rho = i * drho; + glBegin(GL_LINE_LOOP); + for (j = 0; j < slices; j++) { + theta = j * dtheta; + x = cos(theta) * sin(rho); + y = sin(theta) * sin(rho); + z = cos(rho); + if (normals) + glNormal3f(x * nsign, y * nsign, z * nsign); + glVertex3f(x * radius, y * radius, z * radius); + } + glEnd(); + } + // draw slice lines + for (j = 0; j < slices; j++) { + theta = j * dtheta; + glBegin(GL_LINE_STRIP); + for (i = 0; i <= stacks; i++) { + rho = i * drho; + x = cos(theta) * sin(rho); + y = sin(theta) * sin(rho); + z = cos(rho); + if (normals) + glNormal3f(x * nsign, y * nsign, z * nsign); + glVertex3f(x * radius, y * radius, z * radius); + } + glEnd(); + } + } else if (super.drawStyle == GLU_POINT) { + // top and bottom-most points + glBegin(GL_POINTS); + if (normals) + glNormal3f(0.0f, 0.0f, nsign); + glVertex3f(0.0f, 0.0f, radius); + if (normals) + glNormal3f(0.0f, 0.0f, -nsign); + glVertex3f(0.0f, 0.0f, -radius); + + // loop over stacks + for (i = 1; i < stacks - 1; i++) { + rho = i * drho; + for (j = 0; j < slices; j++) { + theta = j * dtheta; + x = cos(theta) * sin(rho); + y = sin(theta) * sin(rho); + z = cos(rho); + if (normals) + glNormal3f(x * nsign, y * nsign, z * nsign); + glVertex3f(x * radius, y * radius, z * radius); + } + } + glEnd(); + } + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/Util.java b/src/main/java/org/lwjglx/util/glu/Util.java new file mode 100644 index 0000000..d505da4 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/Util.java @@ -0,0 +1,247 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.glu; + +import java.nio.IntBuffer; + +import org.lwjgl.BufferUtils; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjgl.opengl.GL12.*; + +/** + * Util.java + *

+ *

+ * Created 7-jan-2004 + * + * @author Erik Duijs + */ +public class Util { + + /** + * temp IntBuffer of one for getting an int from some GL functions + */ + private static IntBuffer scratch = BufferUtils.createIntBuffer(16); + + /** + * Return ceiling of integer division + * + * @param a + * @param b + * + * @return int + */ + protected static int ceil(int a, int b) { + return (a % b == 0 ? a / b : a / b + 1); + } + + /** + * Normalize vector + * + * @param v + * + * @return float[] + */ + protected static float[] normalize(float[] v) { + float r; + + r = (float)Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + if ( r == 0.0 ) + return v; + + r = 1.0f / r; + + v[0] *= r; + v[1] *= r; + v[2] *= r; + + return v; + } + + /** + * Calculate cross-product + * + * @param v1 + * @param v2 + * @param result + */ + protected static void cross(float[] v1, float[] v2, float[] result) { + result[0] = v1[1] * v2[2] - v1[2] * v2[1]; + result[1] = v1[2] * v2[0] - v1[0] * v2[2]; + result[2] = v1[0] * v2[1] - v1[1] * v2[0]; + } + + /** + * Method compPerPix. + * + * @param format + * + * @return int + */ + protected static int compPerPix(int format) { + /* Determine number of components per pixel */ + switch ( format ) { + case GL_COLOR_INDEX: + case GL_STENCIL_INDEX: + case GL_DEPTH_COMPONENT: + case GL_RED: + case GL_GREEN: + case GL_BLUE: + case GL_ALPHA: + case GL_LUMINANCE: + return 1; + case GL_LUMINANCE_ALPHA: + return 2; + case GL_RGB: + case GL_BGR: + return 3; + case GL_RGBA: + case GL_BGRA: + return 4; + default : + return -1; + } + } + + /** + * Method nearestPower. + *

+ * Compute the nearest power of 2 number. This algorithm is a little strange, but it works quite well. + * + * @param value + * + * @return int + */ + protected static int nearestPower(int value) { + int i; + + i = 1; + + /* Error! */ + if ( value == 0 ) + return -1; + + for ( ; ; ) { + if ( value == 1 ) { + return i; + } else if ( value == 3 ) { + return i << 2; + } + value >>= 1; + i <<= 1; + } + } + + /** + * Method bytesPerPixel. + * + * @param format + * @param type + * + * @return int + */ + protected static int bytesPerPixel(int format, int type) { + int n, m; + + switch ( format ) { + case GL_COLOR_INDEX: + case GL_STENCIL_INDEX: + case GL_DEPTH_COMPONENT: + case GL_RED: + case GL_GREEN: + case GL_BLUE: + case GL_ALPHA: + case GL_LUMINANCE: + n = 1; + break; + case GL_LUMINANCE_ALPHA: + n = 2; + break; + case GL_RGB: + case GL_BGR: + n = 3; + break; + case GL_RGBA: + case GL_BGRA: + n = 4; + break; + default : + n = 0; + } + + switch ( type ) { + case GL_UNSIGNED_BYTE: + m = 1; + break; + case GL_BYTE: + m = 1; + break; + case GL_BITMAP: + m = 1; + break; + case GL_UNSIGNED_SHORT: + m = 2; + break; + case GL_SHORT: + m = 2; + break; + case GL_UNSIGNED_INT: + m = 4; + break; + case GL_INT: + m = 4; + break; + case GL_FLOAT: + m = 4; + break; + default : + m = 0; + } + + return n * m; + } + + /** + * Convenience method for returning an int, rather than getting it out of a buffer yourself. + * + * @param what + * + * @return int + */ + protected static int glGetIntegerv(int what) { + scratch.rewind(); + glGetInteger(what, scratch); + return scratch.get(); + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/ActiveRegion.java b/src/main/java/org/lwjglx/util/glu/tessellation/ActiveRegion.java new file mode 100644 index 0000000..12be5f0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/ActiveRegion.java @@ -0,0 +1,100 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class ActiveRegion { + GLUhalfEdge eUp; /* upper edge, directed right to left */ + DictNode nodeUp; /* dictionary node corresponding to eUp */ + int windingNumber; /* used to determine which regions are + * inside the polygon */ + boolean inside; /* is this region inside the polygon? */ + boolean sentinel; /* marks fake edges at t = +/-infinity */ + boolean dirty; /* marks regions where the upper or lower + * edge has changed, but we haven't checked + * whether they intersect yet */ + boolean fixUpperEdge; /* marks temporary edges introduced when + * we process a "right vertex" (one without + * any edges leaving to the right) */ +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/CachedVertex.java b/src/main/java/org/lwjglx/util/glu/tessellation/CachedVertex.java new file mode 100644 index 0000000..1cb8ccd --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/CachedVertex.java @@ -0,0 +1,90 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class CachedVertex { + public double[] coords = new double[3]; + public Object data; +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Dict.java b/src/main/java/org/lwjglx/util/glu/tessellation/Dict.java new file mode 100644 index 0000000..6be1e5d --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Dict.java @@ -0,0 +1,172 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class Dict { + DictNode head; + Object frame; + DictLeq leq; + + private Dict() { + } + + static Dict dictNewDict(Object frame, DictLeq leq) { + Dict dict = new Dict(); + dict.head = new DictNode(); + + dict.head.key = null; + dict.head.next = dict.head; + dict.head.prev = dict.head; + + dict.frame = frame; + dict.leq = leq; + + return dict; + } + + static void dictDeleteDict(Dict dict) { + dict.head = null; + dict.frame = null; + dict.leq = null; + } + + static DictNode dictInsert(Dict dict, Object key) { + return dictInsertBefore(dict, dict.head, key); + } + + static DictNode dictInsertBefore(Dict dict, DictNode node, Object key) { + do { + node = node.prev; + } while (node.key != null && !dict.leq.leq(dict.frame, node.key, key)); + + DictNode newNode = new DictNode(); + newNode.key = key; + newNode.next = node.next; + node.next.prev = newNode; + newNode.prev = node; + node.next = newNode; + + return newNode; + } + + static Object dictKey(DictNode aNode) { + return aNode.key; + } + + static DictNode dictSucc(DictNode aNode) { + return aNode.next; + } + + static DictNode dictPred(DictNode aNode) { + return aNode.prev; + } + + static DictNode dictMin(Dict aDict) { + return aDict.head.next; + } + + static DictNode dictMax(Dict aDict) { + return aDict.head.prev; + } + + static void dictDelete(Dict dict, DictNode node) { + node.next.prev = node.prev; + node.prev.next = node.next; + } + + static DictNode dictSearch(Dict dict, Object key) { + DictNode node = dict.head; + + do { + node = node.next; + } while (node.key != null && !(dict.leq.leq(dict.frame, key, node.key))); + + return node; + } + + public interface DictLeq { + boolean leq(Object frame, Object key1, Object key2); + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/DictNode.java b/src/main/java/org/lwjglx/util/glu/tessellation/DictNode.java new file mode 100644 index 0000000..2817706 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/DictNode.java @@ -0,0 +1,91 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class DictNode { + Object key; + DictNode next; + DictNode prev; +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/GLUface.java b/src/main/java/org/lwjglx/util/glu/tessellation/GLUface.java new file mode 100644 index 0000000..2bd13d1 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/GLUface.java @@ -0,0 +1,97 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class GLUface { + public GLUface next; /* next face (never NULL) */ + public GLUface prev; /* previous face (never NULL) */ + public GLUhalfEdge anEdge; /* a half edge with this left face */ + public Object data; /* room for client's data */ + + /* Internal data (keep hidden) */ + public GLUface trail; /* "stack" for conversion to strips */ + public boolean marked; /* flag for conversion to strips */ + public boolean inside; /* this face is in the polygon interior */ +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/GLUhalfEdge.java b/src/main/java/org/lwjglx/util/glu/tessellation/GLUhalfEdge.java new file mode 100644 index 0000000..2854fd8 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/GLUhalfEdge.java @@ -0,0 +1,105 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + + + +class GLUhalfEdge { + public GLUhalfEdge next; /* doubly-linked list (prev==Sym->next) */ + public GLUhalfEdge Sym; /* same edge, opposite direction */ + public GLUhalfEdge Onext; /* next edge CCW around origin */ + public GLUhalfEdge Lnext; /* next edge CCW around left face */ + public GLUvertex Org; /* origin vertex (Overtex too long) */ + public GLUface Lface; /* left face */ + + /* Internal data (keep hidden) */ + public ActiveRegion activeRegion; /* a region with this upper edge (sweep.c) */ + public int winding; /* change in winding number when crossing */ + public boolean first; + + GLUhalfEdge(boolean first) { + this.first = first; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/GLUmesh.java b/src/main/java/org/lwjglx/util/glu/tessellation/GLUmesh.java new file mode 100644 index 0000000..b80d361 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/GLUmesh.java @@ -0,0 +1,94 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + + + +class GLUmesh { + GLUvertex vHead = new GLUvertex(); /* dummy header for vertex list */ + GLUface fHead = new GLUface(); /* dummy header for face list */ + GLUhalfEdge eHead = new GLUhalfEdge(true); /* dummy header for edge list */ + GLUhalfEdge eHeadSym = new GLUhalfEdge(false); /* and its symmetric counterpart */ +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/GLUtessellatorImpl.java b/src/main/java/org/lwjglx/util/glu/tessellation/GLUtessellatorImpl.java new file mode 100644 index 0000000..b25b9c7 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/GLUtessellatorImpl.java @@ -0,0 +1,669 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +import org.lwjglx.util.glu.GLUtessellator; +import org.lwjglx.util.glu.GLUtessellatorCallback; +import org.lwjglx.util.glu.GLUtessellatorCallbackAdapter; + +import static org.lwjglx.util.glu.GLU.*; + +public class GLUtessellatorImpl implements GLUtessellator { + public static final int TESS_MAX_CACHE = 100; + + private int state; /* what begin/end calls have we seen? */ + + private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */ + GLUmesh mesh; /* stores the input contours, and eventually + the tessellation itself */ + + /*** state needed for projecting onto the sweep plane ***/ + + double[] normal = new double[3]; /* user-specified normal (if provided) */ + double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */ + double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */ + + /*** state needed for the line sweep ***/ + + private double relTolerance; /* tolerance for merging features */ + int windingRule; /* rule for determining polygon interior */ + boolean fatalError; /* fatal error: needed combine callback */ + + Dict dict; /* edge dictionary for sweep line */ + PriorityQ pq; /* priority queue of vertex events */ + GLUvertex event; /* current sweep event being processed */ + + /*** state needed for rendering callbacks (see render.c) ***/ + + boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */ + boolean boundaryOnly; /* Extract contours, not triangles */ + GLUface lonelyTriList; + /* list of triangles which could not be rendered as strips or fans */ + + + + /*** state needed to cache single-contour polygons for renderCache() */ + + private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */ + int cacheCount; /* number of cached vertices */ + CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */ + + /*** rendering callbacks that also pass polygon data ***/ + private Object polygonData; /* client data for current polygon */ + + private GLUtessellatorCallback callBegin; + private GLUtessellatorCallback callEdgeFlag; + private GLUtessellatorCallback callVertex; + private GLUtessellatorCallback callEnd; +// private GLUtessellatorCallback callMesh; + private GLUtessellatorCallback callError; + private GLUtessellatorCallback callCombine; + + private GLUtessellatorCallback callBeginData; + private GLUtessellatorCallback callEdgeFlagData; + private GLUtessellatorCallback callVertexData; + private GLUtessellatorCallback callEndData; +// private GLUtessellatorCallback callMeshData; + private GLUtessellatorCallback callErrorData; + private GLUtessellatorCallback callCombineData; + + private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0; +// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */ + private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter(); + +// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \ +// MAX(sizeof(GLUvertex),sizeof(GLUface)))) + + public GLUtessellatorImpl() { + state = TessState.T_DORMANT; + + normal[0] = 0; + normal[1] = 0; + normal[2] = 0; + + relTolerance = GLU_TESS_DEFAULT_TOLERANCE; + windingRule = GLU_TESS_WINDING_ODD; + flagBoundary = false; + boundaryOnly = false; + + callBegin = NULL_CB; + callEdgeFlag = NULL_CB; + callVertex = NULL_CB; + callEnd = NULL_CB; + callError = NULL_CB; + callCombine = NULL_CB; +// callMesh = NULL_CB; + + callBeginData = NULL_CB; + callEdgeFlagData = NULL_CB; + callVertexData = NULL_CB; + callEndData = NULL_CB; + callErrorData = NULL_CB; + callCombineData = NULL_CB; + + polygonData = null; + + for (int i = 0; i < cache.length; i++) { + cache[i] = new CachedVertex(); + } + } + + public static GLUtessellator gluNewTess() + { + return new GLUtessellatorImpl(); + } + + + private void makeDormant() { + /* Return the tessellator to its original dormant state. */ + + if (mesh != null) { + Mesh.__gl_meshDeleteMesh(mesh); + } + state = TessState.T_DORMANT; + lastEdge = null; + mesh = null; + } + + private void requireState(int newState) { + if (state != newState) gotoState(newState); + } + + private void gotoState(int newState) { + while (state != newState) { + /* We change the current state one level at a time, to get to + * the desired state. + */ + if (state < newState) { + if (state == TessState.T_DORMANT) { + callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_POLYGON); + gluTessBeginPolygon(null); + } else if (state == TessState.T_IN_POLYGON) { + callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_CONTOUR); + gluTessBeginContour(); + } + } else { + if (state == TessState.T_IN_CONTOUR) { + callErrorOrErrorData(GLU_TESS_MISSING_END_CONTOUR); + gluTessEndContour(); + } else if (state == TessState.T_IN_POLYGON) { + callErrorOrErrorData(GLU_TESS_MISSING_END_POLYGON); + /* gluTessEndPolygon( tess ) is too much work! */ + makeDormant(); + } + } + } + } + + public void gluDeleteTess() { + requireState(TessState.T_DORMANT); + } + + public void gluTessProperty(int which, double value) { + switch (which) { + case GLU_TESS_TOLERANCE: + if (value < 0.0 || value > 1.0) break; + relTolerance = value; + return; + + case GLU_TESS_WINDING_RULE: + int windingRule = (int) value; + if (windingRule != value) break; /* not an integer */ + + switch (windingRule) { + case GLU_TESS_WINDING_ODD: + case GLU_TESS_WINDING_NONZERO: + case GLU_TESS_WINDING_POSITIVE: + case GLU_TESS_WINDING_NEGATIVE: + case GLU_TESS_WINDING_ABS_GEQ_TWO: + this.windingRule = windingRule; + return; + default: + break; + } + + case GLU_TESS_BOUNDARY_ONLY: + boundaryOnly = (value != 0); + return; + + default: + callErrorOrErrorData(GLU_INVALID_ENUM); + return; + } + callErrorOrErrorData(GLU_INVALID_VALUE); + } + +/* Returns tessellator property */ + public void gluGetTessProperty(int which, double[] value, int value_offset) { + switch (which) { + case GLU_TESS_TOLERANCE: +/* tolerance should be in range [0..1] */ + assert (0.0 <= relTolerance && relTolerance <= 1.0); + value[value_offset] = relTolerance; + break; + case GLU_TESS_WINDING_RULE: + assert (windingRule == GLU_TESS_WINDING_ODD || + windingRule == GLU_TESS_WINDING_NONZERO || + windingRule == GLU_TESS_WINDING_POSITIVE || + windingRule == GLU_TESS_WINDING_NEGATIVE || + windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO); + value[value_offset] = windingRule; + break; + case GLU_TESS_BOUNDARY_ONLY: + assert (boundaryOnly == true || boundaryOnly == false); + value[value_offset] = boundaryOnly ? 1 : 0; + break; + default: + value[value_offset] = 0.0; + callErrorOrErrorData(GLU_INVALID_ENUM); + break; + } + } /* gluGetTessProperty() */ + + public void gluTessNormal(double x, double y, double z) { + normal[0] = x; + normal[1] = y; + normal[2] = z; + } + + public void gluTessCallback(int which, GLUtessellatorCallback aCallback) { + switch (which) { + case GLU_TESS_BEGIN: + callBegin = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_BEGIN_DATA: + callBeginData = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_EDGE_FLAG: + callEdgeFlag = aCallback == null ? NULL_CB : aCallback; +/* If the client wants boundary edges to be flagged, + * we render everything as separate triangles (no strips or fans). + */ + flagBoundary = aCallback != null; + return; + case GLU_TESS_EDGE_FLAG_DATA: + callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback; +/* If the client wants boundary edges to be flagged, + * we render everything as separate triangles (no strips or fans). + */ + flagBoundary = (aCallback != null); + return; + case GLU_TESS_VERTEX: + callVertex = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_VERTEX_DATA: + callVertexData = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_END: + callEnd = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_END_DATA: + callEndData = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_ERROR: + callError = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_ERROR_DATA: + callErrorData = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_COMBINE: + callCombine = aCallback == null ? NULL_CB : aCallback; + return; + case GLU_TESS_COMBINE_DATA: + callCombineData = aCallback == null ? NULL_CB : aCallback; + return; +// case GLU_TESS_MESH: +// callMesh = aCallback == null ? NULL_CB : aCallback; +// return; + default: + callErrorOrErrorData(GLU_INVALID_ENUM); + return; + } + } + + private boolean addVertex(double[] coords, Object vertexData) { + GLUhalfEdge e; + + e = lastEdge; + if (e == null) { +/* Make a self-loop (one vertex, one edge). */ + + e = Mesh.__gl_meshMakeEdge(mesh); + if (e == null) return false; + if (!Mesh.__gl_meshSplice(e, e.Sym)) return false; + } else { +/* Create a new vertex and edge which immediately follow e + * in the ordering around the left face. + */ + if (Mesh.__gl_meshSplitEdge(e) == null) return false; + e = e.Lnext; + } + +/* The new vertex is now e.Org. */ + e.Org.data = vertexData; + e.Org.coords[0] = coords[0]; + e.Org.coords[1] = coords[1]; + e.Org.coords[2] = coords[2]; + +/* The winding of an edge says how the winding number changes as we + * cross from the edge''s right face to its left face. We add the + * vertices in such an order that a CCW contour will add +1 to + * the winding number of the region inside the contour. + */ + e.winding = 1; + e.Sym.winding = -1; + + lastEdge = e; + + return true; + } + + private void cacheVertex(double[] coords, Object vertexData) { + if (cache[cacheCount] == null) { + cache[cacheCount] = new CachedVertex(); + } + + CachedVertex v = cache[cacheCount]; + + v.data = vertexData; + v.coords[0] = coords[0]; + v.coords[1] = coords[1]; + v.coords[2] = coords[2]; + ++cacheCount; + } + + + private boolean flushCache() { + CachedVertex[] v = cache; + + mesh = Mesh.__gl_meshNewMesh(); + if (mesh == null) return false; + + for (int i = 0; i < cacheCount; i++) { + CachedVertex vertex = v[i]; + if (!addVertex(vertex.coords, vertex.data)) return false; + } + cacheCount = 0; + flushCacheOnNextVertex = false; + + return true; + } + + public void gluTessVertex(double[] coords, int coords_offset, Object vertexData) { + int i; + boolean tooLarge = false; + double x; + double[] clamped = new double[3]; + + requireState(TessState.T_IN_CONTOUR); + + if (flushCacheOnNextVertex) { + if (!flushCache()) { + callErrorOrErrorData(GLU_OUT_OF_MEMORY); + return; + } + lastEdge = null; + } + for (i = 0; i < 3; ++i) { + x = coords[i+coords_offset]; + if (x < -GLU_TESS_MAX_COORD) { + x = -GLU_TESS_MAX_COORD; + tooLarge = true; + } + if (x > GLU_TESS_MAX_COORD) { + x = GLU_TESS_MAX_COORD; + tooLarge = true; + } + clamped[i] = x; + } + if (tooLarge) { + callErrorOrErrorData(GLU_TESS_COORD_TOO_LARGE); + } + + if (mesh == null) { + if (cacheCount < TESS_MAX_CACHE) { + cacheVertex(clamped, vertexData); + return; + } + if (!flushCache()) { + callErrorOrErrorData(GLU_OUT_OF_MEMORY); + return; + } + } + + if (!addVertex(clamped, vertexData)) { + callErrorOrErrorData(GLU_OUT_OF_MEMORY); + } + } + + + public void gluTessBeginPolygon(Object data) { + requireState(TessState.T_DORMANT); + + state = TessState.T_IN_POLYGON; + cacheCount = 0; + flushCacheOnNextVertex = false; + mesh = null; + + polygonData = data; + } + + + public void gluTessBeginContour() { + requireState(TessState.T_IN_POLYGON); + + state = TessState.T_IN_CONTOUR; + lastEdge = null; + if (cacheCount > 0) { +/* Just set a flag so we don't get confused by empty contours + * -- these can be generated accidentally with the obsolete + * NextContour() interface. + */ + flushCacheOnNextVertex = true; + } + } + + + public void gluTessEndContour() { + requireState(TessState.T_IN_CONTOUR); + state = TessState.T_IN_POLYGON; + } + + public void gluTessEndPolygon() { + GLUmesh mesh; + + try { + requireState(TessState.T_IN_POLYGON); + state = TessState.T_DORMANT; + + if (this.mesh == null) { + if (!flagBoundary /*&& callMesh == NULL_CB*/) { + +/* Try some special code to make the easy cases go quickly + * (eg. convex polygons). This code does NOT handle multiple contours, + * intersections, edge flags, and of course it does not generate + * an explicit mesh either. + */ + if (Render.__gl_renderCache(this)) { + polygonData = null; + return; + } + } + if (!flushCache()) throw new RuntimeException(); /* could've used a label*/ + } + +/* Determine the polygon normal and project vertices onto the plane + * of the polygon. + */ + Normal.__gl_projectPolygon(this); + +/* __gl_computeInterior( tess ) computes the planar arrangement specified + * by the given contours, and further subdivides this arrangement + * into regions. Each region is marked "inside" if it belongs + * to the polygon, according to the rule given by windingRule. + * Each interior region is guaranteed be monotone. + */ + if (!Sweep.__gl_computeInterior(this)) { + throw new RuntimeException(); /* could've used a label */ + } + + mesh = this.mesh; + if (!fatalError) { + boolean rc = true; + +/* If the user wants only the boundary contours, we throw away all edges + * except those which separate the interior from the exterior. + * Otherwise we tessellate all the regions marked "inside". + */ + if (boundaryOnly) { + rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true); + } else { + rc = TessMono.__gl_meshTessellateInterior(mesh); + } + if (!rc) throw new RuntimeException(); /* could've used a label */ + + Mesh.__gl_meshCheckMesh(mesh); + + if (callBegin != NULL_CB || callEnd != NULL_CB + || callVertex != NULL_CB || callEdgeFlag != NULL_CB + || callBeginData != NULL_CB + || callEndData != NULL_CB + || callVertexData != NULL_CB + || callEdgeFlagData != NULL_CB) { + if (boundaryOnly) { + Render.__gl_renderBoundary(this, mesh); /* output boundary contours */ + } else { + Render.__gl_renderMesh(this, mesh); /* output strips and fans */ + } + } +// if (callMesh != NULL_CB) { +// +///* Throw away the exterior faces, so that all faces are interior. +// * This way the user doesn't have to check the "inside" flag, +// * and we don't need to even reveal its existence. It also leaves +// * the freedom for an implementation to not generate the exterior +// * faces in the first place. +// */ +// TessMono.__gl_meshDiscardExterior(mesh); +// callMesh.mesh(mesh); /* user wants the mesh itself */ +// mesh = null; +// polygonData = null; +// return; +// } + } + Mesh.__gl_meshDeleteMesh(mesh); + polygonData = null; + mesh = null; + } catch (Exception e) { + e.printStackTrace(); + callErrorOrErrorData(GLU_OUT_OF_MEMORY); + } + } + + /*******************************************************/ + +/* Obsolete calls -- for backward compatibility */ + + public void gluBeginPolygon() { + gluTessBeginPolygon(null); + gluTessBeginContour(); + } + + +/*ARGSUSED*/ + public void gluNextContour(int type) { + gluTessEndContour(); + gluTessBeginContour(); + } + + + public void gluEndPolygon() { + gluTessEndContour(); + gluTessEndPolygon(); + } + + void callBeginOrBeginData(int a) { + if (callBeginData != NULL_CB) + callBeginData.beginData(a, polygonData); + else + callBegin.begin(a); + } + + void callVertexOrVertexData(Object a) { + if (callVertexData != NULL_CB) + callVertexData.vertexData(a, polygonData); + else + callVertex.vertex(a); + } + + void callEdgeFlagOrEdgeFlagData(boolean a) { + if (callEdgeFlagData != NULL_CB) + callEdgeFlagData.edgeFlagData(a, polygonData); + else + callEdgeFlag.edgeFlag(a); + } + + void callEndOrEndData() { + if (callEndData != NULL_CB) + callEndData.endData(polygonData); + else + callEnd.end(); + } + + void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) { + if (callCombineData != NULL_CB) + callCombineData.combineData(coords, vertexData, weights, outData, polygonData); + else + callCombine.combine(coords, vertexData, weights, outData); + } + + void callErrorOrErrorData(int a) { + if (callErrorData != NULL_CB) + callErrorData.errorData(a, polygonData); + else + callError.error(a); + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/GLUvertex.java b/src/main/java/org/lwjglx/util/glu/tessellation/GLUvertex.java new file mode 100644 index 0000000..9f630fc --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/GLUvertex.java @@ -0,0 +1,97 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class GLUvertex { + public GLUvertex next; /* next vertex (never NULL) */ + public GLUvertex prev; /* previous vertex (never NULL) */ + public GLUhalfEdge anEdge; /* a half-edge with this origin */ + public Object data; /* client's data */ + + /* Internal data (keep hidden) */ + public double[] coords = new double[3]; /* vertex location in 3D */ + public double s, t; /* projection onto the sweep plane */ + public int pqHandle; /* to allow deletion from priority queue */ +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Geom.java b/src/main/java/org/lwjglx/util/glu/tessellation/Geom.java new file mode 100644 index 0000000..e9cde2a --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Geom.java @@ -0,0 +1,350 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class Geom { + private Geom() { + } + + /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), + * evaluates the t-coord of the edge uw at the s-coord of the vertex v. + * Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. + * If uw is vertical (and thus passes thru v), the result is zero. + * + * The calculation is extremely accurate and stable, even when v + * is very close to u or w. In particular if we set v->t = 0 and + * let r be the negated result (this evaluates (uw)(v->s)), then + * r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). + */ + static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) { + double gapL, gapR; + + assert (VertLeq(u, v) && VertLeq(v, w)); + + gapL = v.s - u.s; + gapR = w.s - v.s; + + if (gapL + gapR > 0) { + if (gapL < gapR) { + return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR)); + } else { + return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR)); + } + } + /* vertical line */ + return 0; + } + + static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) { + double gapL, gapR; + + assert (VertLeq(u, v) && VertLeq(v, w)); + + gapL = v.s - u.s; + gapR = w.s - v.s; + + if (gapL + gapR > 0) { + return (v.t - w.t) * gapL + (v.t - u.t) * gapR; + } + /* vertical line */ + return 0; + } + + + /*********************************************************************** + * Define versions of EdgeSign, EdgeEval with s and t transposed. + */ + + static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) { + /* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w), + * evaluates the t-coord of the edge uw at the s-coord of the vertex v. + * Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. + * If uw is vertical (and thus passes thru v), the result is zero. + * + * The calculation is extremely accurate and stable, even when v + * is very close to u or w. In particular if we set v->s = 0 and + * let r be the negated result (this evaluates (uw)(v->t)), then + * r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s). + */ + double gapL, gapR; + + assert (TransLeq(u, v) && TransLeq(v, w)); + + gapL = v.t - u.t; + gapR = w.t - v.t; + + if (gapL + gapR > 0) { + if (gapL < gapR) { + return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR)); + } else { + return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR)); + } + } + /* vertical line */ + return 0; + } + + static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) { + /* Returns a number whose sign matches TransEval(u,v,w) but which + * is cheaper to evaluate. Returns > 0, == 0 , or < 0 + * as v is above, on, or below the edge uw. + */ + double gapL, gapR; + + assert (TransLeq(u, v) && TransLeq(v, w)); + + gapL = v.t - u.t; + gapR = w.t - v.t; + + if (gapL + gapR > 0) { + return (v.s - w.s) * gapL + (v.s - u.s) * gapR; + } + /* vertical line */ + return 0; + } + + + static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) { + /* For almost-degenerate situations, the results are not reliable. + * Unless the floating-point arithmetic can be performed without + * rounding errors, *any* implementation will give incorrect results + * on some degenerate inputs, so the client must have some way to + * handle this situation. + */ + return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0; + } + +/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), + * or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces + * this in the rare case that one argument is slightly negative. + * The implementation is extremely stable numerically. + * In particular it guarantees that the result r satisfies + * MIN(x,y) <= r <= MAX(x,y), and the results are very accurate + * even when a and b differ greatly in magnitude. + */ + static double Interpolate(double a, double x, double b, double y) { + a = (a < 0) ? 0 : a; + b = (b < 0) ? 0 : b; + if (a <= b) { + if (b == 0) { + return (x + y) / 2.0; + } else { + return (x + (y - x) * (a / (a + b))); + } + } else { + return (y + (x - y) * (b / (a + b))); + } + } + + static void EdgeIntersect(GLUvertex o1, GLUvertex d1, + GLUvertex o2, GLUvertex d2, + GLUvertex v) +/* Given edges (o1,d1) and (o2,d2), compute their point of intersection. + * The computed point is guaranteed to lie in the intersection of the + * bounding rectangles defined by each edge. + */ { + double z1, z2; + + /* This is certainly not the most efficient way to find the intersection + * of two line segments, but it is very numerically stable. + * + * Strategy: find the two middle vertices in the VertLeq ordering, + * and interpolate the intersection s-value from these. Then repeat + * using the TransLeq ordering to find the intersection t-value. + */ + + if (!VertLeq(o1, d1)) { + GLUvertex temp = o1; + o1 = d1; + d1 = temp; + } + if (!VertLeq(o2, d2)) { + GLUvertex temp = o2; + o2 = d2; + d2 = temp; + } + if (!VertLeq(o1, o2)) { + GLUvertex temp = o1; + o1 = o2; + o2 = temp; + temp = d1; + d1 = d2; + d2 = temp; + } + + if (!VertLeq(o2, d1)) { + /* Technically, no intersection -- do our best */ + v.s = (o2.s + d1.s) / 2.0; + } else if (VertLeq(d1, d2)) { + /* Interpolate between o2 and d1 */ + z1 = EdgeEval(o1, o2, d1); + z2 = EdgeEval(o2, d1, d2); + if (z1 + z2 < 0) { + z1 = -z1; + z2 = -z2; + } + v.s = Interpolate(z1, o2.s, z2, d1.s); + } else { + /* Interpolate between o2 and d2 */ + z1 = EdgeSign(o1, o2, d1); + z2 = -EdgeSign(o1, d2, d1); + if (z1 + z2 < 0) { + z1 = -z1; + z2 = -z2; + } + v.s = Interpolate(z1, o2.s, z2, d2.s); + } + + /* Now repeat the process for t */ + + if (!TransLeq(o1, d1)) { + GLUvertex temp = o1; + o1 = d1; + d1 = temp; + } + if (!TransLeq(o2, d2)) { + GLUvertex temp = o2; + o2 = d2; + d2 = temp; + } + if (!TransLeq(o1, o2)) { + GLUvertex temp = o2; + o2 = o1; + o1 = temp; + temp = d2; + d2 = d1; + d1 = temp; + } + + if (!TransLeq(o2, d1)) { + /* Technically, no intersection -- do our best */ + v.t = (o2.t + d1.t) / 2.0; + } else if (TransLeq(d1, d2)) { + /* Interpolate between o2 and d1 */ + z1 = TransEval(o1, o2, d1); + z2 = TransEval(o2, d1, d2); + if (z1 + z2 < 0) { + z1 = -z1; + z2 = -z2; + } + v.t = Interpolate(z1, o2.t, z2, d1.t); + } else { + /* Interpolate between o2 and d2 */ + z1 = TransSign(o1, o2, d1); + z2 = -TransSign(o1, d2, d1); + if (z1 + z2 < 0) { + z1 = -z1; + z2 = -z2; + } + v.t = Interpolate(z1, o2.t, z2, d2.t); + } + } + + static boolean VertEq(GLUvertex u, GLUvertex v) { + return u.s == v.s && u.t == v.t; + } + + static boolean VertLeq(GLUvertex u, GLUvertex v) { + return u.s < v.s || (u.s == v.s && u.t <= v.t); + } + +/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */ + + static boolean TransLeq(GLUvertex u, GLUvertex v) { + return u.t < v.t || (u.t == v.t && u.s <= v.s); + } + + static boolean EdgeGoesLeft(GLUhalfEdge e) { + return VertLeq(e.Sym.Org, e.Org); + } + + static boolean EdgeGoesRight(GLUhalfEdge e) { + return VertLeq(e.Org, e.Sym.Org); + } + + static double VertL1dist(GLUvertex u, GLUvertex v) { + return Math.abs(u.s - v.s) + Math.abs(u.t - v.t); + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Mesh.java b/src/main/java/org/lwjglx/util/glu/tessellation/Mesh.java new file mode 100644 index 0000000..7f36517 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Mesh.java @@ -0,0 +1,766 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class Mesh { + private Mesh() { + } + + /************************ Utility Routines ************************/ +/* MakeEdge creates a new pair of half-edges which form their own loop. + * No vertex or face structures are allocated, but these must be assigned + * before the current edge operation is completed. + */ + static GLUhalfEdge MakeEdge(GLUhalfEdge eNext) { + GLUhalfEdge e; + GLUhalfEdge eSym; + GLUhalfEdge ePrev; + +// EdgePair * pair = (EdgePair *) +// memAlloc(sizeof(EdgePair)); +// if (pair == NULL) return NULL; +// +// e = &pair - > e; + e = new GLUhalfEdge(true); +// eSym = &pair - > eSym; + eSym = new GLUhalfEdge(false); + + + /* Make sure eNext points to the first edge of the edge pair */ + if (!eNext.first) { + eNext = eNext.Sym; + } + + /* Insert in circular doubly-linked list before eNext. + * Note that the prev pointer is stored in Sym->next. + */ + ePrev = eNext.Sym.next; + eSym.next = ePrev; + ePrev.Sym.next = e; + e.next = eNext; + eNext.Sym.next = eSym; + + e.Sym = eSym; + e.Onext = e; + e.Lnext = eSym; + e.Org = null; + e.Lface = null; + e.winding = 0; + e.activeRegion = null; + + eSym.Sym = e; + eSym.Onext = eSym; + eSym.Lnext = e; + eSym.Org = null; + eSym.Lface = null; + eSym.winding = 0; + eSym.activeRegion = null; + + return e; + } + +/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the + * CS348a notes (see mesh.h). Basically it modifies the mesh so that + * a->Onext and b->Onext are exchanged. This can have various effects + * depending on whether a and b belong to different face or vertex rings. + * For more explanation see __gl_meshSplice() below. + */ + static void Splice(GLUhalfEdge a, GLUhalfEdge b) { + GLUhalfEdge aOnext = a.Onext; + GLUhalfEdge bOnext = b.Onext; + + aOnext.Sym.Lnext = b; + bOnext.Sym.Lnext = a; + a.Onext = bOnext; + b.Onext = aOnext; + } + +/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the + * origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives + * a place to insert the new vertex in the global vertex list. We insert + * the new vertex *before* vNext so that algorithms which walk the vertex + * list will not see the newly created vertices. + */ + static void MakeVertex(GLUvertex newVertex, + GLUhalfEdge eOrig, GLUvertex vNext) { + GLUhalfEdge e; + GLUvertex vPrev; + GLUvertex vNew = newVertex; + + assert (vNew != null); + + /* insert in circular doubly-linked list before vNext */ + vPrev = vNext.prev; + vNew.prev = vPrev; + vPrev.next = vNew; + vNew.next = vNext; + vNext.prev = vNew; + + vNew.anEdge = eOrig; + vNew.data = null; + /* leave coords, s, t undefined */ + + /* fix other edges on this vertex loop */ + e = eOrig; + do { + e.Org = vNew; + e = e.Onext; + } while (e != eOrig); + } + +/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left + * face of all edges in the face loop to which eOrig belongs. "fNext" gives + * a place to insert the new face in the global face list. We insert + * the new face *before* fNext so that algorithms which walk the face + * list will not see the newly created faces. + */ + static void MakeFace(GLUface newFace, GLUhalfEdge eOrig, GLUface fNext) { + GLUhalfEdge e; + GLUface fPrev; + GLUface fNew = newFace; + + assert (fNew != null); + + /* insert in circular doubly-linked list before fNext */ + fPrev = fNext.prev; + fNew.prev = fPrev; + fPrev.next = fNew; + fNew.next = fNext; + fNext.prev = fNew; + + fNew.anEdge = eOrig; + fNew.data = null; + fNew.trail = null; + fNew.marked = false; + + /* The new face is marked "inside" if the old one was. This is a + * convenience for the common case where a face has been split in two. + */ + fNew.inside = fNext.inside; + + /* fix other edges on this face loop */ + e = eOrig; + do { + e.Lface = fNew; + e = e.Lnext; + } while (e != eOrig); + } + +/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym), + * and removes from the global edge list. + */ + static void KillEdge(GLUhalfEdge eDel) { + GLUhalfEdge ePrev, eNext; + + /* Half-edges are allocated in pairs, see EdgePair above */ + if (!eDel.first) { + eDel = eDel.Sym; + } + + /* delete from circular doubly-linked list */ + eNext = eDel.next; + ePrev = eDel.Sym.next; + eNext.Sym.next = ePrev; + ePrev.Sym.next = eNext; + } + + +/* KillVertex( vDel ) destroys a vertex and removes it from the global + * vertex list. It updates the vertex loop to point to a given new vertex. + */ + static void KillVertex(GLUvertex vDel, GLUvertex newOrg) { + GLUhalfEdge e, eStart = vDel.anEdge; + GLUvertex vPrev, vNext; + + /* change the origin of all affected edges */ + e = eStart; + do { + e.Org = newOrg; + e = e.Onext; + } while (e != eStart); + + /* delete from circular doubly-linked list */ + vPrev = vDel.prev; + vNext = vDel.next; + vNext.prev = vPrev; + vPrev.next = vNext; + } + +/* KillFace( fDel ) destroys a face and removes it from the global face + * list. It updates the face loop to point to a given new face. + */ + static void KillFace(GLUface fDel, GLUface newLface) { + GLUhalfEdge e, eStart = fDel.anEdge; + GLUface fPrev, fNext; + + /* change the left face of all affected edges */ + e = eStart; + do { + e.Lface = newLface; + e = e.Lnext; + } while (e != eStart); + + /* delete from circular doubly-linked list */ + fPrev = fDel.prev; + fNext = fDel.next; + fNext.prev = fPrev; + fPrev.next = fNext; + } + + + /****************** Basic Edge Operations **********************/ + +/* __gl_meshMakeEdge creates one edge, two vertices, and a loop (face). + * The loop consists of the two new half-edges. + */ + public static GLUhalfEdge __gl_meshMakeEdge(GLUmesh mesh) { + GLUvertex newVertex1 = new GLUvertex(); + GLUvertex newVertex2 = new GLUvertex(); + GLUface newFace = new GLUface(); + GLUhalfEdge e; + + e = MakeEdge(mesh.eHead); + if (e == null) return null; + + MakeVertex(newVertex1, e, mesh.vHead); + MakeVertex(newVertex2, e.Sym, mesh.vHead); + MakeFace(newFace, e, mesh.fHead); + return e; + } + + +/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the + * mesh connectivity and topology. It changes the mesh so that + * eOrg->Onext <- OLD( eDst->Onext ) + * eDst->Onext <- OLD( eOrg->Onext ) + * where OLD(...) means the value before the meshSplice operation. + * + * This can have two effects on the vertex structure: + * - if eOrg->Org != eDst->Org, the two vertices are merged together + * - if eOrg->Org == eDst->Org, the origin is split into two vertices + * In both cases, eDst->Org is changed and eOrg->Org is untouched. + * + * Similarly (and independently) for the face structure, + * - if eOrg->Lface == eDst->Lface, one loop is split into two + * - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one + * In both cases, eDst->Lface is changed and eOrg->Lface is unaffected. + * + * Some special cases: + * If eDst == eOrg, the operation has no effect. + * If eDst == eOrg->Lnext, the new face will have a single edge. + * If eDst == eOrg->Lprev, the old face will have a single edge. + * If eDst == eOrg->Onext, the new vertex will have a single edge. + * If eDst == eOrg->Oprev, the old vertex will have a single edge. + */ + public static boolean __gl_meshSplice(GLUhalfEdge eOrg, GLUhalfEdge eDst) { + boolean joiningLoops = false; + boolean joiningVertices = false; + + if (eOrg == eDst) return true; + + if (eDst.Org != eOrg.Org) { + /* We are merging two disjoint vertices -- destroy eDst->Org */ + joiningVertices = true; + KillVertex(eDst.Org, eOrg.Org); + } + if (eDst.Lface != eOrg.Lface) { + /* We are connecting two disjoint loops -- destroy eDst.Lface */ + joiningLoops = true; + KillFace(eDst.Lface, eOrg.Lface); + } + + /* Change the edge structure */ + Splice(eDst, eOrg); + + if (!joiningVertices) { + GLUvertex newVertex = new GLUvertex(); + + /* We split one vertex into two -- the new vertex is eDst.Org. + * Make sure the old vertex points to a valid half-edge. + */ + MakeVertex(newVertex, eDst, eOrg.Org); + eOrg.Org.anEdge = eOrg; + } + if (!joiningLoops) { + GLUface newFace = new GLUface(); + + /* We split one loop into two -- the new loop is eDst.Lface. + * Make sure the old face points to a valid half-edge. + */ + MakeFace(newFace, eDst, eOrg.Lface); + eOrg.Lface.anEdge = eOrg; + } + + return true; + } + + +/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases: + * if (eDel.Lface != eDel.Rface), we join two loops into one; the loop + * eDel.Lface is deleted. Otherwise, we are splitting one loop into two; + * the newly created loop will contain eDel.Dst. If the deletion of eDel + * would create isolated vertices, those are deleted as well. + * + * This function could be implemented as two calls to __gl_meshSplice + * plus a few calls to memFree, but this would allocate and delete + * unnecessary vertices and faces. + */ + static boolean __gl_meshDelete(GLUhalfEdge eDel) { + GLUhalfEdge eDelSym = eDel.Sym; + boolean joiningLoops = false; + + /* First step: disconnect the origin vertex eDel.Org. We make all + * changes to get a consistent mesh in this "intermediate" state. + */ + if (eDel.Lface != eDel.Sym.Lface) { + /* We are joining two loops into one -- remove the left face */ + joiningLoops = true; + KillFace(eDel.Lface, eDel.Sym.Lface); + } + + if (eDel.Onext == eDel) { + KillVertex(eDel.Org, null); + } else { + /* Make sure that eDel.Org and eDel.Sym.Lface point to valid half-edges */ + eDel.Sym.Lface.anEdge = eDel.Sym.Lnext; + eDel.Org.anEdge = eDel.Onext; + + Splice(eDel, eDel.Sym.Lnext); + if (!joiningLoops) { + GLUface newFace = new GLUface(); + + /* We are splitting one loop into two -- create a new loop for eDel. */ + MakeFace(newFace, eDel, eDel.Lface); + } + } + + /* Claim: the mesh is now in a consistent state, except that eDel.Org + * may have been deleted. Now we disconnect eDel.Dst. + */ + if (eDelSym.Onext == eDelSym) { + KillVertex(eDelSym.Org, null); + KillFace(eDelSym.Lface, null); + } else { + /* Make sure that eDel.Dst and eDel.Lface point to valid half-edges */ + eDel.Lface.anEdge = eDelSym.Sym.Lnext; + eDelSym.Org.anEdge = eDelSym.Onext; + Splice(eDelSym, eDelSym.Sym.Lnext); + } + + /* Any isolated vertices or faces have already been freed. */ + KillEdge(eDel); + + return true; + } + + + /******************** Other Edge Operations **********************/ + +/* All these routines can be implemented with the basic edge + * operations above. They are provided for convenience and efficiency. + */ + + +/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that + * eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex. + * eOrg and eNew will have the same left face. + */ + static GLUhalfEdge __gl_meshAddEdgeVertex(GLUhalfEdge eOrg) { + GLUhalfEdge eNewSym; + GLUhalfEdge eNew = MakeEdge(eOrg); + + eNewSym = eNew.Sym; + + /* Connect the new edge appropriately */ + Splice(eNew, eOrg.Lnext); + + /* Set the vertex and face information */ + eNew.Org = eOrg.Sym.Org; + { + GLUvertex newVertex = new GLUvertex(); + + MakeVertex(newVertex, eNewSym, eNew.Org); + } + eNew.Lface = eNewSym.Lface = eOrg.Lface; + + return eNew; + } + + +/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew, + * such that eNew == eOrg.Lnext. The new vertex is eOrg.Sym.Org == eNew.Org. + * eOrg and eNew will have the same left face. + */ + public static GLUhalfEdge __gl_meshSplitEdge(GLUhalfEdge eOrg) { + GLUhalfEdge eNew; + GLUhalfEdge tempHalfEdge = __gl_meshAddEdgeVertex(eOrg); + + eNew = tempHalfEdge.Sym; + + /* Disconnect eOrg from eOrg.Sym.Org and connect it to eNew.Org */ + Splice(eOrg.Sym, eOrg.Sym.Sym.Lnext); + Splice(eOrg.Sym, eNew); + + /* Set the vertex and face information */ + eOrg.Sym.Org = eNew.Org; + eNew.Sym.Org.anEdge = eNew.Sym; /* may have pointed to eOrg.Sym */ + eNew.Sym.Lface = eOrg.Sym.Lface; + eNew.winding = eOrg.winding; /* copy old winding information */ + eNew.Sym.winding = eOrg.Sym.winding; + + return eNew; + } + + +/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Sym.Org + * to eDst.Org, and returns the corresponding half-edge eNew. + * If eOrg.Lface == eDst.Lface, this splits one loop into two, + * and the newly created loop is eNew.Lface. Otherwise, two disjoint + * loops are merged into one, and the loop eDst.Lface is destroyed. + * + * If (eOrg == eDst), the new face will have only two edges. + * If (eOrg.Lnext == eDst), the old face is reduced to a single edge. + * If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges. + */ + static GLUhalfEdge __gl_meshConnect(GLUhalfEdge eOrg, GLUhalfEdge eDst) { + GLUhalfEdge eNewSym; + boolean joiningLoops = false; + GLUhalfEdge eNew = MakeEdge(eOrg); + + eNewSym = eNew.Sym; + + if (eDst.Lface != eOrg.Lface) { + /* We are connecting two disjoint loops -- destroy eDst.Lface */ + joiningLoops = true; + KillFace(eDst.Lface, eOrg.Lface); + } + + /* Connect the new edge appropriately */ + Splice(eNew, eOrg.Lnext); + Splice(eNewSym, eDst); + + /* Set the vertex and face information */ + eNew.Org = eOrg.Sym.Org; + eNewSym.Org = eDst.Org; + eNew.Lface = eNewSym.Lface = eOrg.Lface; + + /* Make sure the old face points to a valid half-edge */ + eOrg.Lface.anEdge = eNewSym; + + if (!joiningLoops) { + GLUface newFace = new GLUface(); + + /* We split one loop into two -- the new loop is eNew.Lface */ + MakeFace(newFace, eNew, eOrg.Lface); + } + return eNew; + } + + + /******************** Other Operations **********************/ + +/* __gl_meshZapFace( fZap ) destroys a face and removes it from the + * global face list. All edges of fZap will have a null pointer as their + * left face. Any edges which also have a null pointer as their right face + * are deleted entirely (along with any isolated vertices this produces). + * An entire mesh can be deleted by zapping its faces, one at a time, + * in any order. Zapped faces cannot be used in further mesh operations! + */ + static void __gl_meshZapFace(GLUface fZap) { + GLUhalfEdge eStart = fZap.anEdge; + GLUhalfEdge e, eNext, eSym; + GLUface fPrev, fNext; + + /* walk around face, deleting edges whose right face is also null */ + eNext = eStart.Lnext; + do { + e = eNext; + eNext = e.Lnext; + + e.Lface = null; + if (e.Sym.Lface == null) { + /* delete the edge -- see __gl_MeshDelete above */ + + if (e.Onext == e) { + KillVertex(e.Org, null); + } else { + /* Make sure that e.Org points to a valid half-edge */ + e.Org.anEdge = e.Onext; + Splice(e, e.Sym.Lnext); + } + eSym = e.Sym; + if (eSym.Onext == eSym) { + KillVertex(eSym.Org, null); + } else { + /* Make sure that eSym.Org points to a valid half-edge */ + eSym.Org.anEdge = eSym.Onext; + Splice(eSym, eSym.Sym.Lnext); + } + KillEdge(e); + } + } while (e != eStart); + + /* delete from circular doubly-linked list */ + fPrev = fZap.prev; + fNext = fZap.next; + fNext.prev = fPrev; + fPrev.next = fNext; + } + + +/* __gl_meshNewMesh() creates a new mesh with no edges, no vertices, + * and no loops (what we usually call a "face"). + */ + public static GLUmesh __gl_meshNewMesh() { + GLUvertex v; + GLUface f; + GLUhalfEdge e; + GLUhalfEdge eSym; + GLUmesh mesh = new GLUmesh(); + + v = mesh.vHead; + f = mesh.fHead; + e = mesh.eHead; + eSym = mesh.eHeadSym; + + v.next = v.prev = v; + v.anEdge = null; + v.data = null; + + f.next = f.prev = f; + f.anEdge = null; + f.data = null; + f.trail = null; + f.marked = false; + f.inside = false; + + e.next = e; + e.Sym = eSym; + e.Onext = null; + e.Lnext = null; + e.Org = null; + e.Lface = null; + e.winding = 0; + e.activeRegion = null; + + eSym.next = eSym; + eSym.Sym = e; + eSym.Onext = null; + eSym.Lnext = null; + eSym.Org = null; + eSym.Lface = null; + eSym.winding = 0; + eSym.activeRegion = null; + + return mesh; + } + + +/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in + * both meshes, and returns the new mesh (the old meshes are destroyed). + */ + static GLUmesh __gl_meshUnion(GLUmesh mesh1, GLUmesh mesh2) { + GLUface f1 = mesh1.fHead; + GLUvertex v1 = mesh1.vHead; + GLUhalfEdge e1 = mesh1.eHead; + GLUface f2 = mesh2.fHead; + GLUvertex v2 = mesh2.vHead; + GLUhalfEdge e2 = mesh2.eHead; + + /* Add the faces, vertices, and edges of mesh2 to those of mesh1 */ + if (f2.next != f2) { + f1.prev.next = f2.next; + f2.next.prev = f1.prev; + f2.prev.next = f1; + f1.prev = f2.prev; + } + + if (v2.next != v2) { + v1.prev.next = v2.next; + v2.next.prev = v1.prev; + v2.prev.next = v1; + v1.prev = v2.prev; + } + + if (e2.next != e2) { + e1.Sym.next.Sym.next = e2.next; + e2.next.Sym.next = e1.Sym.next; + e2.Sym.next.Sym.next = e1; + e1.Sym.next = e2.Sym.next; + } + + return mesh1; + } + + +/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh. + */ + static void __gl_meshDeleteMeshZap(GLUmesh mesh) { + GLUface fHead = mesh.fHead; + + while (fHead.next != fHead) { + __gl_meshZapFace(fHead.next); + } + assert (mesh.vHead.next == mesh.vHead); + } + +/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh. + */ + public static void __gl_meshDeleteMesh(GLUmesh mesh) { + GLUface f, fNext; + GLUvertex v, vNext; + GLUhalfEdge e, eNext; + + for (f = mesh.fHead.next; f != mesh.fHead; f = fNext) { + fNext = f.next; + } + + for (v = mesh.vHead.next; v != mesh.vHead; v = vNext) { + vNext = v.next; + } + + for (e = mesh.eHead.next; e != mesh.eHead; e = eNext) { + /* One call frees both e and e.Sym (see EdgePair above) */ + eNext = e.next; + } + } + +/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency. + */ + public static void __gl_meshCheckMesh(GLUmesh mesh) { + GLUface fHead = mesh.fHead; + GLUvertex vHead = mesh.vHead; + GLUhalfEdge eHead = mesh.eHead; + GLUface f, fPrev; + GLUvertex v, vPrev; + GLUhalfEdge e, ePrev; + + fPrev = fHead; + for (fPrev = fHead; (f = fPrev.next) != fHead; fPrev = f) { + assert (f.prev == fPrev); + e = f.anEdge; + do { + assert (e.Sym != e); + assert (e.Sym.Sym == e); + assert (e.Lnext.Onext.Sym == e); + assert (e.Onext.Sym.Lnext == e); + assert (e.Lface == f); + e = e.Lnext; + } while (e != f.anEdge); + } + assert (f.prev == fPrev && f.anEdge == null && f.data == null); + + vPrev = vHead; + for (vPrev = vHead; (v = vPrev.next) != vHead; vPrev = v) { + assert (v.prev == vPrev); + e = v.anEdge; + do { + assert (e.Sym != e); + assert (e.Sym.Sym == e); + assert (e.Lnext.Onext.Sym == e); + assert (e.Onext.Sym.Lnext == e); + assert (e.Org == v); + e = e.Onext; + } while (e != v.anEdge); + } + assert (v.prev == vPrev && v.anEdge == null && v.data == null); + + ePrev = eHead; + for (ePrev = eHead; (e = ePrev.next) != eHead; ePrev = e) { + assert (e.Sym.next == ePrev.Sym); + assert (e.Sym != e); + assert (e.Sym.Sym == e); + assert (e.Org != null); + assert (e.Sym.Org != null); + assert (e.Lnext.Onext.Sym == e); + assert (e.Onext.Sym.Lnext == e); + } + assert (e.Sym.next == ePrev.Sym + && e.Sym == mesh.eHeadSym + && e.Sym.Sym == e + && e.Org == null && e.Sym.Org == null + && e.Lface == null && e.Sym.Lface == null); + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Normal.java b/src/main/java/org/lwjglx/util/glu/tessellation/Normal.java new file mode 100644 index 0000000..eb51916 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Normal.java @@ -0,0 +1,319 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +import org.lwjglx.util.glu.GLU; + +class Normal { + private Normal() { + } + + static boolean SLANTED_SWEEP; + static double S_UNIT_X; /* Pre-normalized */ + static double S_UNIT_Y; + private static final boolean TRUE_PROJECT = false; + + static { + if (SLANTED_SWEEP) { +/* The "feature merging" is not intended to be complete. There are + * special cases where edges are nearly parallel to the sweep line + * which are not implemented. The algorithm should still behave + * robustly (ie. produce a reasonable tesselation) in the presence + * of such edges, however it may miss features which could have been + * merged. We could minimize this effect by choosing the sweep line + * direction to be something unusual (ie. not parallel to one of the + * coordinate axes). + */ + S_UNIT_X = 0.50941539564955385; /* Pre-normalized */ + S_UNIT_Y = 0.86052074622010633; + } else { + S_UNIT_X = 1.0; + S_UNIT_Y = 0.0; + } + } + + private static double Dot(double[] u, double[] v) { + return (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]); + } + + static void Normalize(double[] v) { + double len = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; + + assert (len > 0); + len = Math.sqrt(len); + v[0] /= len; + v[1] /= len; + v[2] /= len; + } + + static int LongAxis(double[] v) { + int i = 0; + + if (Math.abs(v[1]) > Math.abs(v[0])) { + i = 1; + } + if (Math.abs(v[2]) > Math.abs(v[i])) { + i = 2; + } + return i; + } + + static void ComputeNormal(GLUtessellatorImpl tess, double[] norm) { + GLUvertex v, v1, v2; + double c, tLen2, maxLen2; + double[] maxVal, minVal, d1, d2, tNorm; + GLUvertex[] maxVert, minVert; + GLUvertex vHead = tess.mesh.vHead; + int i; + + maxVal = new double[3]; + minVal = new double[3]; + minVert = new GLUvertex[3]; + maxVert = new GLUvertex[3]; + d1 = new double[3]; + d2 = new double[3]; + tNorm = new double[3]; + + maxVal[0] = maxVal[1] = maxVal[2] = -2 * GLU.TESS_MAX_COORD; + minVal[0] = minVal[1] = minVal[2] = 2 * GLU.TESS_MAX_COORD; + + for (v = vHead.next; v != vHead; v = v.next) { + for (i = 0; i < 3; ++i) { + c = v.coords[i]; + if (c < minVal[i]) { + minVal[i] = c; + minVert[i] = v; + } + if (c > maxVal[i]) { + maxVal[i] = c; + maxVert[i] = v; + } + } + } + +/* Find two vertices separated by at least 1/sqrt(3) of the maximum + * distance between any two vertices + */ + i = 0; + if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0]) { + i = 1; + } + if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i]) { + i = 2; + } + if (minVal[i] >= maxVal[i]) { +/* All vertices are the same -- normal doesn't matter */ + norm[0] = 0; + norm[1] = 0; + norm[2] = 1; + return; + } + +/* Look for a third vertex which forms the triangle with maximum area + * (Length of normal == twice the triangle area) + */ + maxLen2 = 0; + v1 = minVert[i]; + v2 = maxVert[i]; + d1[0] = v1.coords[0] - v2.coords[0]; + d1[1] = v1.coords[1] - v2.coords[1]; + d1[2] = v1.coords[2] - v2.coords[2]; + for (v = vHead.next; v != vHead; v = v.next) { + d2[0] = v.coords[0] - v2.coords[0]; + d2[1] = v.coords[1] - v2.coords[1]; + d2[2] = v.coords[2] - v2.coords[2]; + tNorm[0] = d1[1] * d2[2] - d1[2] * d2[1]; + tNorm[1] = d1[2] * d2[0] - d1[0] * d2[2]; + tNorm[2] = d1[0] * d2[1] - d1[1] * d2[0]; + tLen2 = tNorm[0] * tNorm[0] + tNorm[1] * tNorm[1] + tNorm[2] * tNorm[2]; + if (tLen2 > maxLen2) { + maxLen2 = tLen2; + norm[0] = tNorm[0]; + norm[1] = tNorm[1]; + norm[2] = tNorm[2]; + } + } + + if (maxLen2 <= 0) { +/* All points lie on a single line -- any decent normal will do */ + norm[0] = norm[1] = norm[2] = 0; + norm[LongAxis(d1)] = 1; + } + } + + static void CheckOrientation(GLUtessellatorImpl tess) { + double area; + GLUface f, fHead = tess.mesh.fHead; + GLUvertex v, vHead = tess.mesh.vHead; + GLUhalfEdge e; + +/* When we compute the normal automatically, we choose the orientation + * so that the the sum of the signed areas of all contours is non-negative. + */ + area = 0; + for (f = fHead.next; f != fHead; f = f.next) { + e = f.anEdge; + if (e.winding <= 0) continue; + do { + area += (e.Org.s - e.Sym.Org.s) * (e.Org.t + e.Sym.Org.t); + e = e.Lnext; + } while (e != f.anEdge); + } + if (area < 0) { +/* Reverse the orientation by flipping all the t-coordinates */ + for (v = vHead.next; v != vHead; v = v.next) { + v.t = -v.t; + } + tess.tUnit[0] = -tess.tUnit[0]; + tess.tUnit[1] = -tess.tUnit[1]; + tess.tUnit[2] = -tess.tUnit[2]; + } + } + +/* Determine the polygon normal and project vertices onto the plane + * of the polygon. + */ + public static void __gl_projectPolygon(GLUtessellatorImpl tess) { + GLUvertex v, vHead = tess.mesh.vHead; + double w; + double[] norm = new double[3]; + double[] sUnit, tUnit; + int i; + boolean computedNormal = false; + + norm[0] = tess.normal[0]; + norm[1] = tess.normal[1]; + norm[2] = tess.normal[2]; + if (norm[0] == 0 && norm[1] == 0 && norm[2] == 0) { + ComputeNormal(tess, norm); + computedNormal = true; + } + sUnit = tess.sUnit; + tUnit = tess.tUnit; + i = LongAxis(norm); + + if (TRUE_PROJECT) { +/* Choose the initial sUnit vector to be approximately perpendicular + * to the normal. + */ + Normalize(norm); + + sUnit[i] = 0; + sUnit[(i + 1) % 3] = S_UNIT_X; + sUnit[(i + 2) % 3] = S_UNIT_Y; + +/* Now make it exactly perpendicular */ + w = Dot(sUnit, norm); + sUnit[0] -= w * norm[0]; + sUnit[1] -= w * norm[1]; + sUnit[2] -= w * norm[2]; + Normalize(sUnit); + +/* Choose tUnit so that (sUnit,tUnit,norm) form a right-handed frame */ + tUnit[0] = norm[1] * sUnit[2] - norm[2] * sUnit[1]; + tUnit[1] = norm[2] * sUnit[0] - norm[0] * sUnit[2]; + tUnit[2] = norm[0] * sUnit[1] - norm[1] * sUnit[0]; + Normalize(tUnit); + } else { +/* Project perpendicular to a coordinate axis -- better numerically */ + sUnit[i] = 0; + sUnit[(i + 1) % 3] = S_UNIT_X; + sUnit[(i + 2) % 3] = S_UNIT_Y; + + tUnit[i] = 0; + tUnit[(i + 1) % 3] = (norm[i] > 0) ? -S_UNIT_Y : S_UNIT_Y; + tUnit[(i + 2) % 3] = (norm[i] > 0) ? S_UNIT_X : -S_UNIT_X; + } + +/* Project the vertices onto the sweep plane */ + for (v = vHead.next; v != vHead; v = v.next) { + v.s = Dot(v.coords, sUnit); + v.t = Dot(v.coords, tUnit); + } + if (computedNormal) { + CheckOrientation(tess); + } + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQ.java b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQ.java new file mode 100644 index 0000000..8fdcf91 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQ.java @@ -0,0 +1,132 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +abstract class PriorityQ { + public static final int INIT_SIZE = 32; + + public static class PQnode { + int handle; + } + + public static class PQhandleElem { + Object key; + int node; + } + + public interface Leq { + boolean leq(Object key1, Object key2); + } + + // #ifdef FOR_TRITE_TEST_PROGRAM +// private static boolean LEQ(PriorityQCommon.Leq leq, Object x,Object y) { +// return pq.leq.leq(x,y); +// } +// #else +/* Violates modularity, but a little faster */ +// #include "geom.h" + public static boolean LEQ(Leq leq, Object x, Object y) { + return Geom.VertLeq((GLUvertex) x, (GLUvertex) y); + } + + static PriorityQ pqNewPriorityQ(Leq leq) { + return new PriorityQSort(leq); + } + + abstract void pqDeletePriorityQ(); + + abstract boolean pqInit(); + + abstract int pqInsert(Object keyNew); + + abstract Object pqExtractMin(); + + abstract void pqDelete(int hCurr); + + abstract Object pqMinimum(); + + abstract boolean pqIsEmpty(); +// #endif +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQHeap.java b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQHeap.java new file mode 100644 index 0000000..44a0043 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQHeap.java @@ -0,0 +1,296 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + + + +class PriorityQHeap extends PriorityQ { + PriorityQ.PQnode[] nodes; + PriorityQ.PQhandleElem[] handles; + int size, max; + int freeList; + boolean initialized; + PriorityQ.Leq leq; + +/* really __gl_pqHeapNewPriorityQ */ +PriorityQHeap(PriorityQ.Leq leq) { + size = 0; + max = PriorityQ.INIT_SIZE; + nodes = new PriorityQ.PQnode[PriorityQ.INIT_SIZE + 1]; + for (int i = 0; i < nodes.length; i++) { + nodes[i] = new PQnode(); + } + handles = new PriorityQ.PQhandleElem[PriorityQ.INIT_SIZE + 1]; + for (int i = 0; i < handles.length; i++) { + handles[i] = new PQhandleElem(); + } + initialized = false; + freeList = 0; + this.leq = leq; + + nodes[1].handle = 1; /* so that Minimum() returns NULL */ + handles[1].key = null; + } + +/* really __gl_pqHeapDeletePriorityQ */ + void pqDeletePriorityQ() { + handles = null; + nodes = null; + } + + void FloatDown(int curr) { + PriorityQ.PQnode[] n = nodes; + PriorityQ.PQhandleElem[] h = handles; + int hCurr, hChild; + int child; + + hCurr = n[curr].handle; + for (; ;) { + child = curr << 1; + if (child < size && LEQ(leq, h[n[child + 1].handle].key, + h[n[child].handle].key)) { + ++child; + } + + assert (child <= max); + + hChild = n[child].handle; + if (child > size || LEQ(leq, h[hCurr].key, h[hChild].key)) { + n[curr].handle = hCurr; + h[hCurr].node = curr; + break; + } + n[curr].handle = hChild; + h[hChild].node = curr; + curr = child; + } + } + + + void FloatUp(int curr) { + PriorityQ.PQnode[] n = nodes; + PriorityQ.PQhandleElem[] h = handles; + int hCurr, hParent; + int parent; + + hCurr = n[curr].handle; + for (; ;) { + parent = curr >> 1; + hParent = n[parent].handle; + if (parent == 0 || LEQ(leq, h[hParent].key, h[hCurr].key)) { + n[curr].handle = hCurr; + h[hCurr].node = curr; + break; + } + n[curr].handle = hParent; + h[hParent].node = curr; + curr = parent; + } + } + +/* really __gl_pqHeapInit */ + boolean pqInit() { + int i; + + /* This method of building a heap is O(n), rather than O(n lg n). */ + + for (i = size; i >= 1; --i) { + FloatDown(i); + } + initialized = true; + + return true; + } + +/* really __gl_pqHeapInsert */ +/* returns LONG_MAX iff out of memory */ + int pqInsert(Object keyNew) { + int curr; + int free; + + curr = ++size; + if ((curr * 2) > max) { + PriorityQ.PQnode[] saveNodes = nodes; + PriorityQ.PQhandleElem[] saveHandles = handles; + + /* If the heap overflows, double its size. */ + max <<= 1; +// pq->nodes = (PQnode *)memRealloc( pq->nodes, (size_t) ((pq->max + 1) * sizeof( pq->nodes[0] ))); + PriorityQ.PQnode[] pqNodes = new PriorityQ.PQnode[max + 1]; + System.arraycopy( nodes, 0, pqNodes, 0, nodes.length ); + for (int i = nodes.length; i < pqNodes.length; i++) { + pqNodes[i] = new PQnode(); + } + nodes = pqNodes; + if (nodes == null) { + nodes = saveNodes; /* restore ptr to free upon return */ + return Integer.MAX_VALUE; + } + +// pq->handles = (PQhandleElem *)memRealloc( pq->handles,(size_t)((pq->max + 1) * sizeof( pq->handles[0] ))); + PriorityQ.PQhandleElem[] pqHandles = new PriorityQ.PQhandleElem[max + 1]; + System.arraycopy( handles, 0, pqHandles, 0, handles.length ); + for (int i = handles.length; i < pqHandles.length; i++) { + pqHandles[i] = new PQhandleElem(); + } + handles = pqHandles; + if (handles == null) { + handles = saveHandles; /* restore ptr to free upon return */ + return Integer.MAX_VALUE; + } + } + + if (freeList == 0) { + free = curr; + } else { + free = freeList; + freeList = handles[free].node; + } + + nodes[curr].handle = free; + handles[free].node = curr; + handles[free].key = keyNew; + + if (initialized) { + FloatUp(curr); + } + assert (free != Integer.MAX_VALUE); + return free; + } + +/* really __gl_pqHeapExtractMin */ + Object pqExtractMin() { + PriorityQ.PQnode[] n = nodes; + PriorityQ.PQhandleElem[] h = handles; + int hMin = n[1].handle; + Object min = h[hMin].key; + + if (size > 0) { + n[1].handle = n[size].handle; + h[n[1].handle].node = 1; + + h[hMin].key = null; + h[hMin].node = freeList; + freeList = hMin; + + if (--size > 0) { + FloatDown(1); + } + } + return min; + } + +/* really __gl_pqHeapDelete */ + void pqDelete(int hCurr) { + PriorityQ.PQnode[] n = nodes; + PriorityQ.PQhandleElem[] h = handles; + int curr; + + assert (hCurr >= 1 && hCurr <= max && h[hCurr].key != null); + + curr = h[hCurr].node; + n[curr].handle = n[size].handle; + h[n[curr].handle].node = curr; + + if (curr <= --size) { + if (curr <= 1 || LEQ(leq, h[n[curr >> 1].handle].key, h[n[curr].handle].key)) { + FloatDown(curr); + } else { + FloatUp(curr); + } + } + h[hCurr].key = null; + h[hCurr].node = freeList; + freeList = hCurr; + } + + Object pqMinimum() { + return handles[nodes[1].handle].key; + } + + boolean pqIsEmpty() { + return size == 0; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQSort.java b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQSort.java new file mode 100644 index 0000000..65b766f --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/PriorityQSort.java @@ -0,0 +1,310 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + + + +class PriorityQSort extends PriorityQ { + PriorityQHeap heap; + Object[] keys; + + // JAVA: 'order' contains indices into the keys array. + // This simulates the indirect pointers used in the original C code + // (from Frank Suykens, Luciad.com). + int[] order; + int size, max; + boolean initialized; + PriorityQ.Leq leq; + + PriorityQSort(PriorityQ.Leq leq) { + heap = new PriorityQHeap(leq); + + keys = new Object[PriorityQ.INIT_SIZE]; + + size = 0; + max = PriorityQ.INIT_SIZE; + initialized = false; + this.leq = leq; + } + +/* really __gl_pqSortDeletePriorityQ */ + void pqDeletePriorityQ() { + if (heap != null) heap.pqDeletePriorityQ(); + order = null; + keys = null; + } + + private static boolean LT(PriorityQ.Leq leq, Object x, Object y) { + return (!PriorityQHeap.LEQ(leq, y, x)); + } + + private static boolean GT(PriorityQ.Leq leq, Object x, Object y) { + return (!PriorityQHeap.LEQ(leq, x, y)); + } + + private static void Swap(int[] array, int a, int b) { + if (true) { + int tmp = array[a]; + array[a] = array[b]; + array[b] = tmp; + } + } + + private static class Stack { + int p, r; + } + +/* really __gl_pqSortInit */ + boolean pqInit() { + int p, r, i, j; + int piv; + Stack[] stack = new Stack[50]; + for (int k = 0; k < stack.length; k++) { + stack[k] = new Stack(); + } + int top = 0; + + int seed = 2016473283; + + /* Create an array of indirect pointers to the keys, so that we + * the handles we have returned are still valid. + */ + order = new int[size + 1]; +/* the previous line is a patch to compensate for the fact that IBM */ +/* machines return a null on a malloc of zero bytes (unlike SGI), */ +/* so we have to put in this defense to guard against a memory */ +/* fault four lines down. from fossum@austin.ibm.com. */ + p = 0; + r = size - 1; + for (piv = 0, i = p; i <= r; ++piv, ++i) { + // indirect pointers: keep an index into the keys array, not a direct pointer to its contents + order[i] = piv; + } + + /* Sort the indirect pointers in descending order, + * using randomized Quicksort + */ + stack[top].p = p; + stack[top].r = r; + ++top; + while (--top >= 0) { + p = stack[top].p; + r = stack[top].r; + while (r > p + 10) { + seed = Math.abs( seed * 1539415821 + 1 ); + i = p + seed % (r - p + 1); + piv = order[i]; + order[i] = order[p]; + order[p] = piv; + i = p - 1; + j = r + 1; + do { + do { + ++i; + } while (GT(leq, keys[order[i]], keys[piv])); + do { + --j; + } while (LT(leq, keys[order[j]], keys[piv])); + Swap(order, i, j); + } while (i < j); + Swap(order, i, j); /* Undo last swap */ + if (i - p < r - j) { + stack[top].p = j + 1; + stack[top].r = r; + ++top; + r = i - 1; + } else { + stack[top].p = p; + stack[top].r = i - 1; + ++top; + p = j + 1; + } + } + /* Insertion sort small lists */ + for (i = p + 1; i <= r; ++i) { + piv = order[i]; + for (j = i; j > p && LT(leq, keys[order[j - 1]], keys[piv]); --j) { + order[j] = order[j - 1]; + } + order[j] = piv; + } + } + max = size; + initialized = true; + heap.pqInit(); /* always succeeds */ + +/* #ifndef NDEBUG + p = order; + r = p + size - 1; + for (i = p; i < r; ++i) { + Assertion.doAssert(LEQ( * * (i + 1), **i )); + } + #endif*/ + + return true; + } + +/* really __gl_pqSortInsert */ +/* returns LONG_MAX iff out of memory */ + int pqInsert(Object keyNew) { + int curr; + + if (initialized) { + return heap.pqInsert(keyNew); + } + curr = size; + if (++size >= max) { + Object[] saveKey = keys; + + /* If the heap overflows, double its size. */ + max <<= 1; +// pq->keys = (PQHeapKey *)memRealloc( pq->keys,(size_t)(pq->max * sizeof( pq->keys[0] ))); + Object[] pqKeys = new Object[max]; + System.arraycopy( keys, 0, pqKeys, 0, keys.length ); + keys = pqKeys; + if (keys == null) { + keys = saveKey; /* restore ptr to free upon return */ + return Integer.MAX_VALUE; + } + } + assert curr != Integer.MAX_VALUE; + keys[curr] = keyNew; + + /* Negative handles index the sorted array. */ + return -(curr + 1); + } + +/* really __gl_pqSortExtractMin */ + Object pqExtractMin() { + Object sortMin, heapMin; + + if (size == 0) { + return heap.pqExtractMin(); + } + sortMin = keys[order[size - 1]]; + if (!heap.pqIsEmpty()) { + heapMin = heap.pqMinimum(); + if (LEQ(leq, heapMin, sortMin)) { + return heap.pqExtractMin(); + } + } + do { + --size; + } while (size > 0 && keys[order[size - 1]] == null); + return sortMin; + } + +/* really __gl_pqSortMinimum */ + Object pqMinimum() { + Object sortMin, heapMin; + + if (size == 0) { + return heap.pqMinimum(); + } + sortMin = keys[order[size - 1]]; + if (!heap.pqIsEmpty()) { + heapMin = heap.pqMinimum(); + if (PriorityQHeap.LEQ(leq, heapMin, sortMin)) { + return heapMin; + } + } + return sortMin; + } + +/* really __gl_pqSortIsEmpty */ + boolean pqIsEmpty() { + return (size == 0) && heap.pqIsEmpty(); + } + +/* really __gl_pqSortDelete */ + void pqDelete(int curr) { + if (curr >= 0) { + heap.pqDelete(curr); + return; + } + curr = -(curr + 1); + assert curr < max && keys[curr] != null; + + keys[curr] = null; + while (size > 0 && keys[order[size - 1]] == null) { + --size; + } + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Render.java b/src/main/java/org/lwjglx/util/glu/tessellation/Render.java new file mode 100644 index 0000000..954d432 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Render.java @@ -0,0 +1,589 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjglx.util.glu.GLU.*; + +class Render { + private static final boolean USE_OPTIMIZED_CODE_PATH = false; + + private Render() { + } + + private static final RenderFan renderFan = new RenderFan(); + private static final RenderStrip renderStrip = new RenderStrip(); + private static final RenderTriangle renderTriangle = new RenderTriangle(); + +/* This structure remembers the information we need about a primitive + * to be able to render it later, once we have determined which + * primitive is able to use the most triangles. + */ + private static class FaceCount { + private FaceCount() { + } + + private FaceCount(long size, GLUhalfEdge eStart, renderCallBack render) { + this.size = size; + this.eStart = eStart; + this.render = render; + } + + long size; /* number of triangles used */ + GLUhalfEdge eStart; /* edge where this primitive starts */ + renderCallBack render; + }; + + private interface renderCallBack { + void render(GLUtessellatorImpl tess, GLUhalfEdge e, long size); + } + + /************************ Strips and Fans decomposition ******************/ + +/* __gl_renderMesh( tess, mesh ) takes a mesh and breaks it into triangle + * fans, strips, and separate triangles. A substantial effort is made + * to use as few rendering primitives as possible (ie. to make the fans + * and strips as large as possible). + * + * The rendering output is provided as callbacks (see the api). + */ + public static void __gl_renderMesh(GLUtessellatorImpl tess, GLUmesh mesh) { + GLUface f; + + /* Make a list of separate triangles so we can render them all at once */ + tess.lonelyTriList = null; + + for (f = mesh.fHead.next; f != mesh.fHead; f = f.next) { + f.marked = false; + } + for (f = mesh.fHead.next; f != mesh.fHead; f = f.next) { + + /* We examine all faces in an arbitrary order. Whenever we find + * an unprocessed face F, we output a group of faces including F + * whose size is maximum. + */ + if (f.inside && !f.marked) { + RenderMaximumFaceGroup(tess, f); + assert (f.marked); + } + } + if (tess.lonelyTriList != null) { + RenderLonelyTriangles(tess, tess.lonelyTriList); + tess.lonelyTriList = null; + } + } + + + static void RenderMaximumFaceGroup(GLUtessellatorImpl tess, GLUface fOrig) { + /* We want to find the largest triangle fan or strip of unmarked faces + * which includes the given face fOrig. There are 3 possible fans + * passing through fOrig (one centered at each vertex), and 3 possible + * strips (one for each CCW permutation of the vertices). Our strategy + * is to try all of these, and take the primitive which uses the most + * triangles (a greedy approach). + */ + GLUhalfEdge e = fOrig.anEdge; + FaceCount max = new FaceCount(); + FaceCount newFace; + + max.size = 1; + max.eStart = e; + max.render = renderTriangle; + + if (!tess.flagBoundary) { + newFace = MaximumFan(e); + if (newFace.size > max.size) { + max = newFace; + } + newFace = MaximumFan(e.Lnext); + if (newFace.size > max.size) { + max = newFace; + } + newFace = MaximumFan(e.Onext.Sym); + if (newFace.size > max.size) { + max = newFace; + } + + newFace = MaximumStrip(e); + if (newFace.size > max.size) { + max = newFace; + } + newFace = MaximumStrip(e.Lnext); + if (newFace.size > max.size) { + max = newFace; + } + newFace = MaximumStrip(e.Onext.Sym); + if (newFace.size > max.size) { + max = newFace; + } + } + max.render.render(tess, max.eStart, max.size); + } + + +/* Macros which keep track of faces we have marked temporarily, and allow + * us to backtrack when necessary. With triangle fans, this is not + * really necessary, since the only awkward case is a loop of triangles + * around a single origin vertex. However with strips the situation is + * more complicated, and we need a general tracking method like the + * one here. + */ + private static boolean Marked(GLUface f) { + return !f.inside || f.marked; + } + + private static GLUface AddToTrail(GLUface f, GLUface t) { + f.trail = t; + f.marked = true; + return f; + } + + private static void FreeTrail(GLUface t) { + if (true) { + while (t != null) { + t.marked = false; + t = t.trail; + } + } + + /* else absorb trailing semicolon */ + } + + static FaceCount MaximumFan(GLUhalfEdge eOrig) { + /* eOrig.Lface is the face we want to render. We want to find the size + * of a maximal fan around eOrig.Org. To do this we just walk around + * the origin vertex as far as possible in both directions. + */ + FaceCount newFace = new FaceCount(0, null, renderFan); + GLUface trail = null; + GLUhalfEdge e; + + for (e = eOrig; !Marked(e.Lface); e = e.Onext) { + trail = AddToTrail(e.Lface, trail); + ++newFace.size; + } + for (e = eOrig; !Marked(e.Sym.Lface); e = e.Sym.Lnext) { + trail = AddToTrail(e.Sym.Lface, trail); + ++newFace.size; + } + newFace.eStart = e; + /*LINTED*/ + FreeTrail(trail); + return newFace; + } + + + private static boolean IsEven(long n) { + return (n & 0x1L) == 0; + } + + static FaceCount MaximumStrip(GLUhalfEdge eOrig) { + /* Here we are looking for a maximal strip that contains the vertices + * eOrig.Org, eOrig.Dst, eOrig.Lnext.Dst (in that order or the + * reverse, such that all triangles are oriented CCW). + * + * Again we walk forward and backward as far as possible. However for + * strips there is a twist: to get CCW orientations, there must be + * an *even* number of triangles in the strip on one side of eOrig. + * We walk the strip starting on a side with an even number of triangles; + * if both side have an odd number, we are forced to shorten one side. + */ + FaceCount newFace = new FaceCount(0, null, renderStrip); + long headSize = 0, tailSize = 0; + GLUface trail = null; + GLUhalfEdge e, eTail, eHead; + + for (e = eOrig; !Marked(e.Lface); ++tailSize, e = e.Onext) { + trail = AddToTrail(e.Lface, trail); + ++tailSize; + e = e.Lnext.Sym; + if (Marked(e.Lface)) break; + trail = AddToTrail(e.Lface, trail); + } + eTail = e; + + for (e = eOrig; !Marked(e.Sym.Lface); ++headSize, e = e.Sym.Onext.Sym) { + trail = AddToTrail(e.Sym.Lface, trail); + ++headSize; + e = e.Sym.Lnext; + if (Marked(e.Sym.Lface)) break; + trail = AddToTrail(e.Sym.Lface, trail); + } + eHead = e; + + newFace.size = tailSize + headSize; + if (IsEven(tailSize)) { + newFace.eStart = eTail.Sym; + } else if (IsEven(headSize)) { + newFace.eStart = eHead; + } else { + /* Both sides have odd length, we must shorten one of them. In fact, + * we must start from eHead to guarantee inclusion of eOrig.Lface. + */ + --newFace.size; + newFace.eStart = eHead.Onext; + } + /*LINTED*/ + FreeTrail(trail); + return newFace; + } + + private static class RenderTriangle implements renderCallBack { + public void render(GLUtessellatorImpl tess, GLUhalfEdge e, long size) { + /* Just add the triangle to a triangle list, so we can render all + * the separate triangles at once. + */ + assert (size == 1); + tess.lonelyTriList = AddToTrail(e.Lface, tess.lonelyTriList); + } + } + + + static void RenderLonelyTriangles(GLUtessellatorImpl tess, GLUface f) { + /* Now we render all the separate triangles which could not be + * grouped into a triangle fan or strip. + */ + GLUhalfEdge e; + int newState; + int edgeState = -1; /* force edge state output for first vertex */ + + tess.callBeginOrBeginData(GL_TRIANGLES); + + for (; f != null; f = f.trail) { + /* Loop once for each edge (there will always be 3 edges) */ + + e = f.anEdge; + do { + if (tess.flagBoundary) { + /* Set the "edge state" to true just before we output the + * first vertex of each edge on the polygon boundary. + */ + newState = (!e.Sym.Lface.inside) ? 1 : 0; + if (edgeState != newState) { + edgeState = newState; + tess.callEdgeFlagOrEdgeFlagData( edgeState != 0); + } + } + tess.callVertexOrVertexData( e.Org.data); + + e = e.Lnext; + } while (e != f.anEdge); + } + tess.callEndOrEndData(); + } + + private static class RenderFan implements renderCallBack { + public void render(GLUtessellatorImpl tess, GLUhalfEdge e, long size) { + /* Render as many CCW triangles as possible in a fan starting from + * edge "e". The fan *should* contain exactly "size" triangles + * (otherwise we've goofed up somewhere). + */ + tess.callBeginOrBeginData(GL_TRIANGLE_FAN); + tess.callVertexOrVertexData( e.Org.data); + tess.callVertexOrVertexData( e.Sym.Org.data); + + while (!Marked(e.Lface)) { + e.Lface.marked = true; + --size; + e = e.Onext; + tess.callVertexOrVertexData( e.Sym.Org.data); + } + + assert (size == 0); + tess.callEndOrEndData(); + } + } + + private static class RenderStrip implements renderCallBack { + public void render(GLUtessellatorImpl tess, GLUhalfEdge e, long size) { + /* Render as many CCW triangles as possible in a strip starting from + * edge "e". The strip *should* contain exactly "size" triangles + * (otherwise we've goofed up somewhere). + */ + tess.callBeginOrBeginData(GL_TRIANGLE_STRIP); + tess.callVertexOrVertexData( e.Org.data); + tess.callVertexOrVertexData( e.Sym.Org.data); + + while (!Marked(e.Lface)) { + e.Lface.marked = true; + --size; + e = e.Lnext.Sym; + tess.callVertexOrVertexData( e.Org.data); + if (Marked(e.Lface)) break; + + e.Lface.marked = true; + --size; + e = e.Onext; + tess.callVertexOrVertexData( e.Sym.Org.data); + } + + assert (size == 0); + tess.callEndOrEndData(); + } + } + + /************************ Boundary contour decomposition ******************/ + +/* __gl_renderBoundary( tess, mesh ) takes a mesh, and outputs one + * contour for each face marked "inside". The rendering output is + * provided as callbacks (see the api). + */ + public static void __gl_renderBoundary(GLUtessellatorImpl tess, GLUmesh mesh) { + GLUface f; + GLUhalfEdge e; + + for (f = mesh.fHead.next; f != mesh.fHead; f = f.next) { + if (f.inside) { + tess.callBeginOrBeginData(GL_LINE_LOOP); + e = f.anEdge; + do { + tess.callVertexOrVertexData( e.Org.data); + e = e.Lnext; + } while (e != f.anEdge); + tess.callEndOrEndData(); + } + } + } + + + /************************ Quick-and-dirty decomposition ******************/ + + private static final int SIGN_INCONSISTENT = 2; + + static int ComputeNormal(GLUtessellatorImpl tess, double[] norm, boolean check) +/* + * If check==false, we compute the polygon normal and place it in norm[]. + * If check==true, we check that each triangle in the fan from v0 has a + * consistent orientation with respect to norm[]. If triangles are + * consistently oriented CCW, return 1; if CW, return -1; if all triangles + * are degenerate return 0; otherwise (no consistent orientation) return + * SIGN_INCONSISTENT. + */ { + CachedVertex[] v = tess.cache; +// CachedVertex vn = v0 + tess.cacheCount; + int vn = tess.cacheCount; +// CachedVertex vc; + int vc; + double dot, xc, yc, zc, xp, yp, zp; + double[] n = new double[3]; + int sign = 0; + + /* Find the polygon normal. It is important to get a reasonable + * normal even when the polygon is self-intersecting (eg. a bowtie). + * Otherwise, the computed normal could be very tiny, but perpendicular + * to the true plane of the polygon due to numerical noise. Then all + * the triangles would appear to be degenerate and we would incorrectly + * decompose the polygon as a fan (or simply not render it at all). + * + * We use a sum-of-triangles normal algorithm rather than the more + * efficient sum-of-trapezoids method (used in CheckOrientation() + * in normal.c). This lets us explicitly reverse the signed area + * of some triangles to get a reasonable normal in the self-intersecting + * case. + */ + if (!check) { + norm[0] = norm[1] = norm[2] = 0.0; + } + + vc = 1; + xc = v[vc].coords[0] - v[0].coords[0]; + yc = v[vc].coords[1] - v[0].coords[1]; + zc = v[vc].coords[2] - v[0].coords[2]; + while (++vc < vn) { + xp = xc; + yp = yc; + zp = zc; + xc = v[vc].coords[0] - v[0].coords[0]; + yc = v[vc].coords[1] - v[0].coords[1]; + zc = v[vc].coords[2] - v[0].coords[2]; + + /* Compute (vp - v0) cross (vc - v0) */ + n[0] = yp * zc - zp * yc; + n[1] = zp * xc - xp * zc; + n[2] = xp * yc - yp * xc; + + dot = n[0] * norm[0] + n[1] * norm[1] + n[2] * norm[2]; + if (!check) { + /* Reverse the contribution of back-facing triangles to get + * a reasonable normal for self-intersecting polygons (see above) + */ + if (dot >= 0) { + norm[0] += n[0]; + norm[1] += n[1]; + norm[2] += n[2]; + } else { + norm[0] -= n[0]; + norm[1] -= n[1]; + norm[2] -= n[2]; + } + } else if (dot != 0) { + /* Check the new orientation for consistency with previous triangles */ + if (dot > 0) { + if (sign < 0) return SIGN_INCONSISTENT; + sign = 1; + } else { + if (sign > 0) return SIGN_INCONSISTENT; + sign = -1; + } + } + } + return sign; + } + +/* __gl_renderCache( tess ) takes a single contour and tries to render it + * as a triangle fan. This handles convex polygons, as well as some + * non-convex polygons if we get lucky. + * + * Returns true if the polygon was successfully rendered. The rendering + * output is provided as callbacks (see the api). + */ + public static boolean __gl_renderCache(GLUtessellatorImpl tess) { + CachedVertex[] v = tess.cache; +// CachedVertex vn = v0 + tess.cacheCount; + int vn = tess.cacheCount; +// CachedVertex vc; + int vc; + double[] norm = new double[3]; + int sign; + + if (tess.cacheCount < 3) { + /* Degenerate contour -- no output */ + return true; + } + + norm[0] = tess.normal[0]; + norm[1] = tess.normal[1]; + norm[2] = tess.normal[2]; + if (norm[0] == 0 && norm[1] == 0 && norm[2] == 0) { + ComputeNormal( tess, norm, false); + } + + sign = ComputeNormal( tess, norm, true); + if (sign == SIGN_INCONSISTENT) { + /* Fan triangles did not have a consistent orientation */ + return false; + } + if (sign == 0) { + /* All triangles were degenerate */ + return true; + } + + if ( !USE_OPTIMIZED_CODE_PATH ) { + return false; + } else { + /* Make sure we do the right thing for each winding rule */ + switch (tess.windingRule) { + case GLU_TESS_WINDING_ODD: + case GLU_TESS_WINDING_NONZERO: + break; + case GLU_TESS_WINDING_POSITIVE: + if (sign < 0) return true; + break; + case GLU_TESS_WINDING_NEGATIVE: + if (sign > 0) return true; + break; + case GLU_TESS_WINDING_ABS_GEQ_TWO: + return true; + } + + tess.callBeginOrBeginData( tess.boundaryOnly ? GL_LINE_LOOP + : (tess.cacheCount > 3) ? GL_TRIANGLE_FAN + : GL_TRIANGLES); + + tess.callVertexOrVertexData( v[0].data); + if (sign > 0) { + for (vc = 1; vc < vn; ++vc) { + tess.callVertexOrVertexData( v[vc].data); + } + } else { + for (vc = vn - 1; vc > 0; --vc) { + tess.callVertexOrVertexData( v[vc].data); + } + } + tess.callEndOrEndData(); + return true; + } + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/Sweep.java b/src/main/java/org/lwjglx/util/glu/tessellation/Sweep.java new file mode 100644 index 0000000..b0ad489 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/Sweep.java @@ -0,0 +1,1384 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +import static org.lwjglx.util.glu.GLU.*; + +class Sweep { + private Sweep() { + } + +// #ifdef FOR_TRITE_TEST_PROGRAM +// extern void DebugEvent( GLUtessellator *tess ); +// #else + private static void DebugEvent(GLUtessellatorImpl tess) { + + } +// #endif + +/* + * Invariants for the Edge Dictionary. + * - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2) + * at any valid location of the sweep event + * - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2 + * share a common endpoint + * - for each e, e.Dst has been processed, but not e.Org + * - each edge e satisfies VertLeq(e.Dst,event) && VertLeq(event,e.Org) + * where "event" is the current sweep line event. + * - no edge e has zero length + * + * Invariants for the Mesh (the processed portion). + * - the portion of the mesh left of the sweep line is a planar graph, + * ie. there is *some* way to embed it in the plane + * - no processed edge has zero length + * - no two processed vertices have identical coordinates + * - each "inside" region is monotone, ie. can be broken into two chains + * of monotonically increasing vertices according to VertLeq(v1,v2) + * - a non-invariant: these chains may intersect (very slightly) + * + * Invariants for the Sweep. + * - if none of the edges incident to the event vertex have an activeRegion + * (ie. none of these edges are in the edge dictionary), then the vertex + * has only right-going edges. + * - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced + * by ConnectRightVertex), then it is the only right-going edge from + * its associated vertex. (This says that these edges exist only + * when it is necessary.) + */ + +/* When we merge two edges into one, we need to compute the combined + * winding of the new edge. + */ + private static void AddWinding(GLUhalfEdge eDst, GLUhalfEdge eSrc) { + eDst.winding += eSrc.winding; + eDst.Sym.winding += eSrc.Sym.winding; + } + + + private static ActiveRegion RegionBelow(ActiveRegion r) { + return ((ActiveRegion) Dict.dictKey(Dict.dictPred(r.nodeUp))); + } + + private static ActiveRegion RegionAbove(ActiveRegion r) { + return ((ActiveRegion) Dict.dictKey(Dict.dictSucc(r.nodeUp))); + } + + static boolean EdgeLeq(GLUtessellatorImpl tess, ActiveRegion reg1, ActiveRegion reg2) +/* + * Both edges must be directed from right to left (this is the canonical + * direction for the upper edge of each region). + * + * The strategy is to evaluate a "t" value for each edge at the + * current sweep line position, given by tess.event. The calculations + * are designed to be very stable, but of course they are not perfect. + * + * Special case: if both edge destinations are at the sweep event, + * we sort the edges by slope (they would otherwise compare equally). + */ { + GLUvertex event = tess.event; + GLUhalfEdge e1, e2; + double t1, t2; + + e1 = reg1.eUp; + e2 = reg2.eUp; + + if (e1.Sym.Org == event) { + if (e2.Sym.Org == event) { + /* Two edges right of the sweep line which meet at the sweep event. + * Sort them by slope. + */ + if (Geom.VertLeq(e1.Org, e2.Org)) { + return Geom.EdgeSign(e2.Sym.Org, e1.Org, e2.Org) <= 0; + } + return Geom.EdgeSign(e1.Sym.Org, e2.Org, e1.Org) >= 0; + } + return Geom.EdgeSign(e2.Sym.Org, event, e2.Org) <= 0; + } + if (e2.Sym.Org == event) { + return Geom.EdgeSign(e1.Sym.Org, event, e1.Org) >= 0; + } + + /* General case - compute signed distance *from* e1, e2 to event */ + t1 = Geom.EdgeEval(e1.Sym.Org, event, e1.Org); + t2 = Geom.EdgeEval(e2.Sym.Org, event, e2.Org); + return (t1 >= t2); + } + + + static void DeleteRegion(GLUtessellatorImpl tess, ActiveRegion reg) { + if (reg.fixUpperEdge) { + /* It was created with zero winding number, so it better be + * deleted with zero winding number (ie. it better not get merged + * with a real edge). + */ + assert (reg.eUp.winding == 0); + } + reg.eUp.activeRegion = null; + Dict.dictDelete(tess.dict, reg.nodeUp); /* __gl_dictListDelete */ + } + + + static boolean FixUpperEdge(ActiveRegion reg, GLUhalfEdge newEdge) +/* + * Replace an upper edge which needs fixing (see ConnectRightVertex). + */ { + assert (reg.fixUpperEdge); + if (!Mesh.__gl_meshDelete(reg.eUp)) return false; + reg.fixUpperEdge = false; + reg.eUp = newEdge; + newEdge.activeRegion = reg; + + return true; + } + + static ActiveRegion TopLeftRegion(ActiveRegion reg) { + GLUvertex org = reg.eUp.Org; + GLUhalfEdge e; + + /* Find the region above the uppermost edge with the same origin */ + do { + reg = RegionAbove(reg); + } while (reg.eUp.Org == org); + + /* If the edge above was a temporary edge introduced by ConnectRightVertex, + * now is the time to fix it. + */ + if (reg.fixUpperEdge) { + e = Mesh.__gl_meshConnect(RegionBelow(reg).eUp.Sym, reg.eUp.Lnext); + if (e == null) return null; + if (!FixUpperEdge(reg, e)) return null; + reg = RegionAbove(reg); + } + return reg; + } + + static ActiveRegion TopRightRegion(ActiveRegion reg) { + GLUvertex dst = reg.eUp.Sym.Org; + + /* Find the region above the uppermost edge with the same destination */ + do { + reg = RegionAbove(reg); + } while (reg.eUp.Sym.Org == dst); + return reg; + } + + static ActiveRegion AddRegionBelow(GLUtessellatorImpl tess, + ActiveRegion regAbove, + GLUhalfEdge eNewUp) +/* + * Add a new active region to the sweep line, *somewhere* below "regAbove" + * (according to where the new edge belongs in the sweep-line dictionary). + * The upper edge of the new region will be "eNewUp". + * Winding number and "inside" flag are not updated. + */ { + ActiveRegion regNew = new ActiveRegion(); + //if (regNew == null) throw new RuntimeException(); + + regNew.eUp = eNewUp; + /* __gl_dictListInsertBefore */ + regNew.nodeUp = Dict.dictInsertBefore(tess.dict, regAbove.nodeUp, regNew); + if (regNew.nodeUp == null) throw new RuntimeException(); + regNew.fixUpperEdge = false; + regNew.sentinel = false; + regNew.dirty = false; + + eNewUp.activeRegion = regNew; + return regNew; + } + + static boolean IsWindingInside(GLUtessellatorImpl tess, int n) { + switch (tess.windingRule) { + case GLU_TESS_WINDING_ODD: + return (n & 1) != 0; + case GLU_TESS_WINDING_NONZERO: + return (n != 0); + case GLU_TESS_WINDING_POSITIVE: + return (n > 0); + case GLU_TESS_WINDING_NEGATIVE: + return (n < 0); + case GLU_TESS_WINDING_ABS_GEQ_TWO: + return (n >= 2) || (n <= -2); + } + /*LINTED*/ +// assert (false); + throw new InternalError(); + /*NOTREACHED*/ + } + + + static void ComputeWinding(GLUtessellatorImpl tess, ActiveRegion reg) { + reg.windingNumber = RegionAbove(reg).windingNumber + reg.eUp.winding; + reg.inside = IsWindingInside(tess, reg.windingNumber); + } + + + static void FinishRegion(GLUtessellatorImpl tess, ActiveRegion reg) +/* + * Delete a region from the sweep line. This happens when the upper + * and lower chains of a region meet (at a vertex on the sweep line). + * The "inside" flag is copied to the appropriate mesh face (we could + * not do this before -- since the structure of the mesh is always + * changing, this face may not have even existed until now). + */ { + GLUhalfEdge e = reg.eUp; + GLUface f = e.Lface; + + f.inside = reg.inside; + f.anEdge = e; /* optimization for __gl_meshTessellateMonoRegion() */ + DeleteRegion(tess, reg); + } + + + static GLUhalfEdge FinishLeftRegions(GLUtessellatorImpl tess, + ActiveRegion regFirst, ActiveRegion regLast) +/* + * We are given a vertex with one or more left-going edges. All affected + * edges should be in the edge dictionary. Starting at regFirst.eUp, + * we walk down deleting all regions where both edges have the same + * origin vOrg. At the same time we copy the "inside" flag from the + * active region to the face, since at this point each face will belong + * to at most one region (this was not necessarily true until this point + * in the sweep). The walk stops at the region above regLast; if regLast + * is null we walk as far as possible. At the same time we relink the + * mesh if necessary, so that the ordering of edges around vOrg is the + * same as in the dictionary. + */ { + ActiveRegion reg, regPrev; + GLUhalfEdge e, ePrev; + + regPrev = regFirst; + ePrev = regFirst.eUp; + while (regPrev != regLast) { + regPrev.fixUpperEdge = false; /* placement was OK */ + reg = RegionBelow(regPrev); + e = reg.eUp; + if (e.Org != ePrev.Org) { + if (!reg.fixUpperEdge) { + /* Remove the last left-going edge. Even though there are no further + * edges in the dictionary with this origin, there may be further + * such edges in the mesh (if we are adding left edges to a vertex + * that has already been processed). Thus it is important to call + * FinishRegion rather than just DeleteRegion. + */ + FinishRegion(tess, regPrev); + break; + } + /* If the edge below was a temporary edge introduced by + * ConnectRightVertex, now is the time to fix it. + */ + e = Mesh.__gl_meshConnect(ePrev.Onext.Sym, e.Sym); + if (e == null) throw new RuntimeException(); + if (!FixUpperEdge(reg, e)) throw new RuntimeException(); + } + + /* Relink edges so that ePrev.Onext == e */ + if (ePrev.Onext != e) { + if (!Mesh.__gl_meshSplice(e.Sym.Lnext, e)) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(ePrev, e)) throw new RuntimeException(); + } + FinishRegion(tess, regPrev); /* may change reg.eUp */ + ePrev = reg.eUp; + regPrev = reg; + } + return ePrev; + } + + + static void AddRightEdges(GLUtessellatorImpl tess, ActiveRegion regUp, + GLUhalfEdge eFirst, GLUhalfEdge eLast, GLUhalfEdge eTopLeft, + boolean cleanUp) +/* + * Purpose: insert right-going edges into the edge dictionary, and update + * winding numbers and mesh connectivity appropriately. All right-going + * edges share a common origin vOrg. Edges are inserted CCW starting at + * eFirst; the last edge inserted is eLast.Sym.Lnext. If vOrg has any + * left-going edges already processed, then eTopLeft must be the edge + * such that an imaginary upward vertical segment from vOrg would be + * contained between eTopLeft.Sym.Lnext and eTopLeft; otherwise eTopLeft + * should be null. + */ { + ActiveRegion reg, regPrev; + GLUhalfEdge e, ePrev; + boolean firstTime = true; + + /* Insert the new right-going edges in the dictionary */ + e = eFirst; + do { + assert (Geom.VertLeq(e.Org, e.Sym.Org)); + AddRegionBelow(tess, regUp, e.Sym); + e = e.Onext; + } while (e != eLast); + + /* Walk *all* right-going edges from e.Org, in the dictionary order, + * updating the winding numbers of each region, and re-linking the mesh + * edges to match the dictionary ordering (if necessary). + */ + if (eTopLeft == null) { + eTopLeft = RegionBelow(regUp).eUp.Sym.Onext; + } + regPrev = regUp; + ePrev = eTopLeft; + for (; ;) { + reg = RegionBelow(regPrev); + e = reg.eUp.Sym; + if (e.Org != ePrev.Org) break; + + if (e.Onext != ePrev) { + /* Unlink e from its current position, and relink below ePrev */ + if (!Mesh.__gl_meshSplice(e.Sym.Lnext, e)) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(ePrev.Sym.Lnext, e)) throw new RuntimeException(); + } + /* Compute the winding number and "inside" flag for the new regions */ + reg.windingNumber = regPrev.windingNumber - e.winding; + reg.inside = IsWindingInside(tess, reg.windingNumber); + + /* Check for two outgoing edges with same slope -- process these + * before any intersection tests (see example in __gl_computeInterior). + */ + regPrev.dirty = true; + if (!firstTime && CheckForRightSplice(tess, regPrev)) { + AddWinding(e, ePrev); + DeleteRegion(tess, regPrev); + if (!Mesh.__gl_meshDelete(ePrev)) throw new RuntimeException(); + } + firstTime = false; + regPrev = reg; + ePrev = e; + } + regPrev.dirty = true; + assert (regPrev.windingNumber - e.winding == reg.windingNumber); + + if (cleanUp) { + /* Check for intersections between newly adjacent edges. */ + WalkDirtyRegions(tess, regPrev); + } + } + + + static void CallCombine(GLUtessellatorImpl tess, GLUvertex isect, + Object[] data, float[] weights, boolean needed) { + double[] coords = new double[3]; + + /* Copy coord data in case the callback changes it. */ + coords[0] = isect.coords[0]; + coords[1] = isect.coords[1]; + coords[2] = isect.coords[2]; + + Object[] outData = new Object[1]; + tess.callCombineOrCombineData(coords, data, weights, outData); + isect.data = outData[0]; + if (isect.data == null) { + if (!needed) { + isect.data = data[0]; + } else if (!tess.fatalError) { + /* The only way fatal error is when two edges are found to intersect, + * but the user has not provided the callback necessary to handle + * generated intersection points. + */ + tess.callErrorOrErrorData(GLU_TESS_NEED_COMBINE_CALLBACK); + tess.fatalError = true; + } + } + } + + static void SpliceMergeVertices(GLUtessellatorImpl tess, GLUhalfEdge e1, + GLUhalfEdge e2) +/* + * Two vertices with idential coordinates are combined into one. + * e1.Org is kept, while e2.Org is discarded. + */ { + Object[] data = new Object[4]; + float[] weights = new float[]{0.5f, 0.5f, 0.0f, 0.0f}; + + data[0] = e1.Org.data; + data[1] = e2.Org.data; + CallCombine(tess, e1.Org, data, weights, false); + if (!Mesh.__gl_meshSplice(e1, e2)) throw new RuntimeException(); + } + + static void VertexWeights(GLUvertex isect, GLUvertex org, GLUvertex dst, + float[] weights) +/* + * Find some weights which describe how the intersection vertex is + * a linear combination of "org" and "dest". Each of the two edges + * which generated "isect" is allocated 50% of the weight; each edge + * splits the weight between its org and dst according to the + * relative distance to "isect". + */ { + double t1 = Geom.VertL1dist(org, isect); + double t2 = Geom.VertL1dist(dst, isect); + + weights[0] = (float) (0.5 * t2 / (t1 + t2)); + weights[1] = (float) (0.5 * t1 / (t1 + t2)); + isect.coords[0] += weights[0] * org.coords[0] + weights[1] * dst.coords[0]; + isect.coords[1] += weights[0] * org.coords[1] + weights[1] * dst.coords[1]; + isect.coords[2] += weights[0] * org.coords[2] + weights[1] * dst.coords[2]; + } + + + static void GetIntersectData(GLUtessellatorImpl tess, GLUvertex isect, + GLUvertex orgUp, GLUvertex dstUp, + GLUvertex orgLo, GLUvertex dstLo) +/* + * We've computed a new intersection point, now we need a "data" pointer + * from the user so that we can refer to this new vertex in the + * rendering callbacks. + */ { + Object[] data = new Object[4]; + float[] weights = new float[4]; + float[] weights1 = new float[2]; + float[] weights2 = new float[2]; + + data[0] = orgUp.data; + data[1] = dstUp.data; + data[2] = orgLo.data; + data[3] = dstLo.data; + + isect.coords[0] = isect.coords[1] = isect.coords[2] = 0; + VertexWeights(isect, orgUp, dstUp, weights1); + VertexWeights(isect, orgLo, dstLo, weights2); + System.arraycopy(weights1, 0, weights, 0, 2); + System.arraycopy(weights2, 0, weights, 2, 2); + + CallCombine(tess, isect, data, weights, true); + } + + static boolean CheckForRightSplice(GLUtessellatorImpl tess, ActiveRegion regUp) +/* + * Check the upper and lower edge of "regUp", to make sure that the + * eUp.Org is above eLo, or eLo.Org is below eUp (depending on which + * origin is leftmost). + * + * The main purpose is to splice right-going edges with the same + * dest vertex and nearly identical slopes (ie. we can't distinguish + * the slopes numerically). However the splicing can also help us + * to recover from numerical errors. For example, suppose at one + * point we checked eUp and eLo, and decided that eUp.Org is barely + * above eLo. Then later, we split eLo into two edges (eg. from + * a splice operation like this one). This can change the result of + * our test so that now eUp.Org is incident to eLo, or barely below it. + * We must correct this condition to maintain the dictionary invariants. + * + * One possibility is to check these edges for intersection again + * (ie. CheckForIntersect). This is what we do if possible. However + * CheckForIntersect requires that tess.event lies between eUp and eLo, + * so that it has something to fall back on when the intersection + * calculation gives us an unusable answer. So, for those cases where + * we can't check for intersection, this routine fixes the problem + * by just splicing the offending vertex into the other edge. + * This is a guaranteed solution, no matter how degenerate things get. + * Basically this is a combinatorial solution to a numerical problem. + */ { + ActiveRegion regLo = RegionBelow(regUp); + GLUhalfEdge eUp = regUp.eUp; + GLUhalfEdge eLo = regLo.eUp; + + if (Geom.VertLeq(eUp.Org, eLo.Org)) { + if (Geom.EdgeSign(eLo.Sym.Org, eUp.Org, eLo.Org) > 0) return false; + + /* eUp.Org appears to be below eLo */ + if (!Geom.VertEq(eUp.Org, eLo.Org)) { + /* Splice eUp.Org into eLo */ + if (Mesh.__gl_meshSplitEdge(eLo.Sym) == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eUp, eLo.Sym.Lnext)) throw new RuntimeException(); + regUp.dirty = regLo.dirty = true; + + } else if (eUp.Org != eLo.Org) { + /* merge the two vertices, discarding eUp.Org */ + tess.pq.pqDelete(eUp.Org.pqHandle); /* __gl_pqSortDelete */ + SpliceMergeVertices(tess, eLo.Sym.Lnext, eUp); + } + } else { + if (Geom.EdgeSign(eUp.Sym.Org, eLo.Org, eUp.Org) < 0) return false; + + /* eLo.Org appears to be above eUp, so splice eLo.Org into eUp */ + RegionAbove(regUp).dirty = regUp.dirty = true; + if (Mesh.__gl_meshSplitEdge(eUp.Sym) == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eLo.Sym.Lnext, eUp)) throw new RuntimeException(); + } + return true; + } + + static boolean CheckForLeftSplice(GLUtessellatorImpl tess, ActiveRegion regUp) +/* + * Check the upper and lower edge of "regUp", to make sure that the + * eUp.Sym.Org is above eLo, or eLo.Sym.Org is below eUp (depending on which + * destination is rightmost). + * + * Theoretically, this should always be true. However, splitting an edge + * into two pieces can change the results of previous tests. For example, + * suppose at one point we checked eUp and eLo, and decided that eUp.Sym.Org + * is barely above eLo. Then later, we split eLo into two edges (eg. from + * a splice operation like this one). This can change the result of + * the test so that now eUp.Sym.Org is incident to eLo, or barely below it. + * We must correct this condition to maintain the dictionary invariants + * (otherwise new edges might get inserted in the wrong place in the + * dictionary, and bad stuff will happen). + * + * We fix the problem by just splicing the offending vertex into the + * other edge. + */ { + ActiveRegion regLo = RegionBelow(regUp); + GLUhalfEdge eUp = regUp.eUp; + GLUhalfEdge eLo = regLo.eUp; + GLUhalfEdge e; + + assert (!Geom.VertEq(eUp.Sym.Org, eLo.Sym.Org)); + + if (Geom.VertLeq(eUp.Sym.Org, eLo.Sym.Org)) { + if (Geom.EdgeSign(eUp.Sym.Org, eLo.Sym.Org, eUp.Org) < 0) return false; + + /* eLo.Sym.Org is above eUp, so splice eLo.Sym.Org into eUp */ + RegionAbove(regUp).dirty = regUp.dirty = true; + e = Mesh.__gl_meshSplitEdge(eUp); + if (e == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eLo.Sym, e)) throw new RuntimeException(); + e.Lface.inside = regUp.inside; + } else { + if (Geom.EdgeSign(eLo.Sym.Org, eUp.Sym.Org, eLo.Org) > 0) return false; + + /* eUp.Sym.Org is below eLo, so splice eUp.Sym.Org into eLo */ + regUp.dirty = regLo.dirty = true; + e = Mesh.__gl_meshSplitEdge(eLo); + if (e == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eUp.Lnext, eLo.Sym)) throw new RuntimeException(); + e.Sym.Lface.inside = regUp.inside; + } + return true; + } + + + static boolean CheckForIntersect(GLUtessellatorImpl tess, ActiveRegion regUp) +/* + * Check the upper and lower edges of the given region to see if + * they intersect. If so, create the intersection and add it + * to the data structures. + * + * Returns true if adding the new intersection resulted in a recursive + * call to AddRightEdges(); in this case all "dirty" regions have been + * checked for intersections, and possibly regUp has been deleted. + */ { + ActiveRegion regLo = RegionBelow(regUp); + GLUhalfEdge eUp = regUp.eUp; + GLUhalfEdge eLo = regLo.eUp; + GLUvertex orgUp = eUp.Org; + GLUvertex orgLo = eLo.Org; + GLUvertex dstUp = eUp.Sym.Org; + GLUvertex dstLo = eLo.Sym.Org; + double tMinUp, tMaxLo; + GLUvertex isect = new GLUvertex(); + GLUvertex orgMin; + GLUhalfEdge e; + + assert (!Geom.VertEq(dstLo, dstUp)); + assert (Geom.EdgeSign(dstUp, tess.event, orgUp) <= 0); + assert (Geom.EdgeSign(dstLo, tess.event, orgLo) >= 0); + assert (orgUp != tess.event && orgLo != tess.event); + assert (!regUp.fixUpperEdge && !regLo.fixUpperEdge); + + if (orgUp == orgLo) return false; /* right endpoints are the same */ + + tMinUp = Math.min(orgUp.t, dstUp.t); + tMaxLo = Math.max(orgLo.t, dstLo.t); + if (tMinUp > tMaxLo) return false; /* t ranges do not overlap */ + + if (Geom.VertLeq(orgUp, orgLo)) { + if (Geom.EdgeSign(dstLo, orgUp, orgLo) > 0) return false; + } else { + if (Geom.EdgeSign(dstUp, orgLo, orgUp) < 0) return false; + } + + /* At this point the edges intersect, at least marginally */ + DebugEvent(tess); + + Geom.EdgeIntersect(dstUp, orgUp, dstLo, orgLo, isect); + /* The following properties are guaranteed: */ + assert (Math.min(orgUp.t, dstUp.t) <= isect.t); + assert (isect.t <= Math.max(orgLo.t, dstLo.t)); + assert (Math.min(dstLo.s, dstUp.s) <= isect.s); + assert (isect.s <= Math.max(orgLo.s, orgUp.s)); + + if (Geom.VertLeq(isect, tess.event)) { + /* The intersection point lies slightly to the left of the sweep line, + * so move it until it''s slightly to the right of the sweep line. + * (If we had perfect numerical precision, this would never happen + * in the first place). The easiest and safest thing to do is + * replace the intersection by tess.event. + */ + isect.s = tess.event.s; + isect.t = tess.event.t; + } + /* Similarly, if the computed intersection lies to the right of the + * rightmost origin (which should rarely happen), it can cause + * unbelievable inefficiency on sufficiently degenerate inputs. + * (If you have the test program, try running test54.d with the + * "X zoom" option turned on). + */ + orgMin = Geom.VertLeq(orgUp, orgLo) ? orgUp : orgLo; + if (Geom.VertLeq(orgMin, isect)) { + isect.s = orgMin.s; + isect.t = orgMin.t; + } + + if (Geom.VertEq(isect, orgUp) || Geom.VertEq(isect, orgLo)) { + /* Easy case -- intersection at one of the right endpoints */ + CheckForRightSplice(tess, regUp); + return false; + } + + if ((!Geom.VertEq(dstUp, tess.event) + && Geom.EdgeSign(dstUp, tess.event, isect) >= 0) + || (!Geom.VertEq(dstLo, tess.event) + && Geom.EdgeSign(dstLo, tess.event, isect) <= 0)) { + /* Very unusual -- the new upper or lower edge would pass on the + * wrong side of the sweep event, or through it. This can happen + * due to very small numerical errors in the intersection calculation. + */ + if (dstLo == tess.event) { + /* Splice dstLo into eUp, and process the new region(s) */ + if (Mesh.__gl_meshSplitEdge(eUp.Sym) == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eLo.Sym, eUp)) throw new RuntimeException(); + regUp = TopLeftRegion(regUp); + if (regUp == null) throw new RuntimeException(); + eUp = RegionBelow(regUp).eUp; + FinishLeftRegions(tess, RegionBelow(regUp), regLo); + AddRightEdges(tess, regUp, eUp.Sym.Lnext, eUp, eUp, true); + return true; + } + if (dstUp == tess.event) { + /* Splice dstUp into eLo, and process the new region(s) */ + if (Mesh.__gl_meshSplitEdge(eLo.Sym) == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eUp.Lnext, eLo.Sym.Lnext)) throw new RuntimeException(); + regLo = regUp; + regUp = TopRightRegion(regUp); + e = RegionBelow(regUp).eUp.Sym.Onext; + regLo.eUp = eLo.Sym.Lnext; + eLo = FinishLeftRegions(tess, regLo, null); + AddRightEdges(tess, regUp, eLo.Onext, eUp.Sym.Onext, e, true); + return true; + } + /* Special case: called from ConnectRightVertex. If either + * edge passes on the wrong side of tess.event, split it + * (and wait for ConnectRightVertex to splice it appropriately). + */ + if (Geom.EdgeSign(dstUp, tess.event, isect) >= 0) { + RegionAbove(regUp).dirty = regUp.dirty = true; + if (Mesh.__gl_meshSplitEdge(eUp.Sym) == null) throw new RuntimeException(); + eUp.Org.s = tess.event.s; + eUp.Org.t = tess.event.t; + } + if (Geom.EdgeSign(dstLo, tess.event, isect) <= 0) { + regUp.dirty = regLo.dirty = true; + if (Mesh.__gl_meshSplitEdge(eLo.Sym) == null) throw new RuntimeException(); + eLo.Org.s = tess.event.s; + eLo.Org.t = tess.event.t; + } + /* leave the rest for ConnectRightVertex */ + return false; + } + + /* General case -- split both edges, splice into new vertex. + * When we do the splice operation, the order of the arguments is + * arbitrary as far as correctness goes. However, when the operation + * creates a new face, the work done is proportional to the size of + * the new face. We expect the faces in the processed part of + * the mesh (ie. eUp.Lface) to be smaller than the faces in the + * unprocessed original contours (which will be eLo.Sym.Lnext.Lface). + */ + if (Mesh.__gl_meshSplitEdge(eUp.Sym) == null) throw new RuntimeException(); + if (Mesh.__gl_meshSplitEdge(eLo.Sym) == null) throw new RuntimeException(); + if (!Mesh.__gl_meshSplice(eLo.Sym.Lnext, eUp)) throw new RuntimeException(); + eUp.Org.s = isect.s; + eUp.Org.t = isect.t; + eUp.Org.pqHandle = tess.pq.pqInsert(eUp.Org); /* __gl_pqSortInsert */ + if (eUp.Org.pqHandle == Long.MAX_VALUE) { + tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */ + tess.pq = null; + throw new RuntimeException(); + } + GetIntersectData(tess, eUp.Org, orgUp, dstUp, orgLo, dstLo); + RegionAbove(regUp).dirty = regUp.dirty = regLo.dirty = true; + return false; + } + + static void WalkDirtyRegions(GLUtessellatorImpl tess, ActiveRegion regUp) +/* + * When the upper or lower edge of any region changes, the region is + * marked "dirty". This routine walks through all the dirty regions + * and makes sure that the dictionary invariants are satisfied + * (see the comments at the beginning of this file). Of course + * new dirty regions can be created as we make changes to restore + * the invariants. + */ { + ActiveRegion regLo = RegionBelow(regUp); + GLUhalfEdge eUp, eLo; + + for (; ;) { + /* Find the lowest dirty region (we walk from the bottom up). */ + while (regLo.dirty) { + regUp = regLo; + regLo = RegionBelow(regLo); + } + if (!regUp.dirty) { + regLo = regUp; + regUp = RegionAbove(regUp); + if (regUp == null || !regUp.dirty) { + /* We've walked all the dirty regions */ + return; + } + } + regUp.dirty = false; + eUp = regUp.eUp; + eLo = regLo.eUp; + + if (eUp.Sym.Org != eLo.Sym.Org) { + /* Check that the edge ordering is obeyed at the Dst vertices. */ + if (CheckForLeftSplice(tess, regUp)) { + + /* If the upper or lower edge was marked fixUpperEdge, then + * we no longer need it (since these edges are needed only for + * vertices which otherwise have no right-going edges). + */ + if (regLo.fixUpperEdge) { + DeleteRegion(tess, regLo); + if (!Mesh.__gl_meshDelete(eLo)) throw new RuntimeException(); + regLo = RegionBelow(regUp); + eLo = regLo.eUp; + } else if (regUp.fixUpperEdge) { + DeleteRegion(tess, regUp); + if (!Mesh.__gl_meshDelete(eUp)) throw new RuntimeException(); + regUp = RegionAbove(regLo); + eUp = regUp.eUp; + } + } + } + if (eUp.Org != eLo.Org) { + if (eUp.Sym.Org != eLo.Sym.Org + && !regUp.fixUpperEdge && !regLo.fixUpperEdge + && (eUp.Sym.Org == tess.event || eLo.Sym.Org == tess.event)) { + /* When all else fails in CheckForIntersect(), it uses tess.event + * as the intersection location. To make this possible, it requires + * that tess.event lie between the upper and lower edges, and also + * that neither of these is marked fixUpperEdge (since in the worst + * case it might splice one of these edges into tess.event, and + * violate the invariant that fixable edges are the only right-going + * edge from their associated vertex). + */ + if (CheckForIntersect(tess, regUp)) { + /* WalkDirtyRegions() was called recursively; we're done */ + return; + } + } else { + /* Even though we can't use CheckForIntersect(), the Org vertices + * may violate the dictionary edge ordering. Check and correct this. + */ + CheckForRightSplice(tess, regUp); + } + } + if (eUp.Org == eLo.Org && eUp.Sym.Org == eLo.Sym.Org) { + /* A degenerate loop consisting of only two edges -- delete it. */ + AddWinding(eLo, eUp); + DeleteRegion(tess, regUp); + if (!Mesh.__gl_meshDelete(eUp)) throw new RuntimeException(); + regUp = RegionAbove(regLo); + } + } + } + + + static void ConnectRightVertex(GLUtessellatorImpl tess, ActiveRegion regUp, + GLUhalfEdge eBottomLeft) +/* + * Purpose: connect a "right" vertex vEvent (one where all edges go left) + * to the unprocessed portion of the mesh. Since there are no right-going + * edges, two regions (one above vEvent and one below) are being merged + * into one. "regUp" is the upper of these two regions. + * + * There are two reasons for doing this (adding a right-going edge): + * - if the two regions being merged are "inside", we must add an edge + * to keep them separated (the combined region would not be monotone). + * - in any case, we must leave some record of vEvent in the dictionary, + * so that we can merge vEvent with features that we have not seen yet. + * For example, maybe there is a vertical edge which passes just to + * the right of vEvent; we would like to splice vEvent into this edge. + * + * However, we don't want to connect vEvent to just any vertex. We don''t + * want the new edge to cross any other edges; otherwise we will create + * intersection vertices even when the input data had no self-intersections. + * (This is a bad thing; if the user's input data has no intersections, + * we don't want to generate any false intersections ourselves.) + * + * Our eventual goal is to connect vEvent to the leftmost unprocessed + * vertex of the combined region (the union of regUp and regLo). + * But because of unseen vertices with all right-going edges, and also + * new vertices which may be created by edge intersections, we don''t + * know where that leftmost unprocessed vertex is. In the meantime, we + * connect vEvent to the closest vertex of either chain, and mark the region + * as "fixUpperEdge". This flag says to delete and reconnect this edge + * to the next processed vertex on the boundary of the combined region. + * Quite possibly the vertex we connected to will turn out to be the + * closest one, in which case we won''t need to make any changes. + */ { + GLUhalfEdge eNew; + GLUhalfEdge eTopLeft = eBottomLeft.Onext; + ActiveRegion regLo = RegionBelow(regUp); + GLUhalfEdge eUp = regUp.eUp; + GLUhalfEdge eLo = regLo.eUp; + boolean degenerate = false; + + if (eUp.Sym.Org != eLo.Sym.Org) { + CheckForIntersect(tess, regUp); + } + + /* Possible new degeneracies: upper or lower edge of regUp may pass + * through vEvent, or may coincide with new intersection vertex + */ + if (Geom.VertEq(eUp.Org, tess.event)) { + if (!Mesh.__gl_meshSplice(eTopLeft.Sym.Lnext, eUp)) throw new RuntimeException(); + regUp = TopLeftRegion(regUp); + if (regUp == null) throw new RuntimeException(); + eTopLeft = RegionBelow(regUp).eUp; + FinishLeftRegions(tess, RegionBelow(regUp), regLo); + degenerate = true; + } + if (Geom.VertEq(eLo.Org, tess.event)) { + if (!Mesh.__gl_meshSplice(eBottomLeft, eLo.Sym.Lnext)) throw new RuntimeException(); + eBottomLeft = FinishLeftRegions(tess, regLo, null); + degenerate = true; + } + if (degenerate) { + AddRightEdges(tess, regUp, eBottomLeft.Onext, eTopLeft, eTopLeft, true); + return; + } + + /* Non-degenerate situation -- need to add a temporary, fixable edge. + * Connect to the closer of eLo.Org, eUp.Org. + */ + if (Geom.VertLeq(eLo.Org, eUp.Org)) { + eNew = eLo.Sym.Lnext; + } else { + eNew = eUp; + } + eNew = Mesh.__gl_meshConnect(eBottomLeft.Onext.Sym, eNew); + if (eNew == null) throw new RuntimeException(); + + /* Prevent cleanup, otherwise eNew might disappear before we've even + * had a chance to mark it as a temporary edge. + */ + AddRightEdges(tess, regUp, eNew, eNew.Onext, eNew.Onext, false); + eNew.Sym.activeRegion.fixUpperEdge = true; + WalkDirtyRegions(tess, regUp); + } + +/* Because vertices at exactly the same location are merged together + * before we process the sweep event, some degenerate cases can't occur. + * However if someone eventually makes the modifications required to + * merge features which are close together, the cases below marked + * TOLERANCE_NONZERO will be useful. They were debugged before the + * code to merge identical vertices in the main loop was added. + */ + private static final boolean TOLERANCE_NONZERO = false; + + static void ConnectLeftDegenerate(GLUtessellatorImpl tess, + ActiveRegion regUp, GLUvertex vEvent) +/* + * The event vertex lies exacty on an already-processed edge or vertex. + * Adding the new vertex involves splicing it into the already-processed + * part of the mesh. + */ { + GLUhalfEdge e, eTopLeft, eTopRight, eLast; + ActiveRegion reg; + + e = regUp.eUp; + if (Geom.VertEq(e.Org, vEvent)) { + /* e.Org is an unprocessed vertex - just combine them, and wait + * for e.Org to be pulled from the queue + */ + assert (TOLERANCE_NONZERO); + SpliceMergeVertices(tess, e, vEvent.anEdge); + return; + } + + if (!Geom.VertEq(e.Sym.Org, vEvent)) { + /* General case -- splice vEvent into edge e which passes through it */ + if (Mesh.__gl_meshSplitEdge(e.Sym) == null) throw new RuntimeException(); + if (regUp.fixUpperEdge) { + /* This edge was fixable -- delete unused portion of original edge */ + if (!Mesh.__gl_meshDelete(e.Onext)) throw new RuntimeException(); + regUp.fixUpperEdge = false; + } + if (!Mesh.__gl_meshSplice(vEvent.anEdge, e)) throw new RuntimeException(); + SweepEvent(tess, vEvent); /* recurse */ + return; + } + + /* vEvent coincides with e.Sym.Org, which has already been processed. + * Splice in the additional right-going edges. + */ + assert (TOLERANCE_NONZERO); + regUp = TopRightRegion(regUp); + reg = RegionBelow(regUp); + eTopRight = reg.eUp.Sym; + eTopLeft = eLast = eTopRight.Onext; + if (reg.fixUpperEdge) { + /* Here e.Sym.Org has only a single fixable edge going right. + * We can delete it since now we have some real right-going edges. + */ + assert (eTopLeft != eTopRight); /* there are some left edges too */ + DeleteRegion(tess, reg); + if (!Mesh.__gl_meshDelete(eTopRight)) throw new RuntimeException(); + eTopRight = eTopLeft.Sym.Lnext; + } + if (!Mesh.__gl_meshSplice(vEvent.anEdge, eTopRight)) throw new RuntimeException(); + if (!Geom.EdgeGoesLeft(eTopLeft)) { + /* e.Sym.Org had no left-going edges -- indicate this to AddRightEdges() */ + eTopLeft = null; + } + AddRightEdges(tess, regUp, eTopRight.Onext, eLast, eTopLeft, true); + } + + + static void ConnectLeftVertex(GLUtessellatorImpl tess, GLUvertex vEvent) +/* + * Purpose: connect a "left" vertex (one where both edges go right) + * to the processed portion of the mesh. Let R be the active region + * containing vEvent, and let U and L be the upper and lower edge + * chains of R. There are two possibilities: + * + * - the normal case: split R into two regions, by connecting vEvent to + * the rightmost vertex of U or L lying to the left of the sweep line + * + * - the degenerate case: if vEvent is close enough to U or L, we + * merge vEvent into that edge chain. The subcases are: + * - merging with the rightmost vertex of U or L + * - merging with the active edge of U or L + * - merging with an already-processed portion of U or L + */ { + ActiveRegion regUp, regLo, reg; + GLUhalfEdge eUp, eLo, eNew; + ActiveRegion tmp = new ActiveRegion(); + + /* assert ( vEvent.anEdge.Onext.Onext == vEvent.anEdge ); */ + + /* Get a pointer to the active region containing vEvent */ + tmp.eUp = vEvent.anEdge.Sym; + /* __GL_DICTLISTKEY */ /* __gl_dictListSearch */ + regUp = (ActiveRegion) Dict.dictKey(Dict.dictSearch(tess.dict, tmp)); + regLo = RegionBelow(regUp); + eUp = regUp.eUp; + eLo = regLo.eUp; + + /* Try merging with U or L first */ + if (Geom.EdgeSign(eUp.Sym.Org, vEvent, eUp.Org) == 0) { + ConnectLeftDegenerate(tess, regUp, vEvent); + return; + } + + /* Connect vEvent to rightmost processed vertex of either chain. + * e.Sym.Org is the vertex that we will connect to vEvent. + */ + reg = Geom.VertLeq(eLo.Sym.Org, eUp.Sym.Org) ? regUp : regLo; + + if (regUp.inside || reg.fixUpperEdge) { + if (reg == regUp) { + eNew = Mesh.__gl_meshConnect(vEvent.anEdge.Sym, eUp.Lnext); + if (eNew == null) throw new RuntimeException(); + } else { + GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(eLo.Sym.Onext.Sym, vEvent.anEdge); + if (tempHalfEdge == null) throw new RuntimeException(); + + eNew = tempHalfEdge.Sym; + } + if (reg.fixUpperEdge) { + if (!FixUpperEdge(reg, eNew)) throw new RuntimeException(); + } else { + ComputeWinding(tess, AddRegionBelow(tess, regUp, eNew)); + } + SweepEvent(tess, vEvent); + } else { + /* The new vertex is in a region which does not belong to the polygon. + * We don''t need to connect this vertex to the rest of the mesh. + */ + AddRightEdges(tess, regUp, vEvent.anEdge, vEvent.anEdge, null, true); + } + } + + + static void SweepEvent(GLUtessellatorImpl tess, GLUvertex vEvent) +/* + * Does everything necessary when the sweep line crosses a vertex. + * Updates the mesh and the edge dictionary. + */ { + ActiveRegion regUp, reg; + GLUhalfEdge e, eTopLeft, eBottomLeft; + + tess.event = vEvent; /* for access in EdgeLeq() */ + DebugEvent(tess); + + /* Check if this vertex is the right endpoint of an edge that is + * already in the dictionary. In this case we don't need to waste + * time searching for the location to insert new edges. + */ + e = vEvent.anEdge; + while (e.activeRegion == null) { + e = e.Onext; + if (e == vEvent.anEdge) { + /* All edges go right -- not incident to any processed edges */ + ConnectLeftVertex(tess, vEvent); + return; + } + } + + /* Processing consists of two phases: first we "finish" all the + * active regions where both the upper and lower edges terminate + * at vEvent (ie. vEvent is closing off these regions). + * We mark these faces "inside" or "outside" the polygon according + * to their winding number, and delete the edges from the dictionary. + * This takes care of all the left-going edges from vEvent. + */ + regUp = TopLeftRegion(e.activeRegion); + if (regUp == null) throw new RuntimeException(); + reg = RegionBelow(regUp); + eTopLeft = reg.eUp; + eBottomLeft = FinishLeftRegions(tess, reg, null); + + /* Next we process all the right-going edges from vEvent. This + * involves adding the edges to the dictionary, and creating the + * associated "active regions" which record information about the + * regions between adjacent dictionary edges. + */ + if (eBottomLeft.Onext == eTopLeft) { + /* No right-going edges -- add a temporary "fixable" edge */ + ConnectRightVertex(tess, regUp, eBottomLeft); + } else { + AddRightEdges(tess, regUp, eBottomLeft.Onext, eTopLeft, eTopLeft, true); + } + } + + +/* Make the sentinel coordinates big enough that they will never be + * merged with real input features. (Even with the largest possible + * input contour and the maximum tolerance of 1.0, no merging will be + * done with coordinates larger than 3 * GLU_TESS_MAX_COORD). + */ + private static final double SENTINEL_COORD = (4.0 * GLU_TESS_MAX_COORD); + + static void AddSentinel(GLUtessellatorImpl tess, double t) +/* + * We add two sentinel edges above and below all other edges, + * to avoid special cases at the top and bottom. + */ { + GLUhalfEdge e; + ActiveRegion reg = new ActiveRegion(); + //if (reg == null) throw new RuntimeException(); + + e = Mesh.__gl_meshMakeEdge(tess.mesh); + if (e == null) throw new RuntimeException(); + + e.Org.s = SENTINEL_COORD; + e.Org.t = t; + e.Sym.Org.s = -SENTINEL_COORD; + e.Sym.Org.t = t; + tess.event = e.Sym.Org; /* initialize it */ + + reg.eUp = e; + reg.windingNumber = 0; + reg.inside = false; + reg.fixUpperEdge = false; + reg.sentinel = true; + reg.dirty = false; + reg.nodeUp = Dict.dictInsert(tess.dict, reg); /* __gl_dictListInsertBefore */ + if (reg.nodeUp == null) throw new RuntimeException(); + } + + + static void InitEdgeDict(final GLUtessellatorImpl tess) +/* + * We maintain an ordering of edge intersections with the sweep line. + * This order is maintained in a dynamic dictionary. + */ { + /* __gl_dictListNewDict */ + tess.dict = Dict.dictNewDict(tess, new Dict.DictLeq() { + public boolean leq(Object frame, Object key1, Object key2) { + return EdgeLeq(tess, (ActiveRegion) key1, (ActiveRegion) key2); + } + }); + if (tess.dict == null) throw new RuntimeException(); + + AddSentinel(tess, -SENTINEL_COORD); + AddSentinel(tess, SENTINEL_COORD); + } + + + static void DoneEdgeDict(GLUtessellatorImpl tess) { + ActiveRegion reg; + int fixedEdges = 0; + + /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */ + while ((reg = (ActiveRegion) Dict.dictKey(Dict.dictMin(tess.dict))) != null) { + /* + * At the end of all processing, the dictionary should contain + * only the two sentinel edges, plus at most one "fixable" edge + * created by ConnectRightVertex(). + */ + if (!reg.sentinel) { + assert (reg.fixUpperEdge); + assert (++fixedEdges == 1); + } + assert (reg.windingNumber == 0); + DeleteRegion(tess, reg); +/* __gl_meshDelete( reg.eUp );*/ + } + Dict.dictDeleteDict(tess.dict); /* __gl_dictListDeleteDict */ + } + + + static void RemoveDegenerateEdges(GLUtessellatorImpl tess) +/* + * Remove zero-length edges, and contours with fewer than 3 vertices. + */ { + GLUhalfEdge e, eNext, eLnext; + GLUhalfEdge eHead = tess.mesh.eHead; + + /*LINTED*/ + for (e = eHead.next; e != eHead; e = eNext) { + eNext = e.next; + eLnext = e.Lnext; + + if (Geom.VertEq(e.Org, e.Sym.Org) && e.Lnext.Lnext != e) { + /* Zero-length edge, contour has at least 3 edges */ + + SpliceMergeVertices(tess, eLnext, e); /* deletes e.Org */ + if (!Mesh.__gl_meshDelete(e)) throw new RuntimeException(); /* e is a self-loop */ + e = eLnext; + eLnext = e.Lnext; + } + if (eLnext.Lnext == e) { + /* Degenerate contour (one or two edges) */ + + if (eLnext != e) { + if (eLnext == eNext || eLnext == eNext.Sym) { + eNext = eNext.next; + } + if (!Mesh.__gl_meshDelete(eLnext)) throw new RuntimeException(); + } + if (e == eNext || e == eNext.Sym) { + eNext = eNext.next; + } + if (!Mesh.__gl_meshDelete(e)) throw new RuntimeException(); + } + } + } + + static boolean InitPriorityQ(GLUtessellatorImpl tess) +/* + * Insert all vertices into the priority queue which determines the + * order in which vertices cross the sweep line. + */ { + PriorityQ pq; + GLUvertex v, vHead; + + /* __gl_pqSortNewPriorityQ */ + pq = tess.pq = PriorityQ.pqNewPriorityQ(new PriorityQ.Leq() { + public boolean leq(Object key1, Object key2) { + return Geom.VertLeq(((GLUvertex) key1), (GLUvertex) key2); + } + }); + if (pq == null) return false; + + vHead = tess.mesh.vHead; + for (v = vHead.next; v != vHead; v = v.next) { + v.pqHandle = pq.pqInsert(v); /* __gl_pqSortInsert */ + if (v.pqHandle == Long.MAX_VALUE) break; + } + if (v != vHead || !pq.pqInit()) { /* __gl_pqSortInit */ + tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */ + tess.pq = null; + return false; + } + + return true; + } + + + static void DonePriorityQ(GLUtessellatorImpl tess) { + tess.pq.pqDeletePriorityQ(); /* __gl_pqSortDeletePriorityQ */ + } + + + static boolean RemoveDegenerateFaces(GLUmesh mesh) +/* + * Delete any degenerate faces with only two edges. WalkDirtyRegions() + * will catch almost all of these, but it won't catch degenerate faces + * produced by splice operations on already-processed edges. + * The two places this can happen are in FinishLeftRegions(), when + * we splice in a "temporary" edge produced by ConnectRightVertex(), + * and in CheckForLeftSplice(), where we splice already-processed + * edges to ensure that our dictionary invariants are not violated + * by numerical errors. + * + * In both these cases it is *very* dangerous to delete the offending + * edge at the time, since one of the routines further up the stack + * will sometimes be keeping a pointer to that edge. + */ { + GLUface f, fNext; + GLUhalfEdge e; + + /*LINTED*/ + for (f = mesh.fHead.next; f != mesh.fHead; f = fNext) { + fNext = f.next; + e = f.anEdge; + assert (e.Lnext != e); + + if (e.Lnext.Lnext == e) { + /* A face with only two edges */ + AddWinding(e.Onext, e); + if (!Mesh.__gl_meshDelete(e)) return false; + } + } + return true; + } + + public static boolean __gl_computeInterior(GLUtessellatorImpl tess) +/* + * __gl_computeInterior( tess ) computes the planar arrangement specified + * by the given contours, and further subdivides this arrangement + * into regions. Each region is marked "inside" if it belongs + * to the polygon, according to the rule given by tess.windingRule. + * Each interior region is guaranteed be monotone. + */ { + GLUvertex v, vNext; + + tess.fatalError = false; + + /* Each vertex defines an event for our sweep line. Start by inserting + * all the vertices in a priority queue. Events are processed in + * lexicographic order, ie. + * + * e1 < e2 iff e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y) + */ + RemoveDegenerateEdges(tess); + if (!InitPriorityQ(tess)) return false; /* if error */ + InitEdgeDict(tess); + + /* __gl_pqSortExtractMin */ + while ((v = (GLUvertex) tess.pq.pqExtractMin()) != null) { + for (; ;) { + vNext = (GLUvertex) tess.pq.pqMinimum(); /* __gl_pqSortMinimum */ + if (vNext == null || !Geom.VertEq(vNext, v)) break; + + /* Merge together all vertices at exactly the same location. + * This is more efficient than processing them one at a time, + * simplifies the code (see ConnectLeftDegenerate), and is also + * important for correct handling of certain degenerate cases. + * For example, suppose there are two identical edges A and B + * that belong to different contours (so without this code they would + * be processed by separate sweep events). Suppose another edge C + * crosses A and B from above. When A is processed, we split it + * at its intersection point with C. However this also splits C, + * so when we insert B we may compute a slightly different + * intersection point. This might leave two edges with a small + * gap between them. This kind of error is especially obvious + * when using boundary extraction (GLU_TESS_BOUNDARY_ONLY). + */ + vNext = (GLUvertex) tess.pq.pqExtractMin(); /* __gl_pqSortExtractMin*/ + SpliceMergeVertices(tess, v.anEdge, vNext.anEdge); + } + SweepEvent(tess, v); + } + + /* Set tess.event for debugging purposes */ + /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */ + tess.event = ((ActiveRegion) Dict.dictKey(Dict.dictMin(tess.dict))).eUp.Org; + DebugEvent(tess); + DoneEdgeDict(tess); + DonePriorityQ(tess); + + if (!RemoveDegenerateFaces(tess.mesh)) return false; + Mesh.__gl_meshCheckMesh(tess.mesh); + + return true; + } +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/TessMono.java b/src/main/java/org/lwjglx/util/glu/tessellation/TessMono.java new file mode 100644 index 0000000..94547b1 --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/TessMono.java @@ -0,0 +1,241 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class TessMono { +/* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region + * (what else would it do??) The region must consist of a single + * loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this + * case means that any vertical line intersects the interior of the + * region in a single interval. + * + * Tessellation consists of adding interior edges (actually pairs of + * half-edges), to split the region into non-overlapping triangles. + * + * The basic idea is explained in Preparata and Shamos (which I don''t + * have handy right now), although their implementation is more + * complicated than this one. The are two edge chains, an upper chain + * and a lower chain. We process all vertices from both chains in order, + * from right to left. + * + * The algorithm ensures that the following invariant holds after each + * vertex is processed: the untessellated region consists of two + * chains, where one chain (say the upper) is a single edge, and + * the other chain is concave. The left vertex of the single edge + * is always to the left of all vertices in the concave chain. + * + * Each step consists of adding the rightmost unprocessed vertex to one + * of the two chains, and forming a fan of triangles from the rightmost + * of two chain endpoints. Determining whether we can add each triangle + * to the fan is a simple orientation test. By making the fan as large + * as possible, we restore the invariant (check it yourself). + */ + static boolean __gl_meshTessellateMonoRegion(GLUface face) { + GLUhalfEdge up, lo; + + /* All edges are oriented CCW around the boundary of the region. + * First, find the half-edge whose origin vertex is rightmost. + * Since the sweep goes from left to right, face->anEdge should + * be close to the edge we want. + */ + up = face.anEdge; + assert (up.Lnext != up && up.Lnext.Lnext != up); + + for (; Geom.VertLeq(up.Sym.Org, up.Org); up = up.Onext.Sym) + ; + for (; Geom.VertLeq(up.Org, up.Sym.Org); up = up.Lnext) + ; + lo = up.Onext.Sym; + + while (up.Lnext != lo) { + if (Geom.VertLeq(up.Sym.Org, lo.Org)) { + /* up.Sym.Org is on the left. It is safe to form triangles from lo.Org. + * The EdgeGoesLeft test guarantees progress even when some triangles + * are CW, given that the upper and lower chains are truly monotone. + */ + while (lo.Lnext != up && (Geom.EdgeGoesLeft(lo.Lnext) + || Geom.EdgeSign(lo.Org, lo.Sym.Org, lo.Lnext.Sym.Org) <= 0)) { + GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(lo.Lnext, lo); + if (tempHalfEdge == null) return false; + lo = tempHalfEdge.Sym; + } + lo = lo.Onext.Sym; + } else { + /* lo.Org is on the left. We can make CCW triangles from up.Sym.Org. */ + while (lo.Lnext != up && (Geom.EdgeGoesRight(up.Onext.Sym) + || Geom.EdgeSign(up.Sym.Org, up.Org, up.Onext.Sym.Org) >= 0)) { + GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(up, up.Onext.Sym); + if (tempHalfEdge == null) return false; + up = tempHalfEdge.Sym; + } + up = up.Lnext; + } + } + + /* Now lo.Org == up.Sym.Org == the leftmost vertex. The remaining region + * can be tessellated in a fan from this leftmost vertex. + */ + assert (lo.Lnext != up); + while (lo.Lnext.Lnext != up) { + GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(lo.Lnext, lo); + if (tempHalfEdge == null) return false; + lo = tempHalfEdge.Sym; + } + + return true; + } + + +/* __gl_meshTessellateInterior( mesh ) tessellates each region of + * the mesh which is marked "inside" the polygon. Each such region + * must be monotone. + */ + public static boolean __gl_meshTessellateInterior(GLUmesh mesh) { + GLUface f, next; + + /*LINTED*/ + for (f = mesh.fHead.next; f != mesh.fHead; f = next) { + /* Make sure we don''t try to tessellate the new triangles. */ + next = f.next; + if (f.inside) { + if (!__gl_meshTessellateMonoRegion(f)) return false; + } + } + + return true; + } + + +/* __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces + * which are not marked "inside" the polygon. Since further mesh operations + * on NULL faces are not allowed, the main purpose is to clean up the + * mesh so that exterior loops are not represented in the data structure. + */ + public static void __gl_meshDiscardExterior(GLUmesh mesh) { + GLUface f, next; + + /*LINTED*/ + for (f = mesh.fHead.next; f != mesh.fHead; f = next) { + /* Since f will be destroyed, save its next pointer. */ + next = f.next; + if (!f.inside) { + Mesh.__gl_meshZapFace(f); + } + } + } + +// private static final int MARKED_FOR_DELETION = 0x7fffffff; + +/* __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the + * winding numbers on all edges so that regions marked "inside" the + * polygon have a winding number of "value", and regions outside + * have a winding number of 0. + * + * If keepOnlyBoundary is TRUE, it also deletes all edges which do not + * separate an interior region from an exterior one. + */ + public static boolean __gl_meshSetWindingNumber(GLUmesh mesh, int value, boolean keepOnlyBoundary) { + GLUhalfEdge e, eNext; + + for (e = mesh.eHead.next; e != mesh.eHead; e = eNext) { + eNext = e.next; + if (e.Sym.Lface.inside != e.Lface.inside) { + + /* This is a boundary edge (one side is interior, one is exterior). */ + e.winding = (e.Lface.inside) ? value : -value; + } else { + + /* Both regions are interior, or both are exterior. */ + if (!keepOnlyBoundary) { + e.winding = 0; + } else { + if (!Mesh.__gl_meshDelete(e)) return false; + } + } + } + return true; + } + +} diff --git a/src/main/java/org/lwjglx/util/glu/tessellation/TessState.java b/src/main/java/org/lwjglx/util/glu/tessellation/TessState.java new file mode 100644 index 0000000..e0d4d7d --- /dev/null +++ b/src/main/java/org/lwjglx/util/glu/tessellation/TessState.java @@ -0,0 +1,91 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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. + */ + +/* +* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** NOTE: The Original Code (as defined below) has been licensed to Sun +** Microsystems, Inc. ("Sun") under the SGI Free Software License B +** (Version 1.1), shown above ("SGI License"). Pursuant to Section +** 3.2(3) of the SGI License, Sun is distributing the Covered Code to +** you under an alternative license ("Alternative License"). This +** Alternative License includes all of the provisions of the SGI License +** except that Section 2.2 and 11 are omitted. Any differences between +** the Alternative License and the SGI License are offered solely by Sun +** and not by SGI. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package org.lwjglx.util.glu.tessellation; + +class TessState { + public static final int T_DORMANT = 0; + public static final int T_IN_POLYGON = 1; + public static final int T_IN_CONTOUR = 2; +} diff --git a/src/main/java/org/lwjglx/util/vector/Matrix.java b/src/main/java/org/lwjglx/util/vector/Matrix.java new file mode 100644 index 0000000..162fc34 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Matrix.java @@ -0,0 +1,134 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Base class for matrices. When a matrix is constructed it will be the identity + * matrix unless otherwise stated. + * + * @author cix_foo + * @version $Revision: 3418 $ + * $Id: Matrix.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public abstract class Matrix implements Serializable { + + /** + * Constructor for Matrix. + */ + protected Matrix() { + super(); + } + + /** + * Set this matrix to be the identity matrix. + * @return this + */ + public abstract Matrix setIdentity(); + + + /** + * Invert this matrix + * @return this + */ + public abstract Matrix invert(); + + + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public abstract Matrix load(FloatBuffer buf); + + + /** + * Load from a float buffer. The buffer stores the matrix in row major + * (mathematical) order. + * + * @param buf A float buffer to read from + * @return this + */ + public abstract Matrix loadTranspose(FloatBuffer buf); + + + /** + * Negate this matrix + * @return this + */ + public abstract Matrix negate(); + + + /** + * Store this matrix in a float buffer. The matrix is stored in column + * major (openGL) order. + * @param buf The buffer to store this matrix in + * @return this + */ + public abstract Matrix store(FloatBuffer buf); + + + /** + * Store this matrix in a float buffer. The matrix is stored in row + * major (maths) order. + * @param buf The buffer to store this matrix in + * @return this + */ + public abstract Matrix storeTranspose(FloatBuffer buf); + + + /** + * Transpose this matrix + * @return this + */ + public abstract Matrix transpose(); + + + /** + * Set this matrix to 0. + * @return this + */ + public abstract Matrix setZero(); + + + /** + * @return the determinant of the matrix + */ + public abstract float determinant(); + + +} diff --git a/src/main/java/org/lwjglx/util/vector/Matrix2f.java b/src/main/java/org/lwjglx/util/vector/Matrix2f.java new file mode 100644 index 0000000..98be10b --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Matrix2f.java @@ -0,0 +1,400 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Holds a 2x2 matrix + * + * @author cix_foo + * @version $Revision: 3799 $ + * $Id: Matrix2f.java 3799 2012-09-12 11:29:40Z kappa1 $ + */ + +public class Matrix2f extends Matrix implements Serializable { + + private static final long serialVersionUID = 1L; + + public float m00, m01, m10, m11; + + /** + * Constructor for Matrix2f. The matrix is initialised to the identity. + */ + public Matrix2f() { + setIdentity(); + } + + /** + * Constructor + */ + public Matrix2f(Matrix2f src) { + load(src); + } + + /** + * Load from another matrix + * @param src The source matrix + * @return this + */ + public Matrix2f load(Matrix2f src) { + return load(src, this); + } + + /** + * Copy the source matrix to the destination matrix. + * @param src The source matrix + * @param dest The destination matrix, or null if a new one should be created. + * @return The copied matrix + */ + public static Matrix2f load(Matrix2f src, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = src.m00; + dest.m01 = src.m01; + dest.m10 = src.m10; + dest.m11 = src.m11; + + return dest; + } + + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix load(FloatBuffer buf) { + + m00 = buf.get(); + m01 = buf.get(); + m10 = buf.get(); + m11 = buf.get(); + + return this; + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major + * (mathematical) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix loadTranspose(FloatBuffer buf) { + + m00 = buf.get(); + m10 = buf.get(); + m01 = buf.get(); + m11 = buf.get(); + + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in column + * major (openGL) order. + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m10); + buf.put(m11); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row + * major (maths) order. + * @param buf The buffer to store this matrix in + */ + public Matrix storeTranspose(FloatBuffer buf) { + buf.put(m00); + buf.put(m10); + buf.put(m01); + buf.put(m11); + return this; + } + + + + /** + * Add two matrices together and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = left.m00 + right.m00; + dest.m01 = left.m01 + right.m01; + dest.m10 = left.m10 + right.m10; + dest.m11 = left.m11 + right.m11; + + return dest; + } + + /** + * Subtract the right matrix from the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + + return dest; + } + + /** + * Multiply the right matrix by the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + float m00 = left.m00 * right.m00 + left.m10 * right.m01; + float m01 = left.m01 * right.m00 + left.m11 * right.m01; + float m10 = left.m00 * right.m10 + left.m10 * right.m11; + float m11 = left.m01 * right.m10 + left.m11 * right.m11; + + dest.m00 = m00; + dest.m01 = m01; + dest.m10 = m10; + dest.m11 = m11; + + return dest; + } + + /** + * Transform a Vector by a matrix and return the result in a destination + * vector. + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector + */ + public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) { + if (dest == null) + dest = new Vector2f(); + + float x = left.m00 * right.x + left.m10 * right.y; + float y = left.m01 * right.x + left.m11 * right.y; + + dest.x = x; + dest.y = y; + + return dest; + } + + /** + * Transpose this matrix + * @return this + */ + public Matrix transpose() { + return transpose(this); + } + + /** + * Transpose this matrix and place the result in another matrix. + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public Matrix2f transpose(Matrix2f dest) { + return transpose(this, dest); + } + + /** + * Transpose the source matrix and place the result in the destination matrix. + * @param src The source matrix or null if a new matrix is to be created + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public static Matrix2f transpose(Matrix2f src, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + float m01 = src.m10; + float m10 = src.m01; + + dest.m01 = m01; + dest.m10 = m10; + + return dest; + } + + /** + * Invert this matrix + * @return this if successful, null otherwise + */ + public Matrix invert() { + return invert(this, this); + } + + /** + * Invert the source matrix and place the result in the destination matrix. + * @param src The source matrix to be inverted + * @param dest The destination matrix or null if a new matrix is to be created + * @return The inverted matrix, or null if source can't be reverted. + */ + public static Matrix2f invert(Matrix2f src, Matrix2f dest) { + /* + *inv(A) = 1/det(A) * adj(A); + */ + + float determinant = src.determinant(); + if (determinant != 0) { + if (dest == null) + dest = new Matrix2f(); + float determinant_inv = 1f/determinant; + float t00 = src.m11*determinant_inv; + float t01 = -src.m01*determinant_inv; + float t11 = src.m00*determinant_inv; + float t10 = -src.m10*determinant_inv; + + dest.m00 = t00; + dest.m01 = t01; + dest.m10 = t10; + dest.m11 = t11; + return dest; + } else + return null; + } + + /** + * Returns a string representation of this matrix + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(m00).append(' ').append(m10).append(' ').append('\n'); + buf.append(m01).append(' ').append(m11).append(' ').append('\n'); + return buf.toString(); + } + + /** + * Negate this matrix + * @return this + */ + public Matrix negate() { + return negate(this); + } + + /** + * Negate this matrix and stash the result in another matrix. + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public Matrix2f negate(Matrix2f dest) { + return negate(this, dest); + } + + /** + * Negate the source matrix and stash the result in the destination matrix. + * @param src The source matrix to be negated + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public static Matrix2f negate(Matrix2f src, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = -src.m00; + dest.m01 = -src.m01; + dest.m10 = -src.m10; + dest.m11 = -src.m11; + + return dest; + } + + /** + * Set this matrix to be the identity matrix. + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set the source matrix to be the identity matrix. + * @param src The matrix to set to the identity. + * @return The source matrix + */ + public static Matrix2f setIdentity(Matrix2f src) { + src.m00 = 1.0f; + src.m01 = 0.0f; + src.m10 = 0.0f; + src.m11 = 1.0f; + return src; + } + + /** + * Set this matrix to 0. + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + + public static Matrix2f setZero(Matrix2f src) { + src.m00 = 0.0f; + src.m01 = 0.0f; + src.m10 = 0.0f; + src.m11 = 0.0f; + return src; + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Matrix#determinant() + */ + public float determinant() { + return m00 * m11 - m01*m10; + } +} diff --git a/src/main/java/org/lwjglx/util/vector/Matrix3f.java b/src/main/java/org/lwjglx/util/vector/Matrix3f.java new file mode 100644 index 0000000..ad810b0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Matrix3f.java @@ -0,0 +1,510 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Holds a 3x3 matrix. + * + * @author cix_foo + * @version $Revision: 3799 $ + * $Id: Matrix3f.java 3799 2012-09-12 11:29:40Z kappa1 $ + */ + +public class Matrix3f extends Matrix implements Serializable { + + private static final long serialVersionUID = 1L; + + public float m00, + m01, + m02, + m10, + m11, + m12, + m20, + m21, + m22; + + /** + * Constructor for Matrix3f. Matrix is initialised to the identity. + */ + public Matrix3f() { + super(); + setIdentity(); + } + + /** + * Load from another matrix + * @param src The source matrix + * @return this + */ + public Matrix3f load(Matrix3f src) { + return load(src, this); + } + + /** + * Copy source matrix to destination matrix + * @param src The source matrix + * @param dest The destination matrix, or null of a new matrix is to be created + * @return The copied matrix + */ + public static Matrix3f load(Matrix3f src, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = src.m00; + dest.m10 = src.m10; + dest.m20 = src.m20; + dest.m01 = src.m01; + dest.m11 = src.m11; + dest.m21 = src.m21; + dest.m02 = src.m02; + dest.m12 = src.m12; + dest.m22 = src.m22; + + return dest; + } + + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix load(FloatBuffer buf) { + + m00 = buf.get(); + m01 = buf.get(); + m02 = buf.get(); + m10 = buf.get(); + m11 = buf.get(); + m12 = buf.get(); + m20 = buf.get(); + m21 = buf.get(); + m22 = buf.get(); + + return this; + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major + * (maths) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix loadTranspose(FloatBuffer buf) { + + m00 = buf.get(); + m10 = buf.get(); + m20 = buf.get(); + m01 = buf.get(); + m11 = buf.get(); + m21 = buf.get(); + m02 = buf.get(); + m12 = buf.get(); + m22 = buf.get(); + + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in column + * major (openGL) order. + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m20); + buf.put(m21); + buf.put(m22); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row + * major (maths) order. + * @param buf The buffer to store this matrix in + */ + public Matrix storeTranspose(FloatBuffer buf) { + buf.put(m00); + buf.put(m10); + buf.put(m20); + buf.put(m01); + buf.put(m11); + buf.put(m21); + buf.put(m02); + buf.put(m12); + buf.put(m22); + return this; + } + + /** + * Add two matrices together and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = left.m00 + right.m00; + dest.m01 = left.m01 + right.m01; + dest.m02 = left.m02 + right.m02; + dest.m10 = left.m10 + right.m10; + dest.m11 = left.m11 + right.m11; + dest.m12 = left.m12 + right.m12; + dest.m20 = left.m20 + right.m20; + dest.m21 = left.m21 + right.m21; + dest.m22 = left.m22 + right.m22; + + return dest; + } + + /** + * Subtract the right matrix from the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m02 = left.m02 - right.m02; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + dest.m12 = left.m12 - right.m12; + dest.m20 = left.m20 - right.m20; + dest.m21 = left.m21 - right.m21; + dest.m22 = left.m22 - right.m22; + + return dest; + } + + /** + * Multiply the right matrix by the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + float m00 = + left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02; + float m01 = + left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02; + float m02 = + left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02; + float m10 = + left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12; + float m11 = + left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12; + float m12 = + left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12; + float m20 = + left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22; + float m21 = + left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22; + float m22 = + left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + + return dest; + } + + /** + * Transform a Vector by a matrix and return the result in a destination + * vector. + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector + */ + public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) { + if (dest == null) + dest = new Vector3f(); + + float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z; + float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z; + float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z; + + dest.x = x; + dest.y = y; + dest.z = z; + + return dest; + } + + /** + * Transpose this matrix + * @return this + */ + public Matrix transpose() { + return transpose(this, this); + } + + /** + * Transpose this matrix and place the result in another matrix + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public Matrix3f transpose(Matrix3f dest) { + return transpose(this, dest); + } + + /** + * Transpose the source matrix and place the result into the destination matrix + * @param src The source matrix to be transposed + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public static Matrix3f transpose(Matrix3f src, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + float m00 = src.m00; + float m01 = src.m10; + float m02 = src.m20; + float m10 = src.m01; + float m11 = src.m11; + float m12 = src.m21; + float m20 = src.m02; + float m21 = src.m12; + float m22 = src.m22; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + return dest; + } + + /** + * @return the determinant of the matrix + */ + public float determinant() { + float f = + m00 * (m11 * m22 - m12 * m21) + + m01 * (m12 * m20 - m10 * m22) + + m02 * (m10 * m21 - m11 * m20); + return f; + } + + /** + * Returns a string representation of this matrix + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append('\n'); + buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append('\n'); + buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append('\n'); + return buf.toString(); + } + + /** + * Invert this matrix + * @return this if successful, null otherwise + */ + public Matrix invert() { + return invert(this, this); + } + + /** + * Invert the source matrix and put the result into the destination matrix + * @param src The source matrix to be inverted + * @param dest The destination matrix, or null if a new one is to be created + * @return The inverted matrix if successful, null otherwise + */ + public static Matrix3f invert(Matrix3f src, Matrix3f dest) { + float determinant = src.determinant(); + + if (determinant != 0) { + if (dest == null) + dest = new Matrix3f(); + /* do it the ordinary way + * + * inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix) + * + * m00 m01 m02 + * m10 m11 m12 + * m20 m21 m22 + */ + float determinant_inv = 1f/determinant; + + // get the conjugate matrix + float t00 = src.m11 * src.m22 - src.m12* src.m21; + float t01 = - src.m10 * src.m22 + src.m12 * src.m20; + float t02 = src.m10 * src.m21 - src.m11 * src.m20; + float t10 = - src.m01 * src.m22 + src.m02 * src.m21; + float t11 = src.m00 * src.m22 - src.m02 * src.m20; + float t12 = - src.m00 * src.m21 + src.m01 * src.m20; + float t20 = src.m01 * src.m12 - src.m02 * src.m11; + float t21 = -src.m00 * src.m12 + src.m02 * src.m10; + float t22 = src.m00 * src.m11 - src.m01 * src.m10; + + dest.m00 = t00*determinant_inv; + dest.m11 = t11*determinant_inv; + dest.m22 = t22*determinant_inv; + dest.m01 = t10*determinant_inv; + dest.m10 = t01*determinant_inv; + dest.m20 = t02*determinant_inv; + dest.m02 = t20*determinant_inv; + dest.m12 = t21*determinant_inv; + dest.m21 = t12*determinant_inv; + return dest; + } else + return null; + } + + + /** + * Negate this matrix + * @return this + */ + public Matrix negate() { + return negate(this); + } + + /** + * Negate this matrix and place the result in a destination matrix. + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public Matrix3f negate(Matrix3f dest) { + return negate(this, dest); + } + + /** + * Negate the source matrix and place the result in the destination matrix. + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public static Matrix3f negate(Matrix3f src, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = -src.m00; + dest.m01 = -src.m02; + dest.m02 = -src.m01; + dest.m10 = -src.m10; + dest.m11 = -src.m12; + dest.m12 = -src.m11; + dest.m20 = -src.m20; + dest.m21 = -src.m22; + dest.m22 = -src.m21; + return dest; + } + + /** + * Set this matrix to be the identity matrix. + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set the matrix to be the identity matrix. + * @param m The matrix to be set to the identity + * @return m + */ + public static Matrix3f setIdentity(Matrix3f m) { + m.m00 = 1.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m10 = 0.0f; + m.m11 = 1.0f; + m.m12 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 1.0f; + return m; + } + + /** + * Set this matrix to 0. + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + + /** + * Set the matrix matrix to 0. + * @param m The matrix to be set to 0 + * @return m + */ + public static Matrix3f setZero(Matrix3f m) { + m.m00 = 0.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m10 = 0.0f; + m.m11 = 0.0f; + m.m12 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 0.0f; + return m; + } +} diff --git a/src/main/java/org/lwjglx/util/vector/Matrix4f.java b/src/main/java/org/lwjglx/util/vector/Matrix4f.java new file mode 100644 index 0000000..0fc772d --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Matrix4f.java @@ -0,0 +1,849 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * Holds a 4x4 float matrix. + * + * @author foo + */ +public class Matrix4f extends Matrix implements Serializable { + private static final long serialVersionUID = 1L; + + public float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; + + /** + * Construct a new matrix, initialized to the identity. + */ + public Matrix4f() { + super(); + setIdentity(); + } + + public Matrix4f(final Matrix4f src) { + super(); + load(src); + } + + /** + * Returns a string representation of this matrix + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append(m30).append('\n'); + buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append(m31).append('\n'); + buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append(m32).append('\n'); + buf.append(m03).append(' ').append(m13).append(' ').append(m23).append(' ').append(m33).append('\n'); + return buf.toString(); + } + + /** + * Set this matrix to be the identity matrix. + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set the given matrix to be the identity matrix. + * @param m The matrix to set to the identity + * @return m + */ + public static Matrix4f setIdentity(Matrix4f m) { + m.m00 = 1.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m03 = 0.0f; + m.m10 = 0.0f; + m.m11 = 1.0f; + m.m12 = 0.0f; + m.m13 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 1.0f; + m.m23 = 0.0f; + m.m30 = 0.0f; + m.m31 = 0.0f; + m.m32 = 0.0f; + m.m33 = 1.0f; + + return m; + } + + /** + * Set this matrix to 0. + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + + /** + * Set the given matrix to 0. + * @param m The matrix to set to 0 + * @return m + */ + public static Matrix4f setZero(Matrix4f m) { + m.m00 = 0.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m03 = 0.0f; + m.m10 = 0.0f; + m.m11 = 0.0f; + m.m12 = 0.0f; + m.m13 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 0.0f; + m.m23 = 0.0f; + m.m30 = 0.0f; + m.m31 = 0.0f; + m.m32 = 0.0f; + m.m33 = 0.0f; + + return m; + } + + /** + * Load from another matrix4f + * @param src The source matrix + * @return this + */ + public Matrix4f load(Matrix4f src) { + return load(src, this); + } + + /** + * Copy the source matrix to the destination matrix + * @param src The source matrix + * @param dest The destination matrix, or null of a new one is to be created + * @return The copied matrix + */ + public static Matrix4f load(Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + dest.m00 = src.m00; + dest.m01 = src.m01; + dest.m02 = src.m02; + dest.m03 = src.m03; + dest.m10 = src.m10; + dest.m11 = src.m11; + dest.m12 = src.m12; + dest.m13 = src.m13; + dest.m20 = src.m20; + dest.m21 = src.m21; + dest.m22 = src.m22; + dest.m23 = src.m23; + dest.m30 = src.m30; + dest.m31 = src.m31; + dest.m32 = src.m32; + dest.m33 = src.m33; + + return dest; + } + + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix load(FloatBuffer buf) { + + m00 = buf.get(); + m01 = buf.get(); + m02 = buf.get(); + m03 = buf.get(); + m10 = buf.get(); + m11 = buf.get(); + m12 = buf.get(); + m13 = buf.get(); + m20 = buf.get(); + m21 = buf.get(); + m22 = buf.get(); + m23 = buf.get(); + m30 = buf.get(); + m31 = buf.get(); + m32 = buf.get(); + m33 = buf.get(); + + return this; + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major + * (maths) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix loadTranspose(FloatBuffer buf) { + + m00 = buf.get(); + m10 = buf.get(); + m20 = buf.get(); + m30 = buf.get(); + m01 = buf.get(); + m11 = buf.get(); + m21 = buf.get(); + m31 = buf.get(); + m02 = buf.get(); + m12 = buf.get(); + m22 = buf.get(); + m32 = buf.get(); + m03 = buf.get(); + m13 = buf.get(); + m23 = buf.get(); + m33 = buf.get(); + + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in column + * major (openGL) order. + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m03); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m13); + buf.put(m20); + buf.put(m21); + buf.put(m22); + buf.put(m23); + buf.put(m30); + buf.put(m31); + buf.put(m32); + buf.put(m33); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row + * major (maths) order. + * @param buf The buffer to store this matrix in + */ + public Matrix storeTranspose(FloatBuffer buf) { + buf.put(m00); + buf.put(m10); + buf.put(m20); + buf.put(m30); + buf.put(m01); + buf.put(m11); + buf.put(m21); + buf.put(m31); + buf.put(m02); + buf.put(m12); + buf.put(m22); + buf.put(m32); + buf.put(m03); + buf.put(m13); + buf.put(m23); + buf.put(m33); + return this; + } + + /** + * Store the rotation portion of this matrix in a float buffer. The matrix is stored in column + * major (openGL) order. + * @param buf The buffer to store this matrix in + */ + public Matrix store3f(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m20); + buf.put(m21); + buf.put(m22); + return this; + } + + /** + * Add two matrices together and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix4f add(Matrix4f left, Matrix4f right, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m00 = left.m00 + right.m00; + dest.m01 = left.m01 + right.m01; + dest.m02 = left.m02 + right.m02; + dest.m03 = left.m03 + right.m03; + dest.m10 = left.m10 + right.m10; + dest.m11 = left.m11 + right.m11; + dest.m12 = left.m12 + right.m12; + dest.m13 = left.m13 + right.m13; + dest.m20 = left.m20 + right.m20; + dest.m21 = left.m21 + right.m21; + dest.m22 = left.m22 + right.m22; + dest.m23 = left.m23 + right.m23; + dest.m30 = left.m30 + right.m30; + dest.m31 = left.m31 + right.m31; + dest.m32 = left.m32 + right.m32; + dest.m33 = left.m33 + right.m33; + + return dest; + } + + /** + * Subtract the right matrix from the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix4f sub(Matrix4f left, Matrix4f right, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m02 = left.m02 - right.m02; + dest.m03 = left.m03 - right.m03; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + dest.m12 = left.m12 - right.m12; + dest.m13 = left.m13 - right.m13; + dest.m20 = left.m20 - right.m20; + dest.m21 = left.m21 - right.m21; + dest.m22 = left.m22 - right.m22; + dest.m23 = left.m23 - right.m23; + dest.m30 = left.m30 - right.m30; + dest.m31 = left.m31 - right.m31; + dest.m32 = left.m32 - right.m32; + dest.m33 = left.m33 - right.m33; + + return dest; + } + + /** + * Multiply the right matrix by the left and place the result in a third matrix. + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix4f mul(Matrix4f left, Matrix4f right, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + float m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02 + left.m30 * right.m03; + float m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02 + left.m31 * right.m03; + float m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02 + left.m32 * right.m03; + float m03 = left.m03 * right.m00 + left.m13 * right.m01 + left.m23 * right.m02 + left.m33 * right.m03; + float m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12 + left.m30 * right.m13; + float m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12 + left.m31 * right.m13; + float m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12 + left.m32 * right.m13; + float m13 = left.m03 * right.m10 + left.m13 * right.m11 + left.m23 * right.m12 + left.m33 * right.m13; + float m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22 + left.m30 * right.m23; + float m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22 + left.m31 * right.m23; + float m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22 + left.m32 * right.m23; + float m23 = left.m03 * right.m20 + left.m13 * right.m21 + left.m23 * right.m22 + left.m33 * right.m23; + float m30 = left.m00 * right.m30 + left.m10 * right.m31 + left.m20 * right.m32 + left.m30 * right.m33; + float m31 = left.m01 * right.m30 + left.m11 * right.m31 + left.m21 * right.m32 + left.m31 * right.m33; + float m32 = left.m02 * right.m30 + left.m12 * right.m31 + left.m22 * right.m32 + left.m32 * right.m33; + float m33 = left.m03 * right.m30 + left.m13 * right.m31 + left.m23 * right.m32 + left.m33 * right.m33; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m03 = m03; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m13 = m13; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + dest.m23 = m23; + dest.m30 = m30; + dest.m31 = m31; + dest.m32 = m32; + dest.m33 = m33; + + return dest; + } + + /** + * Transform a Vector by a matrix and return the result in a destination + * vector. + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector + */ + public static Vector4f transform(Matrix4f left, Vector4f right, Vector4f dest) { + if (dest == null) + dest = new Vector4f(); + + float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z + left.m30 * right.w; + float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z + left.m31 * right.w; + float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z + left.m32 * right.w; + float w = left.m03 * right.x + left.m13 * right.y + left.m23 * right.z + left.m33 * right.w; + + dest.x = x; + dest.y = y; + dest.z = z; + dest.w = w; + + return dest; + } + + /** + * Transpose this matrix + * @return this + */ + public Matrix transpose() { + return transpose(this); + } + + /** + * Translate this matrix + * @param vec The vector to translate by + * @return this + */ + public Matrix4f translate(Vector2f vec) { + return translate(vec, this); + } + + /** + * Translate this matrix + * @param vec The vector to translate by + * @return this + */ + public Matrix4f translate(Vector3f vec) { + return translate(vec, this); + } + + /** + * Scales this matrix + * @param vec The vector to scale by + * @return this + */ + public Matrix4f scale(Vector3f vec) { + return scale(vec, this, this); + } + + /** + * Scales the source matrix and put the result in the destination matrix + * @param vec The vector to scale by + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return The scaled matrix + */ + public static Matrix4f scale(Vector3f vec, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + dest.m00 = src.m00 * vec.x; + dest.m01 = src.m01 * vec.x; + dest.m02 = src.m02 * vec.x; + dest.m03 = src.m03 * vec.x; + dest.m10 = src.m10 * vec.y; + dest.m11 = src.m11 * vec.y; + dest.m12 = src.m12 * vec.y; + dest.m13 = src.m13 * vec.y; + dest.m20 = src.m20 * vec.z; + dest.m21 = src.m21 * vec.z; + dest.m22 = src.m22 * vec.z; + dest.m23 = src.m23 * vec.z; + return dest; + } + + /** + * Rotates the matrix around the given axis the specified angle + * @param angle the angle, in radians. + * @param axis The vector representing the rotation axis. Must be normalized. + * @return this + */ + public Matrix4f rotate(float angle, Vector3f axis) { + return rotate(angle, axis, this); + } + + /** + * Rotates the matrix around the given axis the specified angle + * @param angle the angle, in radians. + * @param axis The vector representing the rotation axis. Must be normalized. + * @param dest The matrix to put the result, or null if a new matrix is to be created + * @return The rotated matrix + */ + public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { + return rotate(angle, axis, this, dest); + } + + /** + * Rotates the source matrix around the given axis the specified angle and + * put the result in the destination matrix. + * @param angle the angle, in radians. + * @param axis The vector representing the rotation axis. Must be normalized. + * @param src The matrix to rotate + * @param dest The matrix to put the result, or null if a new matrix is to be created + * @return The rotated matrix + */ + public static Matrix4f rotate(float angle, Vector3f axis, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + float c = (float) Math.cos(angle); + float s = (float) Math.sin(angle); + float oneminusc = 1.0f - c; + float xy = axis.x*axis.y; + float yz = axis.y*axis.z; + float xz = axis.x*axis.z; + float xs = axis.x*s; + float ys = axis.y*s; + float zs = axis.z*s; + + float f00 = axis.x*axis.x*oneminusc+c; + float f01 = xy*oneminusc+zs; + float f02 = xz*oneminusc-ys; + // n[3] not used + float f10 = xy*oneminusc-zs; + float f11 = axis.y*axis.y*oneminusc+c; + float f12 = yz*oneminusc+xs; + // n[7] not used + float f20 = xz*oneminusc+ys; + float f21 = yz*oneminusc-xs; + float f22 = axis.z*axis.z*oneminusc+c; + + float t00 = src.m00 * f00 + src.m10 * f01 + src.m20 * f02; + float t01 = src.m01 * f00 + src.m11 * f01 + src.m21 * f02; + float t02 = src.m02 * f00 + src.m12 * f01 + src.m22 * f02; + float t03 = src.m03 * f00 + src.m13 * f01 + src.m23 * f02; + float t10 = src.m00 * f10 + src.m10 * f11 + src.m20 * f12; + float t11 = src.m01 * f10 + src.m11 * f11 + src.m21 * f12; + float t12 = src.m02 * f10 + src.m12 * f11 + src.m22 * f12; + float t13 = src.m03 * f10 + src.m13 * f11 + src.m23 * f12; + dest.m20 = src.m00 * f20 + src.m10 * f21 + src.m20 * f22; + dest.m21 = src.m01 * f20 + src.m11 * f21 + src.m21 * f22; + dest.m22 = src.m02 * f20 + src.m12 * f21 + src.m22 * f22; + dest.m23 = src.m03 * f20 + src.m13 * f21 + src.m23 * f22; + dest.m00 = t00; + dest.m01 = t01; + dest.m02 = t02; + dest.m03 = t03; + dest.m10 = t10; + dest.m11 = t11; + dest.m12 = t12; + dest.m13 = t13; + return dest; + } + + /** + * Translate this matrix and stash the result in another matrix + * @param vec The vector to translate by + * @param dest The destination matrix or null if a new matrix is to be created + * @return the translated matrix + */ + public Matrix4f translate(Vector3f vec, Matrix4f dest) { + return translate(vec, this, dest); + } + + /** + * Translate the source matrix and stash the result in the destination matrix + * @param vec The vector to translate by + * @param src The source matrix + * @param dest The destination matrix or null if a new matrix is to be created + * @return The translated matrix + */ + public static Matrix4f translate(Vector3f vec, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m30 += src.m00 * vec.x + src.m10 * vec.y + src.m20 * vec.z; + dest.m31 += src.m01 * vec.x + src.m11 * vec.y + src.m21 * vec.z; + dest.m32 += src.m02 * vec.x + src.m12 * vec.y + src.m22 * vec.z; + dest.m33 += src.m03 * vec.x + src.m13 * vec.y + src.m23 * vec.z; + + return dest; + } + + /** + * Translate this matrix and stash the result in another matrix + * @param vec The vector to translate by + * @param dest The destination matrix or null if a new matrix is to be created + * @return the translated matrix + */ + public Matrix4f translate(Vector2f vec, Matrix4f dest) { + return translate(vec, this, dest); + } + + /** + * Translate the source matrix and stash the result in the destination matrix + * @param vec The vector to translate by + * @param src The source matrix + * @param dest The destination matrix or null if a new matrix is to be created + * @return The translated matrix + */ + public static Matrix4f translate(Vector2f vec, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m30 += src.m00 * vec.x + src.m10 * vec.y; + dest.m31 += src.m01 * vec.x + src.m11 * vec.y; + dest.m32 += src.m02 * vec.x + src.m12 * vec.y; + dest.m33 += src.m03 * vec.x + src.m13 * vec.y; + + return dest; + } + + /** + * Transpose this matrix and place the result in another matrix + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public Matrix4f transpose(Matrix4f dest) { + return transpose(this, dest); + } + + /** + * Transpose the source matrix and place the result in the destination matrix + * @param src The source matrix + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public static Matrix4f transpose(Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + float m00 = src.m00; + float m01 = src.m10; + float m02 = src.m20; + float m03 = src.m30; + float m10 = src.m01; + float m11 = src.m11; + float m12 = src.m21; + float m13 = src.m31; + float m20 = src.m02; + float m21 = src.m12; + float m22 = src.m22; + float m23 = src.m32; + float m30 = src.m03; + float m31 = src.m13; + float m32 = src.m23; + float m33 = src.m33; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m03 = m03; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m13 = m13; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + dest.m23 = m23; + dest.m30 = m30; + dest.m31 = m31; + dest.m32 = m32; + dest.m33 = m33; + + return dest; + } + + /** + * @return the determinant of the matrix + */ + public float determinant() { + float f = + m00 + * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32) + - m13 * m22 * m31 + - m11 * m23 * m32 + - m12 * m21 * m33); + f -= m01 + * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32) + - m13 * m22 * m30 + - m10 * m23 * m32 + - m12 * m20 * m33); + f += m02 + * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31) + - m13 * m21 * m30 + - m10 * m23 * m31 + - m11 * m20 * m33); + f -= m03 + * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31) + - m12 * m21 * m30 + - m10 * m22 * m31 + - m11 * m20 * m32); + return f; + } + + /** + * Calculate the determinant of a 3x3 matrix + * @return result + */ + + private static float determinant3x3(float t00, float t01, float t02, + float t10, float t11, float t12, + float t20, float t21, float t22) + { + return t00 * (t11 * t22 - t12 * t21) + + t01 * (t12 * t20 - t10 * t22) + + t02 * (t10 * t21 - t11 * t20); + } + + /** + * Invert this matrix + * @return this if successful, null otherwise + */ + public Matrix invert() { + return invert(this, this); + } + + /** + * Invert the source matrix and put the result in the destination + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return The inverted matrix if successful, null otherwise + */ + public static Matrix4f invert(Matrix4f src, Matrix4f dest) { + float determinant = src.determinant(); + + if (determinant != 0) { + /* + * m00 m01 m02 m03 + * m10 m11 m12 m13 + * m20 m21 m22 m23 + * m30 m31 m32 m33 + */ + if (dest == null) + dest = new Matrix4f(); + float determinant_inv = 1f/determinant; + + // first row + float t00 = determinant3x3(src.m11, src.m12, src.m13, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33); + float t01 = -determinant3x3(src.m10, src.m12, src.m13, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33); + float t02 = determinant3x3(src.m10, src.m11, src.m13, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33); + float t03 = -determinant3x3(src.m10, src.m11, src.m12, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32); + // second row + float t10 = -determinant3x3(src.m01, src.m02, src.m03, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33); + float t11 = determinant3x3(src.m00, src.m02, src.m03, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33); + float t12 = -determinant3x3(src.m00, src.m01, src.m03, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33); + float t13 = determinant3x3(src.m00, src.m01, src.m02, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32); + // third row + float t20 = determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m31, src.m32, src.m33); + float t21 = -determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m30, src.m32, src.m33); + float t22 = determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m30, src.m31, src.m33); + float t23 = -determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m30, src.m31, src.m32); + // fourth row + float t30 = -determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m21, src.m22, src.m23); + float t31 = determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m20, src.m22, src.m23); + float t32 = -determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m20, src.m21, src.m23); + float t33 = determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m20, src.m21, src.m22); + + // transpose and divide by the determinant + dest.m00 = t00*determinant_inv; + dest.m11 = t11*determinant_inv; + dest.m22 = t22*determinant_inv; + dest.m33 = t33*determinant_inv; + dest.m01 = t10*determinant_inv; + dest.m10 = t01*determinant_inv; + dest.m20 = t02*determinant_inv; + dest.m02 = t20*determinant_inv; + dest.m12 = t21*determinant_inv; + dest.m21 = t12*determinant_inv; + dest.m03 = t30*determinant_inv; + dest.m30 = t03*determinant_inv; + dest.m13 = t31*determinant_inv; + dest.m31 = t13*determinant_inv; + dest.m32 = t23*determinant_inv; + dest.m23 = t32*determinant_inv; + return dest; + } else + return null; + } + + /** + * Negate this matrix + * @return this + */ + public Matrix negate() { + return negate(this); + } + + /** + * Negate this matrix and place the result in a destination matrix. + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public Matrix4f negate(Matrix4f dest) { + return negate(this, dest); + } + + /** + * Negate this matrix and place the result in a destination matrix. + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return The negated matrix + */ + public static Matrix4f negate(Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m00 = -src.m00; + dest.m01 = -src.m01; + dest.m02 = -src.m02; + dest.m03 = -src.m03; + dest.m10 = -src.m10; + dest.m11 = -src.m11; + dest.m12 = -src.m12; + dest.m13 = -src.m13; + dest.m20 = -src.m20; + dest.m21 = -src.m21; + dest.m22 = -src.m22; + dest.m23 = -src.m23; + dest.m30 = -src.m30; + dest.m31 = -src.m31; + dest.m32 = -src.m32; + dest.m33 = -src.m33; + + return dest; + } +} diff --git a/src/main/java/org/lwjglx/util/vector/Quaternion.java b/src/main/java/org/lwjglx/util/vector/Quaternion.java new file mode 100644 index 0000000..84c389b --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Quaternion.java @@ -0,0 +1,530 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * + * Quaternions for LWJGL! + * + * @author fbi + * @version $Revision: 3418 $ + * $Id: Quaternion.java 3418 2010-09-28 21:11:35Z spasi $ + */ + +import java.nio.FloatBuffer; + +public class Quaternion extends Vector implements ReadableVector4f { + private static final long serialVersionUID = 1L; + + public float x, y, z, w; + + /** + * C'tor. The quaternion will be initialized to the identity. + */ + public Quaternion() { + super(); + setIdentity(); + } + + /** + * C'tor + * + * @param src + */ + public Quaternion(ReadableVector4f src) { + set(src); + } + + /** + * C'tor + * + */ + public Quaternion(float x, float y, float z, float w) { + set(x, y, z, w); + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, + * float) + */ + public void set(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /** + * Load from another Vector4f + * + * @param src + * The source vector + * @return this + */ + public Quaternion set(ReadableVector4f src) { + x = src.getX(); + y = src.getY(); + z = src.getZ(); + w = src.getW(); + return this; + } + + /** + * Set this quaternion to the multiplication identity. + * @return this + */ + public Quaternion setIdentity() { + return setIdentity(this); + } + + /** + * Set the given quaternion to the multiplication identity. + * @param q The quaternion + * @return q + */ + public static Quaternion setIdentity(Quaternion q) { + q.x = 0; + q.y = 0; + q.z = 0; + q.w = 1; + return q; + } + + /** + * @return the length squared of the quaternion + */ + public float lengthSquared() { + return x * x + y * y + z * z + w * w; + } + + /** + * Normalise the source quaternion and place the result in another quaternion. + * + * @param src + * The source quaternion + * @param dest + * The destination quaternion, or null if a new quaternion is to be + * created + * @return The normalised quaternion + */ + public static Quaternion normalise(Quaternion src, Quaternion dest) { + float inv_l = 1f/src.length(); + + if (dest == null) + dest = new Quaternion(); + + dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l); + + return dest; + } + + /** + * Normalise this quaternion and place the result in another quaternion. + * + * @param dest + * The destination quaternion, or null if a new quaternion is to be + * created + * @return the normalised quaternion + */ + public Quaternion normalise(Quaternion dest) { + return normalise(this, dest); + } + + /** + * The dot product of two quaternions + * + * @param left + * The LHS quat + * @param right + * The RHS quat + * @return left dot right + */ + public static float dot(Quaternion left, Quaternion right) { + return left.x * right.x + left.y * right.y + left.z * right.z + left.w + * right.w; + } + + /** + * Calculate the conjugate of this quaternion and put it into the given one + * + * @param dest + * The quaternion which should be set to the conjugate of this + * quaternion + */ + public Quaternion negate(Quaternion dest) { + return negate(this, dest); + } + + /** + * Calculate the conjugate of this quaternion and put it into the given one + * + * @param src + * The source quaternion + * @param dest + * The quaternion which should be set to the conjugate of this + * quaternion + */ + public static Quaternion negate(Quaternion src, Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + + dest.x = -src.x; + dest.y = -src.y; + dest.z = -src.z; + dest.w = src.w; + + return dest; + } + + /** + * Calculate the conjugate of this quaternion + */ + public Vector negate() { + return negate(this, this); + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer) + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + w = buf.get(); + return this; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + return scale(scale, this, this); + } + + /** + * Scale the source quaternion by scale and put the result in the destination + * @param scale The amount to scale by + * @param src The source quaternion + * @param dest The destination quaternion, or null if a new quaternion is to be created + * @return The scaled quaternion + */ + public static Quaternion scale(float scale, Quaternion src, Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + dest.x = src.x * scale; + dest.y = src.y * scale; + dest.z = src.z * scale; + dest.w = src.w * scale; + return dest; + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer) + */ + public Vector store(FloatBuffer buf) { + buf.put(x); + buf.put(y); + buf.put(z); + buf.put(w); + + return this; + } + + /** + * @return x + */ + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /** + * Set X + * + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * + * @param y + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Set Z + * + * @param z + */ + public void setZ(float z) { + this.z = z; + } + + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; + } + + /** + * Set W + * + * @param w + */ + public void setW(float w) { + this.w = w; + } + + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getW() + */ + public float getW() { + return w; + } + + public String toString() { + return "Quaternion: " + x + " " + y + " " + z + " " + w; + } + + /** + * Sets the value of this quaternion to the quaternion product of + * quaternions left and right (this = left * right). Note that this is safe + * for aliasing (e.g. this can be left or right). + * + * @param left + * the first quaternion + * @param right + * the second quaternion + */ + public static Quaternion mul(Quaternion left, Quaternion right, + Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + dest.set(left.x * right.w + left.w * right.x + left.y * right.z + - left.z * right.y, left.y * right.w + left.w * right.y + + left.z * right.x - left.x * right.z, left.z * right.w + + left.w * right.z + left.x * right.y - left.y * right.x, + left.w * right.w - left.x * right.x - left.y * right.y + - left.z * right.z); + return dest; + } + + /** + * + * Multiplies quaternion left by the inverse of quaternion right and places + * the value into this quaternion. The value of both argument quaternions is + * preservered (this = left * right^-1). + * + * @param left + * the left quaternion + * @param right + * the right quaternion + */ + public static Quaternion mulInverse(Quaternion left, Quaternion right, + Quaternion dest) { + float n = right.lengthSquared(); + // zero-div may occur. + n = (n == 0.0 ? n : 1 / n); + // store on stack once for aliasing-safty + if (dest == null) + dest = new Quaternion(); + dest + .set((left.x * right.w - left.w * right.x - left.y + * right.z + left.z * right.y) + * n, (left.y * right.w - left.w * right.y - left.z + * right.x + left.x * right.z) + * n, (left.z * right.w - left.w * right.z - left.x + * right.y + left.y * right.x) + * n, (left.w * right.w + left.x * right.x + left.y + * right.y + left.z * right.z) + * n); + + return dest; + } + + /** + * Sets the value of this quaternion to the equivalent rotation of the + * Axis-Angle argument. + * + * @param a1 + * the axis-angle: (x,y,z) is the axis and w is the angle + */ + public final void setFromAxisAngle(Vector4f a1) { + x = a1.x; + y = a1.y; + z = a1.z; + float n = (float) Math.sqrt(x * x + y * y + z * z); + // zero-div may occur. + float s = (float) (Math.sin(0.5 * a1.w) / n); + x *= s; + y *= s; + z *= s; + w = (float) Math.cos(0.5 * a1.w); + } + + /** + * Sets the value of this quaternion using the rotational component of the + * passed matrix. + * + * @param m + * The matrix + * @return this + */ + public final Quaternion setFromMatrix(Matrix4f m) { + return setFromMatrix(m, this); + } + + /** + * Sets the value of the source quaternion using the rotational component of the + * passed matrix. + * + * @param m + * The source matrix + * @param q + * The destination quaternion, or null if a new quaternion is to be created + * @return q + */ + public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) { + return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, + m.m21, m.m22); + } + + /** + * Sets the value of this quaternion using the rotational component of the + * passed matrix. + * + * @param m + * The source matrix + */ + public final Quaternion setFromMatrix(Matrix3f m) { + return setFromMatrix(m, this); + } + + /** + * Sets the value of the source quaternion using the rotational component of the + * passed matrix. + * + * @param m + * The source matrix + * @param q + * The destination quaternion, or null if a new quaternion is to be created + * @return q + */ + public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) { + return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, + m.m21, m.m22); + } + + /** + * Private method to perform the matrix-to-quaternion conversion + */ + private Quaternion setFromMat(float m00, float m01, float m02, float m10, + float m11, float m12, float m20, float m21, float m22) { + + float s; + float tr = m00 + m11 + m22; + if (tr >= 0.0) { + s = (float) Math.sqrt(tr + 1.0); + w = s * 0.5f; + s = 0.5f / s; + x = (m21 - m12) * s; + y = (m02 - m20) * s; + z = (m10 - m01) * s; + } else { + float max = Math.max(Math.max(m00, m11), m22); + if (max == m00) { + s = (float) Math.sqrt(m00 - (m11 + m22) + 1.0); + x = s * 0.5f; + s = 0.5f / s; + y = (m01 + m10) * s; + z = (m20 + m02) * s; + w = (m21 - m12) * s; + } else if (max == m11) { + s = (float) Math.sqrt(m11 - (m22 + m00) + 1.0); + y = s * 0.5f; + s = 0.5f / s; + z = (m12 + m21) * s; + x = (m01 + m10) * s; + w = (m02 - m20) * s; + } else { + s = (float) Math.sqrt(m22 - (m00 + m11) + 1.0); + z = s * 0.5f; + s = 0.5f / s; + x = (m20 + m02) * s; + y = (m12 + m21) * s; + w = (m10 - m01) * s; + } + } + return this; + } +} diff --git a/src/main/java/org/lwjglx/util/vector/ReadableVector.java b/src/main/java/org/lwjglx/util/vector/ReadableVector.java new file mode 100644 index 0000000..c307834 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/ReadableVector.java @@ -0,0 +1,54 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.nio.FloatBuffer; + +/** + * @author foo + */ +public interface ReadableVector { + /** + * @return the length of the vector + */ + float length(); + /** + * @return the length squared of the vector + */ + float lengthSquared(); + /** + * Store this vector in a FloatBuffer + * @param buf The buffer to store it in, at the current position + * @return this + */ + Vector store(FloatBuffer buf); +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/vector/ReadableVector2f.java b/src/main/java/org/lwjglx/util/vector/ReadableVector2f.java new file mode 100644 index 0000000..d3deccf --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/ReadableVector2f.java @@ -0,0 +1,46 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * @author foo + */ +public interface ReadableVector2f extends ReadableVector { + /** + * @return x + */ + float getX(); + /** + * @return y + */ + float getY(); +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/vector/ReadableVector3f.java b/src/main/java/org/lwjglx/util/vector/ReadableVector3f.java new file mode 100644 index 0000000..881d316 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/ReadableVector3f.java @@ -0,0 +1,42 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * @author foo + */ +public interface ReadableVector3f extends ReadableVector2f { + /** + * @return z + */ + float getZ(); +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/vector/ReadableVector4f.java b/src/main/java/org/lwjglx/util/vector/ReadableVector4f.java new file mode 100644 index 0000000..c9579b7 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/ReadableVector4f.java @@ -0,0 +1,44 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * @author foo + */ +public interface ReadableVector4f extends ReadableVector3f { + + /** + * @return w + */ + float getW(); + +} diff --git a/src/main/java/org/lwjglx/util/vector/Vector.java b/src/main/java/org/lwjglx/util/vector/Vector.java new file mode 100644 index 0000000..d7bc883 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Vector.java @@ -0,0 +1,112 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Base class for vectors. + * + * @author cix_foo + * @version $Revision: 3418 $ + * $Id: Vector.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public abstract class Vector implements Serializable, ReadableVector { + + /** + * Constructor for Vector. + */ + protected Vector() { + super(); + } + + /** + * @return the length of the vector + */ + public final float length() { + return (float) Math.sqrt(lengthSquared()); + } + + + /** + * @return the length squared of the vector + */ + public abstract float lengthSquared(); + + /** + * Load this vector from a FloatBuffer + * @param buf The buffer to load it from, at the current position + * @return this + */ + public abstract Vector load(FloatBuffer buf); + + /** + * Negate a vector + * @return this + */ + public abstract Vector negate(); + + + /** + * Normalise this vector + * @return this + */ + public final Vector normalise() { + float len = length(); + if (len != 0.0f) { + float l = 1.0f / len; + return scale(l); + } else + throw new IllegalStateException("Zero length vector"); + } + + + /** + * Store this vector in a FloatBuffer + * @param buf The buffer to store it in, at the current position + * @return this + */ + public abstract Vector store(FloatBuffer buf); + + + /** + * Scale this vector + * @param scale The scale factor + * @return this + */ + public abstract Vector scale(float scale); + + + +} diff --git a/src/main/java/org/lwjglx/util/vector/Vector2f.java b/src/main/java/org/lwjglx/util/vector/Vector2f.java new file mode 100644 index 0000000..660a4e6 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Vector2f.java @@ -0,0 +1,290 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Holds a 2-tuple vector. + * + * @author cix_foo + * @version $Revision: 3418 $ + * $Id: Vector2f.java 3418 2010-09-28 21:11:35Z spasi $ + */ + +public class Vector2f extends Vector implements Serializable, ReadableVector2f, WritableVector2f { + + private static final long serialVersionUID = 1L; + + public float x, y; + + /** + * Constructor for Vector3f. + */ + public Vector2f() { + super(); + } + + /** + * Constructor + */ + public Vector2f(ReadableVector2f src) { + set(src); + } + + /** + * Constructor + */ + public Vector2f(float x, float y) { + set(x, y); + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /** + * Load from another Vector2f + * @param src The source vector + * @return this + */ + public Vector2f set(ReadableVector2f src) { + x = src.getX(); + y = src.getY(); + return this; + } + + /** + * @return the length squared of the vector + */ + public float lengthSquared() { + return x * x + y * y; + } + + /** + * Translate a vector + * @param x The translation in x + * @param y the translation in y + * @return this + */ + public Vector2f translate(float x, float y) { + this.x += x; + this.y += y; + return this; + } + + /** + * Negate a vector + * @return this + */ + public Vector negate() { + x = -x; + y = -y; + return this; + } + + /** + * Negate a vector and place the result in a destination vector. + * @param dest The destination vector or null if a new vector is to be created + * @return the negated vector + */ + public Vector2f negate(Vector2f dest) { + if (dest == null) + dest = new Vector2f(); + dest.x = -x; + dest.y = -y; + return dest; + } + + + /** + * Normalise this vector and place the result in another vector. + * @param dest The destination vector, or null if a new vector is to be created + * @return the normalised vector + */ + public Vector2f normalise(Vector2f dest) { + float l = length(); + + if (dest == null) + dest = new Vector2f(x / l, y / l); + else + dest.set(x / l, y / l); + + return dest; + } + + /** + * The dot product of two vectors is calculated as + * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector2f left, Vector2f right) { + return left.x * right.x + left.y * right.y; + } + + + + /** + * Calculate the angle between two vectors, in radians + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector2f a, Vector2f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float)Math.acos(dls); + } + + /** + * Add a vector to another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest) { + if (dest == null) + return new Vector2f(left.x + right.x, left.y + right.y); + else { + dest.set(left.x + right.x, left.y + right.y); + return dest; + } + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest) { + if (dest == null) + return new Vector2f(left.x - right.x, left.y - right.y); + else { + dest.set(left.x - right.x, left.y - right.y); + return dest; + } + } + + /** + * Store this vector in a FloatBuffer + * @param buf The buffer to store it in, at the current position + * @return this + */ + public Vector store(FloatBuffer buf) { + buf.put(x); + buf.put(y); + return this; + } + + /** + * Load this vector from a FloatBuffer + * @param buf The buffer to load it from, at the current position + * @return this + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + return this; + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + + x *= scale; + y *= scale; + + return this; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuilder sb = new StringBuilder(64); + + sb.append("Vector2f["); + sb.append(x); + sb.append(", "); + sb.append(y); + sb.append(']'); + return sb.toString(); + } + + /** + * @return x + */ + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /** + * Set X + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * @param y + */ + public final void setY(float y) { + this.y = y; + } + +} diff --git a/src/main/java/org/lwjglx/util/vector/Vector3f.java b/src/main/java/org/lwjglx/util/vector/Vector3f.java new file mode 100644 index 0000000..366bb99 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Vector3f.java @@ -0,0 +1,347 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Holds a 3-tuple vector. + * + * @author cix_foo + * @version $Revision: 3418 $ + * $Id: Vector3f.java 3418 2010-09-28 21:11:35Z spasi $ + */ + +public class Vector3f extends Vector implements Serializable, ReadableVector3f, WritableVector3f { + + private static final long serialVersionUID = 1L; + + public float x, y, z; + + /** + * Constructor for Vector3f. + */ + public Vector3f() { + super(); + } + + /** + * Constructor + */ + public Vector3f(ReadableVector3f src) { + set(src); + } + + /** + * Constructor + */ + public Vector3f(float x, float y, float z) { + set(x, y, z); + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Load from another Vector3f + * @param src The source vector + * @return this + */ + public Vector3f set(ReadableVector3f src) { + x = src.getX(); + y = src.getY(); + z = src.getZ(); + return this; + } + + /** + * @return the length squared of the vector + */ + public float lengthSquared() { + return x * x + y * y + z * z; + } + + /** + * Translate a vector + * @param x The translation in x + * @param y the translation in y + * @return this + */ + public Vector3f translate(float x, float y, float z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + /** + * Add a vector to another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) { + if (dest == null) + return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z); + else { + dest.set(left.x + right.x, left.y + right.y, left.z + right.z); + return dest; + } + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) { + if (dest == null) + return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z); + else { + dest.set(left.x - right.x, left.y - right.y, left.z - right.z); + return dest; + } + } + + /** + * The cross product of two vectors. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination result, or null if a new vector is to be created + * @return left cross right + */ + public static Vector3f cross( + Vector3f left, + Vector3f right, + Vector3f dest) + { + + if (dest == null) + dest = new Vector3f(); + + dest.set( + left.y * right.z - left.z * right.y, + right.x * left.z - right.z * left.x, + left.x * right.y - left.y * right.x + ); + + return dest; + } + + + + /** + * Negate a vector + * @return this + */ + public Vector negate() { + x = -x; + y = -y; + z = -z; + return this; + } + + /** + * Negate a vector and place the result in a destination vector. + * @param dest The destination vector or null if a new vector is to be created + * @return the negated vector + */ + public Vector3f negate(Vector3f dest) { + if (dest == null) + dest = new Vector3f(); + dest.x = -x; + dest.y = -y; + dest.z = -z; + return dest; + } + + + /** + * Normalise this vector and place the result in another vector. + * @param dest The destination vector, or null if a new vector is to be created + * @return the normalised vector + */ + public Vector3f normalise(Vector3f dest) { + float l = length(); + + if (dest == null) + dest = new Vector3f(x / l, y / l, z / l); + else + dest.set(x / l, y / l, z / l); + + return dest; + } + + /** + * The dot product of two vectors is calculated as + * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector3f left, Vector3f right) { + return left.x * right.x + left.y * right.y + left.z * right.z; + } + + /** + * Calculate the angle between two vectors, in radians + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector3f a, Vector3f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float)Math.acos(dls); + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#load(FloatBuffer) + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + return this; + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + + x *= scale; + y *= scale; + z *= scale; + + return this; + + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#store(FloatBuffer) + */ + public Vector store(FloatBuffer buf) { + + buf.put(x); + buf.put(y); + buf.put(z); + + return this; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuilder sb = new StringBuilder(64); + + sb.append("Vector3f["); + sb.append(x); + sb.append(", "); + sb.append(y); + sb.append(", "); + sb.append(z); + sb.append(']'); + return sb.toString(); + } + + /** + * @return x + */ + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /** + * Set X + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * @param y + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Set Z + * @param z + */ + public void setZ(float z) { + this.z = z; + } + + /* (Overrides) + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; + } +} diff --git a/src/main/java/org/lwjglx/util/vector/Vector4f.java b/src/main/java/org/lwjglx/util/vector/Vector4f.java new file mode 100644 index 0000000..9b258fc --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/Vector4f.java @@ -0,0 +1,340 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +import java.io.Serializable; +import java.nio.FloatBuffer; + +/** + * + * Holds a 4-tuple vector. + * + * @author cix_foo + * @version $Revision: 2983 $ + * $Id: Vector4f.java 2983 2008-04-07 18:36:09Z matzon $ + */ + +public class Vector4f extends Vector implements Serializable, ReadableVector4f, WritableVector4f { + + private static final long serialVersionUID = 1L; + + public float x, y, z, w; + + /** + * Constructor for Vector4f. + */ + public Vector4f() { + super(); + } + + /** + * Constructor + */ + public Vector4f(ReadableVector4f src) { + set(src); + } + + /** + * Constructor + */ + public Vector4f(float x, float y, float z, float w) { + set(x, y, z, w); + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /* (non-Javadoc) + * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float) + */ + public void set(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /** + * Load from another Vector4f + * @param src The source vector + * @return this + */ + public Vector4f set(ReadableVector4f src) { + x = src.getX(); + y = src.getY(); + z = src.getZ(); + w = src.getW(); + return this; + } + + /** + * @return the length squared of the vector + */ + public float lengthSquared() { + return x * x + y * y + z * z + w * w; + } + + /** + * Translate a vector + * @param x The translation in x + * @param y the translation in y + * @return this + */ + public Vector4f translate(float x, float y, float z, float w) { + this.x += x; + this.y += y; + this.z += z; + this.w += w; + return this; + } + + /** + * Add a vector to another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest) { + if (dest == null) + return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); + else { + dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); + return dest; + } + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest) { + if (dest == null) + return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); + else { + dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); + return dest; + } + } + + + /** + * Negate a vector + * @return this + */ + public Vector negate() { + x = -x; + y = -y; + z = -z; + w = -w; + return this; + } + + /** + * Negate a vector and place the result in a destination vector. + * @param dest The destination vector or null if a new vector is to be created + * @return the negated vector + */ + public Vector4f negate(Vector4f dest) { + if (dest == null) + dest = new Vector4f(); + dest.x = -x; + dest.y = -y; + dest.z = -z; + dest.w = -w; + return dest; + } + + + /** + * Normalise this vector and place the result in another vector. + * @param dest The destination vector, or null if a new vector is to be created + * @return the normalised vector + */ + public Vector4f normalise(Vector4f dest) { + float l = length(); + + if (dest == null) + dest = new Vector4f(x / l, y / l, z / l, w / l); + else + dest.set(x / l, y / l, z / l, w / l); + + return dest; + } + + /** + * The dot product of two vectors is calculated as + * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector4f left, Vector4f right) { + return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; + } + + /** + * Calculate the angle between two vectors, in radians + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector4f a, Vector4f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float)Math.acos(dls); + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#load(FloatBuffer) + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + w = buf.get(); + return this; + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + x *= scale; + y *= scale; + z *= scale; + w *= scale; + return this; + } + + /* (non-Javadoc) + * @see org.lwjgl.vector.Vector#store(FloatBuffer) + */ + public Vector store(FloatBuffer buf) { + + buf.put(x); + buf.put(y); + buf.put(z); + buf.put(w); + + return this; + } + + public String toString() { + return "Vector4f: " + x + " " + y + " " + z + " " + w; + } + + /** + * @return x + */ + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /** + * Set X + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * @param y + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Set Z + * @param z + */ + public void setZ(float z) { + this.z = z; + } + + + /* (Overrides) + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; + } + + /** + * Set W + * @param w + */ + public void setW(float w) { + this.w = w; + } + + /* (Overrides) + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getW() { + return w; + } + + +} diff --git a/src/main/java/org/lwjglx/util/vector/WritableVector2f.java b/src/main/java/org/lwjglx/util/vector/WritableVector2f.java new file mode 100644 index 0000000..681e2f9 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/WritableVector2f.java @@ -0,0 +1,61 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * Writable interface to Vector2fs + * @author $author$ + * @version $revision$ + * $Id: WritableVector2f.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public interface WritableVector2f { + + /** + * Set the X value + * @param x + */ + void setX(float x); + + /** + * Set the Y value + * @param y + */ + void setY(float y); + + /** + * Set the X,Y values + * @param x + * @param y + */ + void set(float x, float y); + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/vector/WritableVector3f.java b/src/main/java/org/lwjglx/util/vector/WritableVector3f.java new file mode 100644 index 0000000..712e348 --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/WritableVector3f.java @@ -0,0 +1,56 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * Writable interface to Vector3fs + * @author $author$ + * @version $revision$ + * $Id: WritableVector3f.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public interface WritableVector3f extends WritableVector2f { + + /** + * Set the Z value + * @param z + */ + void setZ(float z); + + /** + * Set the X,Y,Z values + * @param x + * @param y + * @param z + */ + void set(float x, float y, float z); + +} \ No newline at end of file diff --git a/src/main/java/org/lwjglx/util/vector/WritableVector4f.java b/src/main/java/org/lwjglx/util/vector/WritableVector4f.java new file mode 100644 index 0000000..93783fe --- /dev/null +++ b/src/main/java/org/lwjglx/util/vector/WritableVector4f.java @@ -0,0 +1,57 @@ +/* + * 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 + * met: + * + * * 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 + * 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 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * 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.lwjglx.util.vector; + +/** + * Writable interface to Vector4fs + * @author $author$ + * @version $revision$ + * $Id: WritableVector4f.java 3418 2010-09-28 21:11:35Z spasi $ + */ +public interface WritableVector4f extends WritableVector3f { + + /** + * Set the W value + * @param w + */ + void setW(float w); + + /** + * Set the X,Y,Z,W values + * @param x + * @param y + * @param z + * @param w + */ + void set(float x, float y, float z, float w); + +} \ No newline at end of file