diff options
Diffstat (limited to 'src')
38 files changed, 1888 insertions, 336 deletions
diff --git a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java index af16348a8..7589b3776 100644 --- a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java +++ b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java @@ -129,7 +129,14 @@ public class JoglVersion extends JogampVersion { public static StringBuilder getGLInfo(final GL gl, final StringBuilder sb) { return getGLInfo(gl, sb, false); } - public static StringBuilder getGLInfo(final GL gl, StringBuilder sb, final boolean withCapabilitiesAndExtensionInfo) { + public static StringBuilder getGLInfo(final GL gl, final StringBuilder sb, final boolean withCapabilitiesAndExtensionInfo) { + return getGLInfo(gl, sb, true, withCapabilitiesAndExtensionInfo, withCapabilitiesAndExtensionInfo); + } + + public static StringBuilder getGLInfo(final GL gl, StringBuilder sb, + final boolean withAvailabilityInfo, + final boolean withCapabilitiesInfo, + final boolean withExtensionInfo) { final AbstractGraphicsDevice device = gl.getContext().getGLDrawable().getNativeSurface() .getGraphicsConfiguration().getScreen().getDevice(); if(null==sb) { @@ -139,12 +146,14 @@ public class JoglVersion extends JogampVersion { sb.append(VersionUtil.SEPERATOR).append(Platform.getNewline()); sb.append(device.getClass().getSimpleName()).append("[type ") .append(device.getType()).append(", connection ").append(device.getConnection()).append("]: ").append(Platform.getNewline()); - GLProfile.glAvailabilityToString(device, sb, "\t", 1); + if( withAvailabilityInfo ) { + GLProfile.glAvailabilityToString(device, sb, "\t", 1); + } sb.append(Platform.getNewline()); - sb = getGLStrings(gl, sb, withCapabilitiesAndExtensionInfo); + sb = getGLStrings(gl, sb, withExtensionInfo); - if( withCapabilitiesAndExtensionInfo ) { + if( withCapabilitiesInfo ) { sb = getAllAvailableCapabilitiesInfo(device, sb); } return sb; diff --git a/src/jogl/classes/com/jogamp/opengl/awt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/awt/GLCanvas.java index 11d217535..5f59f7e6d 100644 --- a/src/jogl/classes/com/jogamp/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/awt/GLCanvas.java @@ -173,7 +173,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private final RecursiveLock lock = LockFactory.createRecursiveLock(); private final GLDrawableHelper helper = new GLDrawableHelper(); - private AWTGraphicsConfiguration awtConfig; private volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access private volatile JAWTWindow jawtWindow; // the JAWTWindow presentation of this AWT Canvas, bound to the 'drawable' lifecycle private volatile GLContextImpl context; // volatile: avoid locking for read-only access @@ -187,9 +186,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private final GLCapabilitiesImmutable capsReqUser; private final GLCapabilitiesChooser chooser; private int additionalCtxCreationFlags = 0; - private final GraphicsDevice device; private boolean shallUseOffscreenLayer = false; + private volatile GraphicsDevice awtDeviceReq; // one time user req. + private volatile AWTGraphicsConfiguration awtConfig; private volatile boolean isShowing; private final HierarchyListener hierarchyListener = new HierarchyListener() { @Override @@ -270,16 +270,8 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing setShallUseOffscreenLayer(true); // trigger offscreen layer - if supported } - if(null==device) { - final GraphicsConfiguration gc = super.getGraphicsConfiguration(); - if(null!=gc) { - this.device = gc.getDevice(); - } else { - this.device = null; - } - } else { - this.device = device; - } + // One time user AWT GraphicsDevice request + awtDeviceReq = device; // instantiation will be issued in addNotify() this.chooser = chooser; @@ -330,124 +322,111 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing /** - * Overridden to choose a GraphicsConfiguration on a parent container's - * GraphicsDevice because both devices + * {@inheritDoc} + * <p> + * Overridden to choose a {@link GraphicsConfiguration} from a parent container's + * {@link GraphicsDevice}. + * </p> + * <p> + * Method also intercepts {@link GraphicsConfiguration} changes regarding to + * its capabilities and its {@link GraphicsDevice}. This may happen in case + * the display changes its configuration or the component is moved to another screen. + * </p> */ @Override public GraphicsConfiguration getGraphicsConfiguration() { - /* - * Workaround for problems with Xinerama and java.awt.Component.checkGD - * when adding to a container on a different graphics device than the - * one that this Canvas is associated with. - * - * GC will be null unless: - * - A native peer has assigned it. This means we have a native - * peer, and are already comitted to a graphics configuration. - * - This canvas has been added to a component hierarchy and has - * an ancestor with a non-null GC, but the native peer has not - * yet been created. This means we can still choose the GC on - * all platforms since the peer hasn't been created. - */ - final GraphicsConfiguration gc = super.getGraphicsConfiguration(); - - if( Beans.isDesignTime() ) { - return gc; - } - - /* - * chosen is only non-null on platforms where the GLDrawableFactory - * returns a non-null GraphicsConfiguration (in the GLCanvas - * constructor). - * - * if gc is from this Canvas' native peer then it should equal chosen, - * otherwise it is from an ancestor component that this Canvas is being - * added to, and we go into this block. - */ - GraphicsConfiguration chosen = null != awtConfig ? awtConfig.getAWTGraphicsConfiguration() : null; - - if (gc != null && chosen != null && !chosen.equals(gc)) { - /* - * Check for compatibility with gc. If they differ by only the - * device then return a new GCconfig with the super-class' GDevice - * (and presumably the same visual ID in Xinerama). - * + /** + * parentGC will be null unless: + * - A native peer has assigned it. This means we have a native + * peer, and are already committed to a graphics configuration. + * - This canvas has been added to a component hierarchy and has + * an ancestor with a non-null GC, but the native peer has not + * yet been created. This means we can still choose the GC on + * all platforms since the peer hasn't been created. */ - if (!chosen.getDevice().getIDstring().equals(gc.getDevice().getIDstring())) { - /* - * Here we select a GraphicsConfiguration on the alternate - * device that is presumably identical to the chosen - * configuration, but on the other device. - * - * Should really check to ensure that we select a configuration - * with the same X visual ID for Xinerama screens, otherwise the - * GLDrawable may have the wrong visual ID (I don't think this - * ever gets updated). May need to add a method to - * X11GLDrawableFactory to do this in a platform specific - * manner. - * - * However, on platforms where we can actually get into this - * block, both devices should have the same visual list, and the - * same configuration should be selected here. - */ - final AWTGraphicsConfiguration config = chooseGraphicsConfiguration( (GLCapabilitiesImmutable)awtConfig.getChosenCapabilities(), - (GLCapabilitiesImmutable)awtConfig.getRequestedCapabilities(), - chooser, gc.getDevice()); - final GraphicsConfiguration compatible = config.getAWTGraphicsConfiguration(); - final boolean equalCaps = config.getChosenCapabilities().equals(awtConfig.getChosenCapabilities()); - if(DEBUG) { - System.err.println(getThreadName()+": Info:"); - System.err.println("Created Config (n): HAVE GC "+chosen); - System.err.println("Created Config (n): THIS GC "+gc); - System.err.println("Created Config (n): Choosen GC "+compatible); - System.err.println("Created Config (n): HAVE CF "+awtConfig); - System.err.println("Created Config (n): Choosen CF "+config); - System.err.println("Created Config (n): EQUALS CAPS "+equalCaps); - // Thread.dumpStack(); - } + final GraphicsConfiguration parentGC = super.getGraphicsConfiguration(); - if (compatible != null) { - /* - * Save the new GC for equals test above, and to return to - * any outside callers of this method. - */ - chosen = compatible; - - if( !equalCaps && GLAutoDrawable.SCREEN_CHANGE_ACTION_ENABLED ) { - // complete destruction! - destroyImpl( true ); - // recreation! - awtConfig = config; - createJAWTDrawableAndContext(); - validateGLDrawable(); - } else { - awtConfig = config; + if( Beans.isDesignTime() ) { + return parentGC; + } + final GraphicsConfiguration oldGC = null != awtConfig ? awtConfig.getAWTGraphicsConfiguration() : null; + + if ( null != parentGC && null != oldGC && !oldGC.equals(parentGC) ) { + // Previous oldGC != parentGC of native peer + + if ( !oldGC.getDevice().getIDstring().equals(parentGC.getDevice().getIDstring()) ) { + // Previous oldGC's GraphicsDevice != parentGC's GraphicsDevice of native peer + + /** + * Here we select a GraphicsConfiguration on the alternate device. + * In case the new configuration differs (-> !equalCaps), + * we might need a reconfiguration, + */ + final AWTGraphicsConfiguration newConfig = chooseGraphicsConfiguration( (GLCapabilitiesImmutable)awtConfig.getChosenCapabilities(), + (GLCapabilitiesImmutable)awtConfig.getRequestedCapabilities(), + chooser, parentGC.getDevice()); + final GraphicsConfiguration newGC = newConfig.getAWTGraphicsConfiguration(); + final boolean equalCaps = newConfig.getChosenCapabilities().equals(awtConfig.getChosenCapabilities()); + if(DEBUG) { + System.err.println(getThreadName()+": getGraphicsConfiguration() Info: Changed GC and GD"); + System.err.println("Created Config (n): Old GC "+oldGC); + System.err.println("Created Config (n): Old GD "+oldGC.getDevice().getIDstring()); + System.err.println("Created Config (n): Parent GC "+parentGC); + System.err.println("Created Config (n): Parent GD "+parentGC.getDevice().getIDstring()); + System.err.println("Created Config (n): New GC "+newGC); + System.err.println("Created Config (n): New GD "+newGC.getDevice().getIDstring()); + System.err.println("Created Config (n): Old CF "+awtConfig); + System.err.println("Created Config (n): New CF "+newConfig); + System.err.println("Created Config (n): EQUALS CAPS "+equalCaps); + // Thread.dumpStack(); + } + if ( null != newGC ) { + if( !equalCaps && GLAutoDrawable.SCREEN_CHANGE_ACTION_ENABLED ) { + // complete destruction! + destroyImpl( true ); + // recreation! + setAWTGraphicsConfiguration(newConfig); + createJAWTDrawableAndContext(); + validateGLDrawable(); + } else { + setAWTGraphicsConfiguration(newConfig); + } + /** + * Return the newGC, which covers the desired capabilities and is compatible + * with the available GC's of its devices. + */ + if(DEBUG) { + System.err.println(getThreadName()+": Info: getGraphicsConfiguration - end.01: newGC "+newGC); + } + return newGC; + } else { + if(DEBUG) { + System.err.println(getThreadName()+": Info: getGraphicsConfiguration - end.00: oldGC "+oldGC); + } + } } - } + /** + * If a new GC was _not_ found/defined above, + * method returns oldGC as selected in the constructor or first addNotify(). + * This may cause an exception in Component.checkGD when adding to a + * container, and is the desired behavior. + */ + return oldGC; + } else if (null == parentGC) { + /** + * The parentGC is null, which means we have no native peer, and are not + * part of a (realized) component hierarchy. So we return the + * desired visual that was selected in the constructor (possibly + * null). + */ + return oldGC; + } else { + /** + * Otherwise we have not explicitly selected a GC in the constructor, so + * just return what Canvas would have. + */ + return parentGC; } - - /* - * If a compatible GC was not found in the block above, this will - * return the GC that was selected in the constructor (and might - * cause an exception in Component.checkGD when adding to a - * container, but in this case that would be the desired behavior). - * - */ - return chosen; - } else if (gc == null) { - /* - * The GC is null, which means we have no native peer, and are not - * part of a (realized) component hierarchy. So we return the - * desired visual that was selected in the constructor (possibly - * null). - */ - return chosen; - } - - /* - * Otherwise we have not explicitly selected a GC in the constructor, so - * just return what Canvas would have. - */ - return gc; } @Override @@ -606,20 +585,35 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } else { /** * 'super.addNotify()' determines the GraphicsConfiguration, - * while calling this class's overriden 'getGraphicsConfiguration()' method + * while calling this class's overridden 'getGraphicsConfiguration()' method * after which it creates the native peer. * Hence we have to set the 'awtConfig' before since it's GraphicsConfiguration * is being used in getGraphicsConfiguration(). * This code order also allows recreation, ie re-adding the GLCanvas. */ - awtConfig = chooseGraphicsConfiguration(capsReqUser, capsReqUser, chooser, device); - if(null==awtConfig) { - throw new GLException("Error: NULL AWTGraphicsConfiguration"); - } // before native peer is valid: X11 disableBackgroundErase(); + final GraphicsDevice awtDevice; + if(null==awtDeviceReq) { + // Query AWT GraphicsDevice from parent tree, default + final GraphicsConfiguration gc = super.getGraphicsConfiguration(); + if(null==gc) { + throw new GLException("Error: NULL AWT GraphicsConfiguration"); + } + awtDevice = gc.getDevice(); + } else { + // Use one time user AWT GraphicsDevice request + awtDevice = awtDeviceReq; + awtDeviceReq = null; + } + final AWTGraphicsConfiguration awtConfig = chooseGraphicsConfiguration(capsReqUser, capsReqUser, chooser, awtDevice); + if(null==awtConfig) { + throw new GLException("Error: NULL AWTGraphicsConfiguration"); + } + setAWTGraphicsConfiguration(awtConfig); + // issues getGraphicsConfiguration() and creates the native peer super.addNotify(); @@ -775,6 +769,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing return false; } + private void setAWTGraphicsConfiguration(final AWTGraphicsConfiguration config) { + // Cache awtConfig + awtConfig = config; + if( null != jawtWindow ) { + // Notify JAWTWindow .. + jawtWindow.setAWTGraphicsConfiguration(config); + } + } + /** <p>Overridden to track when this component is removed from a container. Subclasses which override this method must call super.removeNotify() in their removeNotify() method in order to @@ -1394,7 +1397,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing System.err.println(getThreadName()+": GLCanvas.disposeJAWTWindowAndAWTDeviceOnEDT(): post GraphicsDevice: "+adeviceMsg+", result: "+closed); } } - awtConfig=null; + awtConfig = null; } }; @@ -1546,10 +1549,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if( Beans.isDesignTime() ) { return null; } - - final AbstractGraphicsScreen aScreen = null != device ? - AWTGraphicsScreen.createScreenDevice(device, AbstractGraphicsDevice.DEFAULT_UNIT): - AWTGraphicsScreen.createDefault(); + if( null == device ) { + throw new GLException("Error: NULL AWT GraphicsDevice"); + } + final AbstractGraphicsScreen aScreen = AWTGraphicsScreen.createScreenDevice(device, AbstractGraphicsDevice.DEFAULT_UNIT); AWTGraphicsConfiguration config = null; if( EventQueue.isDispatchThread() || Thread.holdsLock(getTreeLock()) ) { diff --git a/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java b/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java index a04055430..7f630f9d5 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java @@ -35,6 +35,7 @@ import jogamp.opengl.Debug; import com.jogamp.common.os.Platform; import com.jogamp.opengl.math.geom.AABBox; +import com.jogamp.opengl.math.geom.Frustum; /** * Basic Float math utility functions. @@ -491,18 +492,18 @@ public final class FloatUtil { * @param zNear * @param zFar * @return given matrix for chaining - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, - * or if left == right, or bottom == top, or zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * or {@code left == right}, or {@code bottom == top}. */ public static float[] makeFrustum(final float[] m, final int m_offset, final boolean initM, final float left, final float right, final float bottom, final float top, final float zNear, final float zFar) throws GLException { - if( zNear <= 0.0f || zFar < 0.0f ) { - throw new GLException("GL_INVALID_VALUE: zNear and zFar must be positive, and zNear>0"); + if( zNear <= 0.0f || zFar <= zNear ) { + throw new GLException("Requirements zNear > 0 and zFar > zNear, but zNear "+zNear+", zFar "+zFar); } - if( left == right || top == bottom || zNear == zFar ) { - throw new GLException("GL_INVALID_VALUE: top,bottom and left,right and zNear,zFar must not be equal"); + if( left == right || top == bottom) { + throw new GLException("GL_INVALID_VALUE: top,bottom and left,right must not be equal"); } if( initM ) { // m[m_offset+0+4*0] = 1f; @@ -565,14 +566,15 @@ public final class FloatUtil { * @param zNear * @param zFar * @return given matrix for chaining - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, or if zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * @see #makeFrustum(float[], int, boolean, float, float, float, float, float, float) */ public static float[] makePerspective(final float[] m, final int m_off, final boolean initM, final float fovy_rad, final float aspect, final float zNear, final float zFar) throws GLException { final float top = tan(fovy_rad/2f) * zNear; // use tangent of half-fov ! - final float bottom = -1.0f * top; - final float left = aspect * bottom; - final float right = aspect * top; + final float bottom = -1.0f * top; // -1f * fovhvTan.top * zNear + final float left = aspect * bottom; // aspect * -1f * fovhvTan.top * zNear + final float right = aspect * top; // aspect * fovhvTan.top * zNear return makeFrustum(m, m_off, initM, left, right, bottom, top, zNear, zFar); } @@ -591,7 +593,9 @@ public final class FloatUtil { * @param zNear * @param zFar * @return given matrix for chaining - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, or if zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * @see #makeFrustum(float[], int, boolean, float, float, float, float, float, float) + * @see Frustum#updateByFovDesc(float[], int, boolean, Frustum.FovDesc) */ public static float[] makePerspective(final float[] m, final int m_offset, final boolean initM, final FovHVHalves fovhv, final float zNear, final float zFar) throws GLException { diff --git a/src/jogl/classes/com/jogamp/opengl/math/FovHVHalves.java b/src/jogl/classes/com/jogamp/opengl/math/FovHVHalves.java index 26ed57009..5d7907f2f 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/FovHVHalves.java +++ b/src/jogl/classes/com/jogamp/opengl/math/FovHVHalves.java @@ -35,13 +35,13 @@ package com.jogamp.opengl.math; * </p> */ public final class FovHVHalves { - /** Half horizontal FOV from center to left. */ + /** Half horizontal FOV from center to left, either in {@link #inTangents} or radians. */ public final float left; - /** Half horizontal FOV from center to right. */ + /** Half horizontal FOV from center to right, either in {@link #inTangents} or radians. */ public final float right; - /** Half vertical FOV from center to top. */ + /** Half vertical FOV from center to top, either in {@link #inTangents} or radians. */ public final float top; - /** Half vertical FOV from center to bottom. */ + /** Half vertical FOV from center to bottom, either in {@link #inTangents} or radians. */ public final float bottom; /** If true, values are in tangent, otherwise radians.*/ public final boolean inTangents; @@ -67,7 +67,7 @@ public final class FovHVHalves { } /** - * Returns a symmetrical centered {@link FovHVHalves} instance in tangents, using: + * Returns a symmetrical centered {@link FovHVHalves} instance in {@link #inTangents}, using: * <pre> halfHorizFovTan = tan( horizontalFov / 2f ); halfVertFovTan = tan( verticalFov / 2f ); @@ -82,7 +82,7 @@ public final class FovHVHalves { } /** - * Returns a symmetrical centered {@link FovHVHalves} instance in tangents, using: + * Returns a symmetrical centered {@link FovHVHalves} instance in {@link #inTangents}, using: * <pre> top = bottom = tan( verticalFov / 2f ); left = right = aspect * top; @@ -99,7 +99,7 @@ public final class FovHVHalves { } /** - * Returns a custom symmetry {@link FovHVHalves} instance in tangents, using: + * Returns a custom symmetry {@link FovHVHalves} instance {@link #inTangents}, using: * <pre> left = tan( horizontalFov * horizCenterFromLeft ) right = tan( horizontalFov * ( 1f - horizCenterFromLeft ) ) @@ -121,7 +121,7 @@ public final class FovHVHalves { } /** - * Returns a custom symmetry {@link FovHVHalves} instance in tangents, + * Returns a custom symmetry {@link FovHVHalves} instance {@link #inTangents}, * via computing the <code>horizontalFov</code> using: * <pre> halfVertFovTan = tan( verticalFov / 2f ); @@ -157,10 +157,10 @@ public final class FovHVHalves { } } - /** Returns the full horizontal FOV, i.e. {@link #left} + {@link #right}. */ + /** Returns the full horizontal FOV, i.e. {@link #left} + {@link #right}, either in {@link #inTangents} or radians. */ public final float horzFov() { return left+right; } - /** Returns the full vertical FOV, i.e. {@link #top} + {@link #bottom}. */ + /** Returns the full vertical FOV, i.e. {@link #top} + {@link #bottom}, either in {@link #inTangents} or radians. */ public final float vertFov() { return top+bottom; } public final String toString() { diff --git a/src/jogl/classes/com/jogamp/opengl/math/Matrix4.java b/src/jogl/classes/com/jogamp/opengl/math/Matrix4.java index 421bb909f..a080d4442 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/Matrix4.java +++ b/src/jogl/classes/com/jogamp/opengl/math/Matrix4.java @@ -147,8 +147,9 @@ public class Matrix4 { * @param top * @param zNear * @param zFar - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, - * or if left == right, or bottom == top, or zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * or {@code left == right}, or {@code bottom == top}. + * @see FloatUtil#makeFrustum(float[], int, boolean, float, float, float, float, float, float) */ public final void makeFrustum(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar) throws GLException { multMatrix( FloatUtil.makeFrustum(mat4Tmp1, 0, true, left, right, bottom, top, zNear, zFar) ); @@ -159,7 +160,8 @@ public class Matrix4 { * @param aspect * @param zNear * @param zFar - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, or if zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * @see FloatUtil#makePerspective(float[], int, boolean, float, float, float, float) */ public final void makePerspective(final float fovy_rad, final float aspect, final float zNear, final float zFar) throws GLException { multMatrix( FloatUtil.makePerspective(mat4Tmp1, 0, true, fovy_rad, aspect, zNear, zFar) ); diff --git a/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java b/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java index b73bad613..8b0fa559e 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java +++ b/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java @@ -30,6 +30,8 @@ package com.jogamp.opengl.math.geom; import jogamp.common.os.PlatformPropsImpl; import com.jogamp.common.os.Platform; +import com.jogamp.opengl.math.FloatUtil; +import com.jogamp.opengl.math.FovHVHalves; /** * Providing frustum {@link #getPlanes() planes} derived by different inputs @@ -77,6 +79,35 @@ import com.jogamp.common.os.Platform; * </p> */ public class Frustum { + /** + * {@link Frustum} description by {@link #fovhv} and {@link #zNear}, {@link #zFar}. + */ + public static class FovDesc { + /** Field of view in both directions, may not be centered, either {@link FovHVHalves#inTangents} or radians. */ + public final FovHVHalves fovhv; + /** Near Z */ + public final float zNear; + /** Far Z */ + public final float zFar; + /** + * @param fovhv field of view in both directions, may not be centered, either {@link FovHVHalves#inTangents} or radians + * @param zNear + * @param zFar + * @throws IllegalArgumentException if {@code zNear <= 0} or {@code zFar <= zNear}. + */ + public FovDesc(final FovHVHalves fovhv, final float zNear, final float zFar) throws IllegalArgumentException { + if( zNear <= 0.0f || zFar <= zNear ) { + throw new IllegalArgumentException("Requirements zNear > 0 and zFar > zNear, but zNear "+zNear+", zFar "+zFar); + } + this.fovhv = fovhv; + this.zNear = zNear; + this.zFar = zFar; + } + public final String toString() { + return "FrustumFovDesc["+fovhv.toStringInDegrees()+", Z["+zNear+" - "+zFar+"]]"; + } + } + /** Normalized planes[l, r, b, t, n, f] */ protected final Plane[] planes = new Plane[6]; @@ -176,19 +207,47 @@ public class Frustum { */ public final void updateByPlanes(final Plane[] src) { for (int i = 0; i < 6; ++i) { - final Plane p0 = planes[i]; - final float[] p0_n = p0.n; - final Plane p1 = src[i]; - final float[] p1_n = p1.n; - p0_n[0] = p1_n[0]; - p0_n[1] = p1_n[1]; - p0_n[2] = p1_n[2]; - p0.d = p1.d; + final Plane pD = planes[i]; + final Plane pS = src[i]; + pD.d = pS.d; + System.arraycopy(pS.n, 0, pD.n, 0, 3); } } /** * Calculate the frustum planes in world coordinates + * using the passed {@link FovDesc}. + * <p> + * Operation Details: + * <ul> + * <li>The given {@link FovDesc} will be transformed + * into the given float[16] as a perspective matrix (column major order) first, + * see {@link FloatUtil#makePerspective(float[], int, boolean, FovHVHalves, float, float)}.</li> + * <li>Then the float[16] perspective matrix is used to {@link #updateByPMV(float[], int)} this instance.</li> + * </ul> + * </p> + * <p> + * Frustum plane's normals will point to the inside of the viewing frustum, + * as required by this class. + * </p> + * + * @param m 4x4 matrix in column-major order (also result) + * @param m_offset offset in given array <i>m</i>, i.e. start of the 4x4 matrix + * @param initM if true, given matrix will be initialized w/ identity matrix, + * otherwise only the frustum fields are set. + * @param fovDesc {@link Frustum} {@link FovDesc} + * @return given matrix for chaining + * @see FloatUtil#makePerspective(float[], int, boolean, FovHVHalves, float, float) + */ + public float[] updateByFovDesc(final float[] m, final int m_offset, final boolean initM, + final FovDesc fovDesc) { + FloatUtil.makePerspective(m, m_offset, initM, fovDesc.fovhv, fovDesc.zNear, fovDesc.zFar); + updateByPMV(m, 0); + return m; + } + + /** + * Calculate the frustum planes in world coordinates * using the passed float[16] as premultiplied P*MV (column major order). * <p> * Frustum plane's normals will point to the inside of the viewing frustum, diff --git a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java index 57f9301b8..196acf9ab 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java +++ b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java @@ -663,8 +663,9 @@ public final class PMVMatrix implements GLMatrixFunc { /** * {@inheritDoc} * - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, - * or if left == right, or bottom == top, or zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * or {@code left == right}, or {@code bottom == top}. + * @see FloatUtil#makeFrustum(float[], int, boolean, float, float, float, float, float, float) */ @Override public final void glFrustumf(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar) throws GLException { @@ -682,7 +683,8 @@ public final class PMVMatrix implements GLMatrixFunc { * @param aspect aspect ratio width / height * @param zNear * @param zFar - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, or if zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * @see FloatUtil#makePerspective(float[], int, boolean, float, float, float, float) */ public final void gluPerspective(final float fovy_deg, final float aspect, final float zNear, final float zFar) throws GLException { glMultMatrixf( FloatUtil.makePerspective(mat4Tmp1, 0, true, fovy_deg * FloatUtil.PI / 180.0f, aspect, zNear, zFar), 0 ); diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java index 6052c3b49..e1db3f7a3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java @@ -189,7 +189,7 @@ public class ShaderCode { * {@link GL4#GL_TESS_CONTROL_SHADER} or {@link GL4#GL_TESS_EVALUATION_SHADER}. * @param count number of shaders * @param context class used to help resolving the source location - * @param sourceFiles array of source locations, organized as <code>sourceFiles[count]</code> + * @param sourceFiles array of source locations, organized as <code>sourceFiles[count]</code> -> <code>shaderSources[count][1]</code> * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. @@ -200,7 +200,8 @@ public class ShaderCode { * @throws IllegalArgumentException if <code>count</code> and <code>sourceFiles.length</code> do not match * @see #readShaderSource(Class, String) */ - public static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, final String[] sourceFiles, final boolean mutableStringBuilder) { + public static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, + final String[] sourceFiles, final boolean mutableStringBuilder) { if(null != gl && !ShaderUtil.isShaderCompilerAvailable(gl)) { return null; } @@ -227,6 +228,53 @@ public class ShaderCode { } /** + * Creates a complete {@link ShaderCode} object while reading all shader sources from {@link Uri} <code>sourceLocations</code> + * via {@link #readShaderSource(Uri, boolean)}. + * + * @param gl current GL object to determine whether a shader compiler is available. If null, no validation is performed. + * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER}, {@link GL3#GL_GEOMETRY_SHADER}, + * {@link GL4#GL_TESS_CONTROL_SHADER} or {@link GL4#GL_TESS_EVALUATION_SHADER}. + * @param count number of shaders + * @param sourceLocations array of {@link Uri} source locations, organized as <code>sourceFiles[count]</code> -> <code>shaderSources[count][1]</code> + * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance + * which can be edited later on at the costs of a String conversion when passing to + * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. + * If <code>false</code> method returns an immutable <code>String</code> instance, + * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} + * at no additional costs. + * + * @throws IllegalArgumentException if <code>count</code> and <code>sourceFiles.length</code> do not match + * @see #readShaderSource(Uri, boolean) + * @since 2.3.2 + */ + public static ShaderCode create(final GL2ES2 gl, final int type, final int count, + final Uri[] sourceLocations, final boolean mutableStringBuilder) { + if(null != gl && !ShaderUtil.isShaderCompilerAvailable(gl)) { + return null; + } + + CharSequence[][] shaderSources = null; + if(null!=sourceLocations) { + // sourceFiles.length and count is validated in ctor + shaderSources = new CharSequence[sourceLocations.length][1]; + for(int i=0; i<sourceLocations.length; i++) { + try { + shaderSources[i][0] = readShaderSource(sourceLocations[i], mutableStringBuilder); + } catch (final IOException ioe) { + throw new RuntimeException("readShaderSource("+sourceLocations[i]+") error: ", ioe); + } + if(null == shaderSources[i][0]) { + shaderSources = null; + } + } + } + if(null==shaderSources) { + return null; + } + return new ShaderCode(type, count, shaderSources); + } + + /** * Creates a complete {@link ShaderCode} object while reading the shader binary of <code>binaryFile</code>, * which location is resolved using the <code>context</code> class, see {@link #readShaderBinary(Class, String)}. * @@ -259,6 +307,37 @@ public class ShaderCode { } /** + * Creates a complete {@link ShaderCode} object while reading the shader binary from {@link Uri} <code>binLocations</code> + * via {@link #readShaderBinary(Uri)}. + * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER}, {@link GL3#GL_GEOMETRY_SHADER}, + * {@link GL4#GL_TESS_CONTROL_SHADER} or {@link GL4#GL_TESS_EVALUATION_SHADER}. + * @param count number of shaders + * @param binFormat a valid native binary format as they can be queried by {@link ShaderUtil#getShaderBinaryFormats(GL)}. + * @param binLocations {@link Uri} binary location + * + * @see #readShaderBinary(Uri) + * @see ShaderUtil#getShaderBinaryFormats(GL) + * @since 2.3.2 + */ + public static ShaderCode create(final int type, final int count, int binFormat, final Uri binLocation) { + ByteBuffer shaderBinary = null; + if(null!=binLocation && 0<=binFormat) { + try { + shaderBinary = readShaderBinary(binLocation); + } catch (final IOException ioe) { + throw new RuntimeException("readShaderBinary("+binLocation+") error: ", ioe); + } + if(null == shaderBinary) { + binFormat = -1; + } + } + if(null==shaderBinary) { + return null; + } + return new ShaderCode(type, count, binFormat, shaderBinary); + } + + /** * Returns a unique suffix for shader resources as follows: * <ul> * <li>Source<ul> @@ -327,7 +406,8 @@ public class ShaderCode { * whatever is available first. * <p> * The source and binary location names are expected w/o suffixes which are - * resolved and appended using {@link #getFileSuffix(boolean, int)}. + * resolved and appended using the given {@code srcSuffixOpt} and {@code binSuffixOpt} + * if not {@code null}, otherwise {@link #getFileSuffix(boolean, int)} determines the suffixes. * </p> * <p> * Additionally, the binary resource is expected within a subfolder of <code>binRoot</code> @@ -358,9 +438,11 @@ public class ShaderCode { * Your invocation in org/test/glsl/MyShaderTest.java: * * ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(), - * "shader", new String[] { "vertex" }, "shader/bin", "vertex"); + * "shader", new String[] { "vertex" }, null, + * "shader/bin", "vertex", null, true); * ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(), - * "shader", new String[] { "vertex" }, "shader/bin", "fragment"); + * "shader", new String[] { "vertex" }, null, + * "shader/bin", "fragment", null, true); * ShaderProgram sp0 = new ShaderProgram(); * sp0.add(gl, vp0, System.err); * sp0.add(gl, fp0, System.err); @@ -380,8 +462,12 @@ public class ShaderCode { * @param context class used to help resolving the source and binary location * @param srcRoot relative <i>root</i> path for <code>srcBasenames</code> optional * @param srcBasenames basenames w/o path or suffix relative to <code>srcRoot</code> for the shader's source code + * @param srcSuffixOpt optional custom suffix for shader's source file, + * if {@code null} {@link #getFileSuffix(boolean, int)} is being used. * @param binRoot relative <i>root</i> path for <code>binBasenames</code> * @param binBasename basename w/o path or suffix relative to <code>binRoot</code> for the shader's binary code + * @param binSuffixOpt optional custom suffix for shader's binary file, + * if {@code null} {@link #getFileSuffix(boolean, int)} is being used. * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. @@ -397,9 +483,12 @@ public class ShaderCode { * @see #getFileSuffix(boolean, int) * @see ShaderUtil#getShaderBinaryFormats(GL) * @see #getBinarySubPath(int) + * + * @since 2.3.2 */ public static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, - final String srcRoot, final String[] srcBasenames, final String binRoot, final String binBasename, + final String srcRoot, final String[] srcBasenames, final String srcSuffixOpt, + final String binRoot, final String binBasename, final String binSuffixOpt, final boolean mutableStringBuilder) { ShaderCode res = null; final String srcPath[]; @@ -408,7 +497,7 @@ public class ShaderCode { if( null!=srcBasenames && ShaderUtil.isShaderCompilerAvailable(gl) ) { srcPath = new String[srcBasenames.length]; - final String srcSuffix = getFileSuffix(false, type); + final String srcSuffix = null != srcSuffixOpt ? srcSuffixOpt : getFileSuffix(false, type); if( null != srcRoot && srcRoot.length() > 0 ) { for(int i=0; i<srcPath.length; i++) { srcPath[i] = srcRoot + '/' + srcBasenames[i] + "." + srcSuffix; @@ -428,7 +517,7 @@ public class ShaderCode { } if( null!=binBasename ) { final Set<Integer> binFmts = ShaderUtil.getShaderBinaryFormats(gl); - final String binSuffix = getFileSuffix(true, type); + final String binSuffix = null != binSuffixOpt ? binSuffixOpt : getFileSuffix(true, type); for(final Iterator<Integer> iter=binFmts.iterator(); iter.hasNext(); ) { final int bFmt = iter.next().intValue(); final String bFmtPath = getBinarySubPath(bFmt); @@ -445,7 +534,162 @@ public class ShaderCode { } /** - * Simplified variation of {@link #create(GL2ES2, int, int, Class, String, String[], String, String, boolean)}. + * Simplified variation of {@link #create(GL2ES2, int, int, Class, String, String[], String, String, String, String, boolean)}. + * <p> + * Convenient creation method for instantiating a complete {@link ShaderCode} object + * either from source code using {@link #create(GL2ES2, int, int, Class, String[])}, + * or from a binary code using {@link #create(int, int, Class, int, String)}, + * whatever is available first. + * </p> + * <p> + * The source and binary location names are expected w/o suffixes which are + * resolved and appended using {@link #getFileSuffix(boolean, int)}. + * </p> + * <p> + * Additionally, the binary resource is expected within a subfolder of <code>binRoot</code> + * which reflects the vendor specific binary format, see {@link #getBinarySubPath(int)}. + * All {@link ShaderUtil#getShaderBinaryFormats(GL)} are being iterated + * using the binary subfolder, the first existing resource is being used. + * </p> + * + * Example: + * <pre> + * Your std JVM layout (plain or within a JAR): + * + * org/test/glsl/MyShaderTest.class + * org/test/glsl/shader/vertex.vp + * org/test/glsl/shader/fragment.fp + * org/test/glsl/shader/bin/nvidia/vertex.bvp + * org/test/glsl/shader/bin/nvidia/fragment.bfp + * + * Your Android APK layout: + * + * classes.dex + * assets/org/test/glsl/shader/vertex.vp + * assets/org/test/glsl/shader/fragment.fp + * assets/org/test/glsl/shader/bin/nvidia/vertex.bvp + * assets/org/test/glsl/shader/bin/nvidia/fragment.bfp + * ... + * + * Your invocation in org/test/glsl/MyShaderTest.java: + * + * ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(), + * "shader", new String[] { "vertex" }, "shader/bin", "vertex", true); + * ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(), + * "shader", new String[] { "vertex" }, "shader/bin", "fragment", true); + * ShaderProgram sp0 = new ShaderProgram(); + * sp0.add(gl, vp0, System.err); + * sp0.add(gl, fp0, System.err); + * st.attachShaderProgram(gl, sp0, true); + * </pre> + * A simplified entry point is {@link #create(GL2ES2, int, Class, String, String, String, boolean)}. + * + * <p> + * The location is finally being resolved using the <code>context</code> class, see {@link #readShaderBinary(Class, String)}. + * </p> + * + * @param gl current GL object to determine whether a shader compiler is available (if <code>source</code> is used), + * or to determine the shader binary format (if <code>binary</code> is used). + * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER}, {@link GL3#GL_GEOMETRY_SHADER}, + * {@link GL4#GL_TESS_CONTROL_SHADER} or {@link GL4#GL_TESS_EVALUATION_SHADER}. + * @param count number of shaders + * @param context class used to help resolving the source and binary location + * @param srcRoot relative <i>root</i> path for <code>srcBasenames</code> optional + * @param srcBasenames basenames w/o path or suffix relative to <code>srcRoot</code> for the shader's source code + * @param binRoot relative <i>root</i> path for <code>binBasenames</code> + * @param binBasename basename w/o path or suffix relative to <code>binRoot</code> for the shader's binary code + * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance + * which can be edited later on at the costs of a String conversion when passing to + * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. + * If <code>false</code> method returns an immutable <code>String</code> instance, + * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} + * at no additional costs. + * + * @throws IllegalArgumentException if <code>count</code> and <code>srcBasenames.length</code> do not match + * + * @see #create(GL2ES2, int, int, Class, String, String[], String, String, String, String, boolean) + * @see #readShaderSource(Class, String) + * @see #getFileSuffix(boolean, int) + * @see ShaderUtil#getShaderBinaryFormats(GL) + * @see #getBinarySubPath(int) + */ + public static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, + final String srcRoot, final String[] srcBasenames, + final String binRoot, final String binBasename, + final boolean mutableStringBuilder) { + return create(gl, type, count, context, srcRoot, srcBasenames, null, + binRoot, binBasename, null, mutableStringBuilder); + } + + /** + * Simplified variation of {@link #create(GL2ES2, int, int, Class, String, String[], String, String, String, String, boolean)}. + * <p> + * Example: + * <pre> + * Your std JVM layout (plain or within a JAR): + * + * org/test/glsl/MyShaderTest.class + * org/test/glsl/shader/vertex.vp + * org/test/glsl/shader/fragment.fp + * org/test/glsl/shader/bin/nvidia/vertex.bvp + * org/test/glsl/shader/bin/nvidia/fragment.bfp + * + * Your Android APK layout: + * + * classes.dex + * assets/org/test/glsl/shader/vertex.vp + * assets/org/test/glsl/shader/fragment.fp + * assets/org/test/glsl/shader/bin/nvidia/vertex.bvp + * assets/org/test/glsl/shader/bin/nvidia/fragment.bfp + * ... + * + * Your invocation in org/test/glsl/MyShaderTest.java: + * + * ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), + * "shader", "shader/bin", "vertex", null, null, true); + * ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), + * "shader", "shader/bin", "fragment", null, null, true); + * ShaderProgram sp0 = new ShaderProgram(); + * sp0.add(gl, vp0, System.err); + * sp0.add(gl, fp0, System.err); + * st.attachShaderProgram(gl, sp0, true); + * </pre> + * </p> + * + * @param gl current GL object to determine whether a shader compiler is available (if <code>source</code> is used), + * or to determine the shader binary format (if <code>binary</code> is used). + * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER}, {@link GL3#GL_GEOMETRY_SHADER}, + * {@link GL4#GL_TESS_CONTROL_SHADER} or {@link GL4#GL_TESS_EVALUATION_SHADER}. + * @param context class used to help resolving the source and binary location + * @param srcRoot relative <i>root</i> path for <code>basename</code> optional + * @param binRoot relative <i>root</i> path for <code>basename</code> + * @param basename basename w/o path or suffix relative to <code>srcRoot</code> and <code>binRoot</code> + * for the shader's source and binary code. + * @param srcSuffixOpt optional custom suffix for shader's source file, + * if {@code null} {@link #getFileSuffix(boolean, int)} is being used. + * @param binSuffixOpt optional custom suffix for shader's binary file, + * if {@code null} {@link #getFileSuffix(boolean, int)} is being used. + * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance + * which can be edited later on at the costs of a String conversion when passing to + * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. + * If <code>false</code> method returns an immutable <code>String</code> instance, + * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} + * at no additional costs. + * @throws IllegalArgumentException if <code>count</code> is not 1 + * + * @see #create(GL2ES2, int, int, Class, String, String[], String, String, String, String, boolean) + * @since 2.3.2 + */ + public static ShaderCode create(final GL2ES2 gl, final int type, final Class<?> context, + final String srcRoot, final String binRoot, + final String basename, final String srcSuffixOpt, final String binSuffixOpt, + final boolean mutableStringBuilder) { + return create(gl, type, 1, context, srcRoot, new String[] { basename }, srcSuffixOpt, + binRoot, basename, binSuffixOpt, mutableStringBuilder ); + } + + /** + * Simplified variation of {@link #create(GL2ES2, int, Class, String, String, String, String, String, boolean)}. * <p> * Example: * <pre> @@ -469,9 +713,9 @@ public class ShaderCode { * Your invocation in org/test/glsl/MyShaderTest.java: * * ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), - * "shader", "shader/bin", "vertex"); + * "shader", "shader/bin", "vertex", true); * ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), - * "shader", "shader/bin", "fragment"); + * "shader", "shader/bin", "fragment", true); * ShaderProgram sp0 = new ShaderProgram(); * sp0.add(gl, vp0, System.err); * sp0.add(gl, fp0, System.err); @@ -496,12 +740,11 @@ public class ShaderCode { * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} * at no additional costs. * @throws IllegalArgumentException if <code>count</code> is not 1 - * - * @see #create(GL2ES2, int, int, Class, String, String[], String, String) */ public static ShaderCode create(final GL2ES2 gl, final int type, final Class<?> context, - final String srcRoot, final String binRoot, final String basename, final boolean mutableStringBuilder) { - return create(gl, type, 1, context, srcRoot, new String[] { basename }, binRoot, basename, mutableStringBuilder ); + final String srcRoot, final String binRoot, final String basename, + final boolean mutableStringBuilder) { + return ShaderCode.create(gl, type, context, srcRoot, binRoot, basename, null, null, mutableStringBuilder); } /** @@ -815,7 +1058,6 @@ public class ShaderCode { } } - @SuppressWarnings("resource") private static int readShaderSource(final Class<?> context, final URLConnection conn, final StringBuilder result, int lineno) throws IOException { if(DEBUG_CODE) { if(0 == lineno) { @@ -858,10 +1100,11 @@ public class ShaderCode { } /** + * Reads shader source located in <code>conn</code>. * - * @param context - * @param conn - * @param result + * @param context class used to help resolve the source location, may be {@code null} + * @param conn the {@link URLConnection} of the shader source + * @param result {@link StringBuilder} sink for the resulting shader source code * @throws IOException */ public static void readShaderSource(final Class<?> context, final URLConnection conn, final StringBuilder result) throws IOException { @@ -899,6 +1142,28 @@ public class ShaderCode { } /** + * Reads shader source located from {@link Uri#absolute} {@link Uri} <code>sourceLocation</code>. + * @param sourceLocation {@link Uri} location of shader source + * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance + * which can be edited later on at the costs of a String conversion when passing to + * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. + * If <code>false</code> method returns an immutable <code>String</code> instance, + * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} + * at no additional costs. + * @throws IOException + * @since 2.3.2 + */ + public static CharSequence readShaderSource(final Uri sourceLocation, final boolean mutableStringBuilder) throws IOException { + final URLConnection conn = IOUtil.openURL(sourceLocation.toURL(), "ShaderCode "); + if (conn == null) { + return null; + } + final StringBuilder result = new StringBuilder(); + readShaderSource(null, conn, result); + return mutableStringBuilder ? result : result.toString(); + } + + /** * Reads shader binary located in <code>path</code>, * either relative to the <code>context</code> class or absolute <i>as-is</i>. * <p> @@ -925,6 +1190,25 @@ public class ShaderCode { } } + /** + * Reads shader binary located from {@link Uri#absolute} {@link Uri} <code>binLocation</code>. + * @param binLocation {@link Uri} location of shader binary + * @throws IOException + * @since 2.3.2 + */ + public static ByteBuffer readShaderBinary(final Uri binLocation) throws IOException { + final URLConnection conn = IOUtil.openURL(binLocation.toURL(), "ShaderCode "); + if (conn == null) { + return null; + } + final BufferedInputStream bis = new BufferedInputStream( conn.getInputStream() ); + try { + return IOUtil.copyStream2ByteBuffer( bis ); + } finally { + IOUtil.close(bis, false); + } + } + // Shall we use: #ifdef GL_FRAGMENT_PRECISION_HIGH .. #endif for using highp in fragment shader if avail ? /** Default precision of {@link GL#isGLES2() ES2} for {@link GL2ES2#GL_VERTEX_SHADER vertex-shader}: {@value #es2_default_precision_vp} */ public static final String es2_default_precision_vp = "\nprecision highp float;\nprecision highp int;\n/*precision lowp sampler2D;*/\n/*precision lowp samplerCube;*/\n"; diff --git a/src/jogl/classes/com/jogamp/opengl/util/stereo/EyeParameter.java b/src/jogl/classes/com/jogamp/opengl/util/stereo/EyeParameter.java index 075da340b..43a6cfc58 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/stereo/EyeParameter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/stereo/EyeParameter.java @@ -30,7 +30,7 @@ package com.jogamp.opengl.util.stereo; import com.jogamp.opengl.math.FovHVHalves; /** - * Constant parameter for one eye. + * Constant single eye parameter of the viewer, relative to its {@link ViewerPose}. */ public final class EyeParameter { /** Eye number, <code>0</code> for the left eye and <code>1</code> for the right eye. */ @@ -39,7 +39,7 @@ public final class EyeParameter { /** float[3] eye position vector used to define eye height in meter relative to <i>actor</i>. */ public final float[] positionOffset; - /** Field of view in both directions, may not be centered, either in radians or tangent. */ + /** Field of view in both directions, may not be centered, either {@link FovHVHalves#inTangents} or radians. */ public final FovHVHalves fovhv; /** IPD related horizontal distance from nose to pupil in meter. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/stereo/LocationSensorParameter.java b/src/jogl/classes/com/jogamp/opengl/util/stereo/LocationSensorParameter.java new file mode 100644 index 000000000..b795927cd --- /dev/null +++ b/src/jogl/classes/com/jogamp/opengl/util/stereo/LocationSensorParameter.java @@ -0,0 +1,51 @@ +/** + * Copyright 2015 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.util.stereo; + +import com.jogamp.opengl.math.geom.Frustum; + +/** + * Constant parameter of the positioning sensor to locate the {@link ViewerPose}. + */ +public final class LocationSensorParameter { + /** The {@link Frustum} of the location sensor. */ + public final Frustum frustum; + /** The {@link Frustum}'s {@link Frustum.FovDesc} description of the location sensor. */ + public final Frustum.FovDesc frustumDesc; + /** The {@link Frustum}'s float[16] projection matrix of the location sensor. */ + public final float[] frustumProjMat; + + public LocationSensorParameter(final Frustum.FovDesc fovDesc) { + this.frustumDesc = fovDesc; + this.frustum = new Frustum(); + this.frustumProjMat = frustum.updateByFovDesc(new float[16], 0, true, fovDesc); + } + public final String toString() { + return "LocationSensor["+frustumDesc+"]"; + } +}
\ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/opengl/util/stereo/StereoDevice.java b/src/jogl/classes/com/jogamp/opengl/util/stereo/StereoDevice.java index 68d0f4b39..b6112650a 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/stereo/StereoDevice.java +++ b/src/jogl/classes/com/jogamp/opengl/util/stereo/StereoDevice.java @@ -117,6 +117,23 @@ public interface StereoDevice { public FovHVHalves[] getDefaultFOV(); /** + * Returns the {@link LocationSensorParameter} of the device + * if {@link #SENSOR_POSITION} is {@link #getSupportedSensorBits() supported}, + * otherwise returns {@code null}. + */ + public LocationSensorParameter getLocationSensorParams(); + + + /** + * Sets the location sensor's origin of this device to the current position. + * <p> + * In case {@link #SENSOR_POSITION} is not {@link #getSupportedSensorBits() supported}, + * this method is a no-op. + * </p> + */ + public void resetLocationSensorOrigin(); + + /** * Start desired and required sensors. Returns true if action was successful, otherwise false. * <p> * Method fails if required sensors are not {@link #getSupportedSensorBits() supported}. diff --git a/src/jogl/classes/com/jogamp/opengl/util/stereo/ViewerPose.java b/src/jogl/classes/com/jogamp/opengl/util/stereo/ViewerPose.java index 40411ac88..10ee4c994 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/stereo/ViewerPose.java +++ b/src/jogl/classes/com/jogamp/opengl/util/stereo/ViewerPose.java @@ -30,7 +30,7 @@ package com.jogamp.opengl.util.stereo; import com.jogamp.opengl.math.Quaternion; /** - * Position and orientation of viewer. + * {@link #position} and {@link #orientation} of viewer. */ public final class ViewerPose { /** diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 401ea29c6..8f4105f98 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -422,7 +422,7 @@ public abstract class GLContextImpl extends GLContext { lastCtxReleaseStack = new Throwable(msg); if( TRACE_SWITCH ) { System.err.println(msg); - // ExceptionUtils.dumpStackTrace(System.err, 0, 10); + // ExceptionUtils.dumpStack(System.err, 0, 10); } } } @@ -773,7 +773,7 @@ public abstract class GLContextImpl extends GLContext { } if ( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName() + ": Create GL context "+(created?"OK":"FAILED")+": For " + getClass().getName()+" - "+getGLVersion()+" - "+getTraceSwitchMsg()); - // ExceptionUtils.dumpStackTrace(System.err, 0, 10); + // ExceptionUtils.dumpStack(System.err, 0, 10); } if(!created) { return CONTEXT_NOT_CURRENT; diff --git a/src/jogl/classes/jogamp/opengl/ProjectFloat.java b/src/jogl/classes/jogamp/opengl/ProjectFloat.java index ee9560214..5ec5a8e3f 100644 --- a/src/jogl/classes/jogamp/opengl/ProjectFloat.java +++ b/src/jogl/classes/jogamp/opengl/ProjectFloat.java @@ -170,7 +170,8 @@ public class ProjectFloat { * @param aspect * @param zNear * @param zFar - * @throws GLException with GL_INVALID_VALUE if zNear is <= 0, or zFar < 0, or if zNear == zFar. + * @throws GLException if {@code zNear <= 0} or {@code zFar <= zNear} + * @see FloatUtil#makePerspective(float[], int, boolean, float, float, float, float) */ public void gluPerspective(final GLMatrixFunc gl, final float fovy_deg, final float aspect, final float zNear, final float zFar) throws GLException { gl.glMultMatrixf(FloatUtil.makePerspective(mat4Tmp1, 0, true, fovy_deg * FloatUtil.PI / 180.0f, aspect, zNear, zFar), 0); diff --git a/src/jogl/classes/jogamp/opengl/util/stereo/GenericStereoDevice.java b/src/jogl/classes/jogamp/opengl/util/stereo/GenericStereoDevice.java index 491535dc1..bfe93b59c 100644 --- a/src/jogl/classes/jogamp/opengl/util/stereo/GenericStereoDevice.java +++ b/src/jogl/classes/jogamp/opengl/util/stereo/GenericStereoDevice.java @@ -36,6 +36,7 @@ import com.jogamp.nativewindow.util.RectangleImmutable; import com.jogamp.opengl.math.FovHVHalves; import com.jogamp.opengl.util.stereo.StereoDeviceConfig; import com.jogamp.opengl.util.stereo.EyeParameter; +import com.jogamp.opengl.util.stereo.LocationSensorParameter; import com.jogamp.opengl.util.stereo.StereoDevice; import com.jogamp.opengl.util.stereo.StereoDeviceFactory; import com.jogamp.opengl.util.stereo.StereoDeviceRenderer; @@ -163,31 +164,27 @@ public class GenericStereoDevice implements StereoDevice { } @Override - public boolean isValid() { - return true; - } + public boolean isValid() { return true; } @Override - public final PointImmutable getPosition() { - return surfacePos; - } + public final PointImmutable getPosition() { return surfacePos; } @Override - public final DimensionImmutable getSurfaceSize() { - return config.surfaceSizeInPixels; - } + public final DimensionImmutable getSurfaceSize() { return config.surfaceSizeInPixels; } @Override public int getRequiredRotation() { return 0; } @Override - public float[] getDefaultEyePositionOffset() { - return config.defaultEyeParam[0].positionOffset; - } + public float[] getDefaultEyePositionOffset() { return config.defaultEyeParam[0].positionOffset; } @Override - public final FovHVHalves[] getDefaultFOV() { - return defaultEyeFov; - } + public final FovHVHalves[] getDefaultFOV() { return defaultEyeFov; } + + @Override + public final LocationSensorParameter getLocationSensorParams() { return null; } + + @Override + public final void resetLocationSensorOrigin() { } @Override public final boolean startSensors(final int desiredSensorBits, final int requiredSensorBits) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 62fd49092..cc70b6b7b 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -73,19 +73,42 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple } /** + * @deprecated Use {@link #create(GraphicsConfiguration, CapabilitiesImmutable, CapabilitiesImmutable)} + * Method constructs a new {@link AWTGraphicsConfiguration} primarily based + * on the given {@link Component}'s {@link GraphicsConfiguration}. + * @param awtComp the {@link Component}, which {@link GraphicsConfiguration} is used for the resulting {@link AWTGraphicsConfiguration} * @param capsChosen if null, <code>capsRequested</code> is copied and aligned * with the graphics {@link Capabilities} of the AWT Component to produce the chosen {@link Capabilities}. * Otherwise the <code>capsChosen</code> is used. * @param capsRequested if null, default {@link Capabilities} are used, otherwise the given values. */ - public static AWTGraphicsConfiguration create(final Component awtComp, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { - final GraphicsConfiguration awtGfxConfig = awtComp.getGraphicsConfiguration(); - if(null==awtGfxConfig) { - throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsConfiguration @ "+awtComp); + public static AWTGraphicsConfiguration create(final Component awtComp, final CapabilitiesImmutable capsChosen, final CapabilitiesImmutable capsRequested) { + if(null==awtComp) { + throw new IllegalArgumentException("Null AWT Component"); } - final GraphicsDevice awtGraphicsDevice = awtGfxConfig.getDevice(); + final GraphicsConfiguration gc = awtComp.getGraphicsConfiguration(); + if( null == gc ) { + throw new NativeWindowException("Null AWT GraphicsConfiguration @ "+awtComp); + } + return create(gc, capsChosen, capsRequested); + } + + /** + * Method constructs a new {@link AWTGraphicsConfiguration} primarily based + * on the given {@link GraphicsConfiguration}. + * @param gc the {@link GraphicsConfiguration} for the resulting {@link AWTGraphicsConfiguration} + * @param capsChosen if null, <code>capsRequested</code> is copied and aligned + * with the graphics {@link Capabilities} of the AWT Component to produce the chosen {@link Capabilities}. + * Otherwise the <code>capsChosen</code> is used. + * @param capsRequested if null, default {@link Capabilities} are used, otherwise the given values. + */ + public static AWTGraphicsConfiguration create(final GraphicsConfiguration gc, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { + if(null==gc) { + throw new IllegalArgumentException("Null AWT GraphicsConfiguration"); + } + final GraphicsDevice awtGraphicsDevice = gc.getDevice(); if(null==awtGraphicsDevice) { - throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsDevice @ "+awtGfxConfig); + throw new NativeWindowException("Null AWT GraphicsDevice @ "+gc); } // Create Device/Screen @@ -96,7 +119,6 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple capsRequested = new Capabilities(); } if(null==capsChosen) { - final GraphicsConfiguration gc = awtGraphicsDevice.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsRequested, gc); } final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(awtDevice, capsChosen); @@ -105,7 +127,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple return (AWTGraphicsConfiguration) config; } // System.err.println("Info: AWTGraphicsConfiguration.create: Expected AWTGraphicsConfiguration got: "+config.getClass()+" w/ factory "+factory.getClass()+" - Unable to encapsulate native GraphicsConfiguration."); - return new AWTGraphicsConfiguration(awtScreen, capsChosen, capsRequested, awtGfxConfig); + return new AWTGraphicsConfiguration(awtScreen, capsChosen, capsRequested, gc); } // open access to superclass method diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index d315e1876..5d84325de 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -49,7 +49,6 @@ import java.awt.Container; import java.awt.Cursor; import java.awt.EventQueue; import java.awt.GraphicsConfiguration; -import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; @@ -91,10 +90,10 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // lifetime: forever protected final Component component; private final AppContextInfo appContextInfo; - private final AWTGraphicsConfiguration config; // control access due to delegation private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); private final JAWTComponentListener jawtComponentListener; + private volatile AWTGraphicsConfiguration awtConfig; // control access through delegation // lifetime: valid after lock but may change with each 1st lock, purges after invalidate private boolean isApplet; @@ -128,9 +127,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } appContextInfo = new AppContextInfo("<init>"); this.component = (Component)comp; - this.config = (AWTGraphicsConfiguration) config; this.jawtComponentListener = new JAWTComponentListener(); invalidate(); + this.awtConfig = (AWTGraphicsConfiguration) config; this.isApplet = false; this.offscreenSurfaceLayer = 0; } @@ -138,7 +137,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private String jawtStr() { return "JAWTWindow["+id(JAWTWindow.this)+"]"; } private class JAWTComponentListener implements ComponentListener, HierarchyListener { - private boolean isShowing; + private volatile boolean isShowing; private String str(final Object obj) { if( null == obj ) { @@ -179,6 +178,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition .. @Override public void run() { + isShowing = component.isShowing(); // Bug 1161: Runnable might be deferred, hence need to update if(DEBUG) { System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString()); } @@ -248,7 +248,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, final java.awt.Component changed = e.getChanged(); final boolean displayable = changed.isDisplayable(); final boolean showing = changed.isShowing(); - System.err.println(jawtStr()+".hierarchyChanged: action "+action+", displayable "+displayable+", showing [changed "+showing+", comp "+isShowing+"], "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged: action "+action+", displayable "+displayable+", showing [changed "+showing+", comp "+wasShowing+" -> "+isShowing+"], "+s(e)); } } } @@ -265,6 +265,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } invalidateNative(); jawt = null; + awtConfig = null; isOffscreenLayerSurface = false; drawable= 0; drawable_old = 0; @@ -280,6 +281,34 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void invalidateNative(); + /** + * Set a new {@link AWTGraphicsConfiguration} instance, + * as required if {@link #getAWTComponent() upstream component}'s {@link GraphicsConfiguration} has been changed + * due to reconfiguration, e.g. moving to a different monitor or changed capabilities. + * <p> + * {@link #getAWTComponent() Upstream component} shall override {@link Component#getGraphicsConfiguration()}, + * which shall call this method if detecting a reconfiguration. + * See JOGL's GLCanvas and NewtCanvasAWT. + * </p> + * @param config the new {@link AWTGraphicsConfiguration} + * @see #getAWTGraphicsConfiguration() + */ + public final void setAWTGraphicsConfiguration(final AWTGraphicsConfiguration config) { + if(DEBUG) { + System.err.println(jawtStr()+".setAWTGraphicsConfiguration(): "+this.awtConfig+" -> "+config); + // Thread.dumpStack(); + } + this.awtConfig = config; + } + /** + * Return the current {@link AWTGraphicsConfiguration} instance, + * which also holds its {@link #getAWTComponent() upstream component}'s {@link GraphicsConfiguration} + * @see #setAWTGraphicsConfiguration(AWTGraphicsConfiguration) + */ + public final AWTGraphicsConfiguration getAWTGraphicsConfiguration() { + return awtConfig; + } + @Override public boolean setSurfaceScale(final float[] pixelScale) { System.arraycopy(pixelScale, 0, reqPixelScale, 0, 2); @@ -312,9 +341,10 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, /** * Updates bounds and pixelScale + * @param gc GraphicsConfiguration for {@link #updatePixelScale(GraphicsConfiguration, boolean)} * @return true if bounds or pixelScale has changed, otherwise false */ - protected final boolean updateLockedData(final JAWT_Rectangle jawtBounds) { + protected final boolean updateLockedData(final JAWT_Rectangle jawtBounds, final GraphicsConfiguration gc) { final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); final boolean changedBounds = !bounds.equals(jb); @@ -330,29 +360,31 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } } - updatePixelScale(false); + updatePixelScale(gc, false); return hasPixelScaleChanged || changedBounds; } /** * Updates the minimum and maximum pixel-scale values * and returns {@code true} if they were updated. + * @param gc pre-fetched {@link GraphicsConfiguration} instance of {@link #getAWTComponent() upstream component}, + * caller may use cached {@link #getAWTGraphicsConfiguration()}'s {@link AWTGraphicsConfiguration#getAWTGraphicsConfiguration() GC} + * or a {@link Component#getGraphicsConfiguration()}. * @param clearFlag if {@code true}, the {@code hasPixelScaleChanged} flag will be cleared * @return {@code true} if values were updated, otherwise {@code false}. * @see #hasPixelScaleChanged() + * @see #getAWTGraphicsConfiguration() + * @see Component#getGraphicsConfiguration() */ - public final boolean updatePixelScale(final boolean clearFlag) { - // Using GraphicsConfiguration from component, which may change by moving to diff monitor - if( EventQueue.isDispatchThread() || Thread.holdsLock(component.getTreeLock()) ) { - if( JAWTUtil.getPixelScale(component.getGraphicsConfiguration(), minPixelScale, maxPixelScale) ) { - hasPixelScaleChanged = true; - if( DEBUG ) { - System.err.println("JAWTWindow.updatePixelScale: updated req["+ - reqPixelScale[0]+", "+reqPixelScale[1]+"], min["+ - minPixelScale[0]+", "+minPixelScale[1]+"], max["+ - maxPixelScale[0]+", "+maxPixelScale[1]+"], has["+ - hasPixelScale[0]+", "+hasPixelScale[1]+"]"); - } + public final boolean updatePixelScale(final GraphicsConfiguration gc, final boolean clearFlag) { + if( JAWTUtil.getPixelScale(gc, minPixelScale, maxPixelScale) ) { + hasPixelScaleChanged = true; + if( DEBUG ) { + System.err.println("JAWTWindow.updatePixelScale: updated req["+ + reqPixelScale[0]+", "+reqPixelScale[1]+"], min["+ + minPixelScale[0]+", "+minPixelScale[1]+"], max["+ + maxPixelScale[0]+", "+maxPixelScale[1]+"], has["+ + hasPixelScale[0]+", "+hasPixelScale[1]+"]"); } } if( clearFlag ) { @@ -363,6 +395,26 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return hasPixelScaleChanged; } } + /** + * @deprecated Use {@link #updatePixelScale(GraphicsConfiguration, boolean)}. + */ + public final boolean updatePixelScale(final boolean clearFlag) { + return updatePixelScale(awtConfig.getAWTGraphicsConfiguration(), clearFlag); + } + + /** + * @deprecated Use {@link #updateLockedData(JAWT_Rectangle, GraphicsConfiguration)}. + */ + protected final boolean updateLockedData(final JAWT_Rectangle jawtBounds) { + throw new RuntimeException("Invalid API entry"); + } + /** + * @deprecated Use {@link #lockSurfaceImpl(GraphicsConfiguration)} + */ + protected int lockSurfaceImpl() throws NativeWindowException { + throw new RuntimeException("Invalid API entry"); + } + /** * Returns and clears the {@code hasPixelScaleChanged} flag, as set via {@link #lockSurface()}. @@ -386,7 +438,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * @return true if pixelScale has changed, otherwise false */ protected final boolean setReqPixelScale() { - updatePixelScale(true); + updatePixelScale(awtConfig.getAWTGraphicsConfiguration(), true); return SurfaceScaleUtils.setNewPixelScale(hasPixelScale, hasPixelScale, reqPixelScale, minPixelScale, maxPixelScale, DEBUG ? getClass().getSimpleName() : null); } @@ -527,7 +579,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public final void setChosenCapabilities(final CapabilitiesImmutable caps) { ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); - config.setChosenCapabilities(caps); + awtConfig.setChosenCapabilities(caps); } @Override @@ -591,7 +643,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * @throws NativeWindowException */ protected abstract JAWT fetchJAWTImpl() throws NativeWindowException; - protected abstract int lockSurfaceImpl() throws NativeWindowException; + protected abstract int lockSurfaceImpl(GraphicsConfiguration gc) throws NativeWindowException; protected void dumpJAWTInfo() { System.err.println(jawt2String(null).toString()); @@ -612,6 +664,19 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, ExceptionUtils.dumpStack(System.err); } } else { + final GraphicsConfiguration gc; + if( EventQueue.isDispatchThread() || Thread.holdsLock(component.getTreeLock()) ) { + /** + * Trigger detection of possible reconfiguration before 'sun.awt.SunToolkit.awtLock()', + * which maybe triggered via adevice.lock() below (X11). + * See setAWTGraphicsConfiguration(..). + */ + gc = component.getGraphicsConfiguration(); + } else { + // Reuse cached instance + gc = awtConfig.getAWTGraphicsConfiguration(); + } + determineIfApplet(); try { final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); @@ -621,7 +686,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, jawt = fetchJAWTImpl(); isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); } - res = lockSurfaceImpl(); + res = lockSurfaceImpl(gc); if(LOCK_SUCCESS == res && drawable_old != drawable) { res = LOCK_SURFACE_CHANGED; if(DEBUG) { @@ -706,7 +771,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { - return config.getNativeGraphicsConfiguration(); + return awtConfig.getNativeGraphicsConfiguration(); } @Override @@ -877,7 +942,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, "], pixels[scale "+getPixelScaleX()+", "+getPixelScaleY()+" -> "+getSurfaceWidth()+"x"+getSurfaceHeight()+"]"+ ", visible "+component.isVisible()); sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+ - ",\n\tconfig "+config+ + ",\n\tconfig "+awtConfig+ ",\n\tawtComponent "+getAWTComponent()+ ",\n\tsurfaceLock "+surfaceLock+"]"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 6f3f1ed6b..264bdf9d3 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -41,6 +41,7 @@ package jogamp.nativewindow.jawt.macosx; import java.awt.Component; +import java.awt.GraphicsConfiguration; import java.nio.Buffer; import java.security.AccessController; import java.security.PrivilegedAction; @@ -242,7 +243,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } @Override - protected int lockSurfaceImpl() throws NativeWindowException { + protected int lockSurfaceImpl(final GraphicsConfiguration gc) throws NativeWindowException { int ret = NativeSurface.LOCK_SURFACE_NOT_READY; ds = getJAWT().GetDrawingSurface(component); if (ds == null) { @@ -279,7 +280,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { unlockSurfaceImpl(); return NativeSurface.LOCK_SURFACE_NOT_READY; } - updateLockedData(dsi.getBounds()); + updateLockedData(dsi.getBounds(), gc); if (DEBUG && firstLock ) { dumpInfo(); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java index a6c9452af..655dadd6b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java @@ -40,6 +40,8 @@ package jogamp.nativewindow.jawt.windows; +import java.awt.GraphicsConfiguration; + import com.jogamp.nativewindow.AbstractGraphicsConfiguration; import com.jogamp.nativewindow.NativeSurface; import com.jogamp.nativewindow.NativeWindow; @@ -72,7 +74,7 @@ public class WindowsJAWTWindow extends JAWTWindow { } @Override - protected int lockSurfaceImpl() throws NativeWindowException { + protected int lockSurfaceImpl(final GraphicsConfiguration gc) throws NativeWindowException { int ret = NativeSurface.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); if (ds == null) { @@ -99,7 +101,7 @@ public class WindowsJAWTWindow extends JAWTWindow { unlockSurfaceImpl(); return LOCK_SURFACE_NOT_READY; } - updateLockedData(dsi.getBounds()); + updateLockedData(dsi.getBounds(), gc); win32dsi = (JAWT_Win32DrawingSurfaceInfo) dsi.platformInfo(getJAWT()); if (win32dsi == null) { unlockSurfaceImpl(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index 2620b60e0..80cf3ba6f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -37,6 +37,8 @@ package jogamp.nativewindow.jawt.x11; +import java.awt.GraphicsConfiguration; + import com.jogamp.nativewindow.AbstractGraphicsConfiguration; import com.jogamp.nativewindow.NativeSurface; import com.jogamp.nativewindow.NativeWindow; @@ -67,7 +69,7 @@ public class X11JAWTWindow extends JAWTWindow { } @Override - protected int lockSurfaceImpl() throws NativeWindowException { + protected int lockSurfaceImpl(final GraphicsConfiguration gc) throws NativeWindowException { int ret = NativeSurface.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); if (ds == null) { @@ -94,7 +96,7 @@ public class X11JAWTWindow extends JAWTWindow { unlockSurfaceImpl(); return LOCK_SURFACE_NOT_READY; } - updateLockedData(dsi.getBounds()); + updateLockedData(dsi.getBounds(), gc); x11dsi = (JAWT_X11DrawingSurfaceInfo) dsi.platformInfo(getJAWT()); if (x11dsi == null) { unlockSurfaceImpl(); diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 5920d6de8..ae32fd164 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -37,6 +37,7 @@ import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; import java.awt.KeyboardFocusManager; import java.awt.geom.NoninvertibleTransformException; import java.beans.Beans; @@ -47,6 +48,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Set; +import com.jogamp.nativewindow.CapabilitiesImmutable; import com.jogamp.nativewindow.NativeWindow; import com.jogamp.nativewindow.OffscreenLayerOption; import com.jogamp.nativewindow.WindowClosingProtocol; @@ -71,6 +73,7 @@ import jogamp.opengl.awt.AWTTilePainter; import com.jogamp.common.ExceptionUtils; import com.jogamp.common.util.awt.AWTEDTExecutor; +import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration; import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.nativewindow.awt.JAWTWindow; @@ -101,7 +104,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto public static final boolean DEBUG = Debug.debug("Window"); private final Object sync = new Object(); - private JAWTWindow jawtWindow = null; + private volatile JAWTWindow jawtWindow = null; // the JAWTWindow presentation of this AWT Canvas, bound to the 'drawable' lifecycle private boolean isApplet = false; private boolean shallUseOffscreenLayer = false; private Window newtChild = null; @@ -112,6 +115,8 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private final AWTAdapter awtMouseAdapter; private final AWTAdapter awtKeyAdapter; + private volatile AWTGraphicsConfiguration awtConfig; + /** Mitigates Bug 910 (IcedTea-Web), i.e. crash via removeNotify() invoked before Applet.destroy(). */ private boolean destroyJAWTPending = false; /** Mitigates Bug 910 (IcedTea-Web), i.e. crash via removeNotify() invoked before Applet.destroy(). */ @@ -452,14 +457,142 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } + private void setAWTGraphicsConfiguration(final AWTGraphicsConfiguration config) { + // Cache awtConfig + awtConfig = config; + if( null != jawtWindow ) { + // Notify JAWTWindow .. + jawtWindow.setAWTGraphicsConfiguration(config); + } + } + + /** + * {@inheritDoc} + * <p> + * Overridden to choose a {@link GraphicsConfiguration} from a parent container's + * {@link GraphicsDevice}. + * </p> + * <p> + * Method also intercepts {@link GraphicsConfiguration} changes regarding to + * its capabilities and its {@link GraphicsDevice}. This may happen in case + * the display changes its configuration or the component is moved to another screen. + * </p> + */ + @Override + public GraphicsConfiguration getGraphicsConfiguration() { + /** + * parentGC will be null unless: + * - A native peer has assigned it. This means we have a native + * peer, and are already committed to a graphics configuration. + * - This canvas has been added to a component hierarchy and has + * an ancestor with a non-null GC, but the native peer has not + * yet been created. This means we can still choose the GC on + * all platforms since the peer hasn't been created. + */ + final GraphicsConfiguration parentGC = super.getGraphicsConfiguration(); + + if( Beans.isDesignTime() ) { + return parentGC; + } + final GraphicsConfiguration oldGC = null != awtConfig ? awtConfig.getAWTGraphicsConfiguration() : null; + + if ( null != parentGC && null != oldGC && !oldGC.equals(parentGC) ) { + // Previous oldGC != parentGC of native peer + + if ( !oldGC.getDevice().getIDstring().equals(parentGC.getDevice().getIDstring()) ) { + // Previous oldGC's GraphicsDevice != parentGC's GraphicsDevice of native peer + + /** + * Here we select a GraphicsConfiguration on the alternate device. + * In case the new configuration differs (-> !equalCaps), + * we might need a reconfiguration, + */ + final AWTGraphicsConfiguration newConfig = AWTGraphicsConfiguration.create(parentGC, + awtConfig.getChosenCapabilities(), + awtConfig.getRequestedCapabilities()); + final GraphicsConfiguration newGC = newConfig.getAWTGraphicsConfiguration(); + final boolean equalCaps = newConfig.getChosenCapabilities().equals(awtConfig.getChosenCapabilities()); + if(DEBUG) { + System.err.println(getThreadName()+": getGraphicsConfiguration() Info: Changed GC and GD"); + System.err.println("Created Config (n): Old GC "+oldGC); + System.err.println("Created Config (n): Old GD "+oldGC.getDevice().getIDstring()); + System.err.println("Created Config (n): Parent GC "+parentGC); + System.err.println("Created Config (n): Parent GD "+parentGC.getDevice().getIDstring()); + System.err.println("Created Config (n): New GC "+newGC); + System.err.println("Created Config (n): Old CF "+awtConfig); + System.err.println("Created Config (n): New CF "+newConfig); + System.err.println("Created Config (n): EQUALS CAPS "+equalCaps); + // Thread.dumpStack(); + } + if ( null != newGC ) { + setAWTGraphicsConfiguration(newConfig); + /** + * Return the newGC, which covers the desired capabilities and is compatible + * with the available GC's of its devices. + */ + if(DEBUG) { + System.err.println(getThreadName()+": Info: getGraphicsConfiguration - end.01: newGC "+newGC); + } + return newGC; + } else { + if(DEBUG) { + System.err.println(getThreadName()+": Info: getGraphicsConfiguration - end.00: oldGC "+oldGC); + } + } + } + /** + * If a new GC was _not_ found/defined above, + * method returns oldGC as selected in the constructor or first addNotify(). + * This may cause an exception in Component.checkGD when adding to a + * container, and is the desired behavior. + */ + return oldGC; + } else if (null == parentGC) { + /** + * The parentGC is null, which means we have no native peer, and are not + * part of a (realized) component hierarchy. So we return the + * desired visual that was selected in the constructor (possibly + * null). + */ + return oldGC; + } else { + /** + * Otherwise we have not explicitly selected a GC in the constructor, so + * just return what Canvas would have. + */ + return parentGC; + } + } + private static String getThreadName() { return Thread.currentThread().getName(); } + @Override public void addNotify() { if( Beans.isDesignTime() ) { super.addNotify(); } else { + /** + * 'super.addNotify()' determines the GraphicsConfiguration, + * while calling this class's overridden 'getGraphicsConfiguration()' method + * after which it creates the native peer. + * Hence we have to set the 'awtConfig' before since it's GraphicsConfiguration + * is being used in getGraphicsConfiguration(). + * This code order also allows recreation, ie re-adding the GLCanvas. + */ // before native peer is valid: X11 disableBackgroundErase(); + // Query AWT GraphicsDevice from parent tree, default + final GraphicsConfiguration gc = super.getGraphicsConfiguration(); + if(null==gc) { + throw new GLException("Error: NULL AWT GraphicsConfiguration"); + } + final CapabilitiesImmutable capsReq = null != newtChild ? newtChild.getRequestedCapabilities() : null; + final AWTGraphicsConfiguration awtConfig = AWTGraphicsConfiguration.create(gc, null, capsReq); + if(null==awtConfig) { + throw new GLException("Error: NULL AWTGraphicsConfiguration"); + } + setAWTGraphicsConfiguration(awtConfig); + // creates the native peer super.addNotify(); @@ -472,7 +605,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto System.err.println("NewtCanvasAWT.addNotify.0 - isApplet "+isApplet+", addedOnAWTEDT "+EventQueue.isDispatchThread()+" @ "+currentThreadName()); ExceptionUtils.dumpStack(System.err); } - jawtWindow = NewtFactoryAWT.getNativeWindow(NewtCanvasAWT.this, null != newtChild ? newtChild.getRequestedCapabilities() : null); + jawtWindow = NewtFactoryAWT.getNativeWindow(NewtCanvasAWT.this, awtConfig); jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); // enforce initial lock on AWT-EDT, allowing acquisition of pixel-scale jawtWindow.lockSurface(); @@ -493,8 +626,8 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } } - private final boolean updatePixelScale() { - if( jawtWindow.updatePixelScale(true) ) { + private final boolean updatePixelScale(final GraphicsConfiguration gc) { + if( jawtWindow.updatePixelScale(gc, true) ) { final Window cWin = newtChild; final Window dWin = cWin.getDelegatedWindow(); if( dWin instanceof WindowImpl ) { @@ -585,6 +718,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } else { NewtFactoryAWT.destroyNativeWindow(jawtWindow); jawtWindow=null; + awtConfig=null; destroyJAWTPending = false; } } @@ -614,7 +748,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto System.err.println("NewtCanvasAWT.reshape: "+x+"/"+y+" "+width+"x"+height); } if( validateComponent(true) ) { - if( !printActive && updatePixelScale() ) { + if( !printActive && updatePixelScale(getGraphicsConfiguration()) ) { // NOP } else { // newtChild.setSize(width, height); diff --git a/src/newt/classes/com/jogamp/newt/opengl/util/stereo/StereoDeviceUtil.java b/src/newt/classes/com/jogamp/newt/opengl/util/stereo/StereoDeviceUtil.java index 24eba6ec1..3586aaa4b 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/util/stereo/StereoDeviceUtil.java +++ b/src/newt/classes/com/jogamp/newt/opengl/util/stereo/StereoDeviceUtil.java @@ -90,6 +90,8 @@ public class StereoDeviceUtil { System.err.println("StereoDevice Set Mode: "+newMode); monitor.setCurrentMode(newMode); } + final MonitorMode queriedMode = monitor.queryCurrentMode(); + System.err.println("StereoDevice Post-Set Mode: "+queriedMode); } else { System.err.println("StereoDevice Keeps Mode: "+currentMode); } diff --git a/src/newt/classes/com/jogamp/newt/util/applet/JOGLNewtApplet3Run.java b/src/newt/classes/com/jogamp/newt/util/applet3/JOGLNewtApplet3Run.java index 6ea63f69c..9b9b7d532 100644 --- a/src/newt/classes/com/jogamp/newt/util/applet/JOGLNewtApplet3Run.java +++ b/src/newt/classes/com/jogamp/newt/util/applet3/JOGLNewtApplet3Run.java @@ -25,7 +25,7 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ -package com.jogamp.newt.util.applet; +package com.jogamp.newt.util.applet3; import java.util.Locale; @@ -48,6 +48,7 @@ import com.jogamp.nativewindow.UpstreamWindowHookMutableSizePos; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Window; import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.newt.util.applet.JOGLNewtAppletBase; /** * Simple GLEventListener deployment as an applet using JOGL. This demo must be diff --git a/src/newt/classes/com/jogamp/newt/util/applet/VersionApplet3.java b/src/newt/classes/com/jogamp/newt/util/applet3/VersionApplet3.java index 518337d20..c864805ab 100644 --- a/src/newt/classes/com/jogamp/newt/util/applet/VersionApplet3.java +++ b/src/newt/classes/com/jogamp/newt/util/applet3/VersionApplet3.java @@ -1,4 +1,4 @@ -package com.jogamp.newt.util.applet; +package com.jogamp.newt.util.applet3; import com.jogamp.plugin.applet.Applet3; import com.jogamp.plugin.applet.Applet3Context; diff --git a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java index 8eaca7c0e..cc71fb559 100644 --- a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java +++ b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java @@ -28,8 +28,6 @@ package jogamp.newt.awt; -import java.awt.GraphicsDevice; - import com.jogamp.nativewindow.AbstractGraphicsConfiguration; import com.jogamp.nativewindow.CapabilitiesImmutable; import com.jogamp.nativewindow.NativeWindow; @@ -57,6 +55,8 @@ public class NewtFactoryAWT extends NewtFactory { public static final boolean DEBUG_IMPLEMENTATION = Debug.debug("Window"); /** + * @deprecated Use {@link #getNativeWindow(java.awt.Component, AWTGraphicsConfiguration)} + * * Wraps an AWT component into a {@link com.jogamp.nativewindow.NativeWindow} utilizing the {@link com.jogamp.nativewindow.NativeWindowFactory},<br> * using a configuration agnostic dummy {@link com.jogamp.nativewindow.DefaultGraphicsConfiguration}.<br> * <p> @@ -78,9 +78,37 @@ public class NewtFactoryAWT extends NewtFactory { return getNativeWindow( (java.awt.Component) awtCompObject, capsRequested ); } + /** + * @deprecated Use {@link #getNativeWindow(java.awt.Component, AWTGraphicsConfiguration)} + * @param awtComp + * @param capsRequested + * @return + */ public static JAWTWindow getNativeWindow(final java.awt.Component awtComp, final CapabilitiesImmutable capsRequested) { - final AWTGraphicsConfiguration config = AWTGraphicsConfiguration.create(awtComp, null, capsRequested); - final NativeWindow nw = NativeWindowFactory.getNativeWindow(awtComp, config); // a JAWTWindow + final AWTGraphicsConfiguration awtConfig = AWTGraphicsConfiguration.create(awtComp, null, capsRequested); + return getNativeWindow(awtComp, awtConfig); + } + + /** + * Wraps an AWT component into a {@link com.jogamp.nativewindow.NativeWindow} utilizing the {@link com.jogamp.nativewindow.NativeWindowFactory},<br> + * using the given {@link AWTGraphicsConfiguration}. + * <p> + * The actual wrapping implementation is {@link com.jogamp.nativewindow.awt.JAWTWindow}. + * </p> + * <p> + * The required {@link AWTGraphicsConfiguration} may be constructed via + * {@link AWTGraphicsConfiguration#create(java.awt.GraphicsConfiguration, CapabilitiesImmutable, CapabilitiesImmutable)} + * </p> + * <p> + * Purpose of this wrapping is to access the AWT window handle,<br> + * not to actually render into it. + * </p> + * + * @param awtComp {@link java.awt.Component} + * @param awtConfig {@link AWTGraphicsConfiguration} reflecting the used {@link java.awt.GraphicsConfiguration} + */ + public static JAWTWindow getNativeWindow(final java.awt.Component awtComp, final AWTGraphicsConfiguration awtConfig) { + final NativeWindow nw = NativeWindowFactory.getNativeWindow(awtComp, awtConfig); // a JAWTWindow if(! ( nw instanceof JAWTWindow ) ) { throw new NativeWindowException("Not an AWT NativeWindow: "+nw); } @@ -101,13 +129,15 @@ public class NewtFactoryAWT extends NewtFactory { * @throws IllegalArgumentException if {@code awtComp} is not {@link java.awt.Component#isDisplayable() displayable} * or has {@code null} {@link java.awt.Component#getGraphicsConfiguration() GraphicsConfiguration}. */ - private static void checkComponentValid(final java.awt.Component awtComp) throws IllegalArgumentException { + private static java.awt.GraphicsConfiguration checkComponentValid(final java.awt.Component awtComp) throws IllegalArgumentException { if( !awtComp.isDisplayable() ) { throw new IllegalArgumentException("Given AWT-Component is not displayable: "+awtComp); } - if( null == awtComp.getGraphicsConfiguration() ) { + final java.awt.GraphicsConfiguration gc = awtComp.getGraphicsConfiguration(); + if( null == gc ) { throw new IllegalArgumentException("Given AWT-Component has no GraphicsConfiguration set: "+awtComp); } + return gc; } /** @@ -120,8 +150,8 @@ public class NewtFactoryAWT extends NewtFactory { * @see #getAbstractGraphicsScreen(java.awt.Component) */ public static Display createDisplay(final java.awt.Component awtComp, final boolean reuse) throws IllegalArgumentException { - checkComponentValid(awtComp); - final GraphicsDevice device = awtComp.getGraphicsConfiguration().getDevice(); + final java.awt.GraphicsConfiguration gc = checkComponentValid(awtComp); + final java.awt.GraphicsDevice device = gc.getDevice(); final String displayConnection; final String nwt = NativeWindowFactory.getNativeWindowType(true); @@ -174,13 +204,13 @@ public class NewtFactoryAWT extends NewtFactory { * @see #createScreen(java.awt.Component, boolean) */ public static MonitorDevice getMonitorDevice(final Screen screen, final java.awt.Component awtComp) throws IllegalArgumentException { - checkComponentValid(awtComp); + final java.awt.GraphicsConfiguration gc = checkComponentValid(awtComp); final String nwt = NativeWindowFactory.getNativeWindowType(true); MonitorDevice res = null; screen.addReference(); try { if( NativeWindowFactory.TYPE_MACOSX == nwt ) { - res = screen.getMonitor( JAWTUtil.getMonitorDisplayID( awtComp.getGraphicsConfiguration().getDevice() ) ); + res = screen.getMonitor( JAWTUtil.getMonitorDisplayID( gc.getDevice() ) ); } if( null == res ) { // Fallback, use AWT component coverage diff --git a/src/oculusvr/classes/com/jogamp/oculusvr/OVRVersion.java b/src/oculusvr/classes/com/jogamp/oculusvr/OVRVersion.java index 1b85e8450..6269ce4e9 100644 --- a/src/oculusvr/classes/com/jogamp/oculusvr/OVRVersion.java +++ b/src/oculusvr/classes/com/jogamp/oculusvr/OVRVersion.java @@ -107,20 +107,23 @@ public class OVRVersion extends JogampVersion { if(null==sb) { sb = new StringBuilder(); } - sb.append("\thmd."+ovrHmdIndex+".productName:\t"+hmdDesc.getProductNameAsString()).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".vendorName:\t"+hmdDesc.getManufacturerAsString()).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".deviceName:\t"+hmdDesc.getDisplayDeviceNameAsString()).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".productId:\t0x"+Integer.toHexString(hmdDesc.getProductId())).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".vendorId:\t0x"+Integer.toHexString(hmdDesc.getVendorId())).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".serial:\t"+hmdDesc.getSerialNumberAsString()).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".type:\t"+hmdDesc.getType()).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".hmdCaps:\t"+toHexString(hmdDesc.getHmdCaps())).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".distorCaps:\t"+toHexString(hmdDesc.getDistortionCaps())).append(Platform.getNewline()); - sb.append("\thmd."+ovrHmdIndex+".sensorCaps:\t"+toHexString(hmdDesc.getTrackingCaps())).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".productName: "+hmdDesc.getProductNameAsString()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".vendorName: "+hmdDesc.getManufacturerAsString()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".deviceName: "+hmdDesc.getDisplayDeviceNameAsString()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".productId: 0x"+Integer.toHexString(hmdDesc.getProductId())).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".vendorId: 0x"+Integer.toHexString(hmdDesc.getVendorId())).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".serial: "+hmdDesc.getSerialNumberAsString()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".firmware: "+hmdDesc.getFirmwareMajor()+"."+hmdDesc.getFirmwareMinor()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".type: "+hmdDesc.getType()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".hmdCaps: "+toHexString(hmdDesc.getHmdCaps())).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".distorCaps: "+toHexString(hmdDesc.getDistortionCaps())).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".sensorCaps: "+toHexString(hmdDesc.getTrackingCaps())).append(Platform.getNewline()); final ovrSizei resolution = hmdDesc.getResolution(); - sb.append("\thmd."+ovrHmdIndex+".resolution:\t"+resolution.getW()+"x"+resolution.getH()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".resolution: "+resolution.getW()+"x"+resolution.getH()).append(Platform.getNewline()); final ovrVector2i winPos = hmdDesc.getWindowsPos(); - sb.append("\thmd."+ovrHmdIndex+".winPos:\t"+winPos.getX()+" / "+winPos.getY()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".winPos: "+winPos.getX()+" / "+winPos.getY()).append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".cameraFrustum.Z: "+hmdDesc.getCameraFrustumNearZInMeters()+" - "+hmdDesc.getCameraFrustumFarZInMeters()+" meter").append(Platform.getNewline()); + sb.append("\thmd."+ovrHmdIndex+".cameraFrustum.Fov: H "+hmdDesc.getCameraFrustumHFovInRadians()+" rad, V "+hmdDesc.getCameraFrustumVFovInRadians()+" rad").append(Platform.getNewline()); return sb; } private static String toHexString(final int v) { return "0x"+Integer.toHexString(v); } diff --git a/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDevice.java b/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDevice.java index fc46a9aab..5025e80c5 100644 --- a/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDevice.java +++ b/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDevice.java @@ -40,6 +40,8 @@ import com.jogamp.oculusvr.ovrHmdDesc; import com.jogamp.oculusvr.ovrSizei; import com.jogamp.oculusvr.ovrTrackingState; import com.jogamp.opengl.math.FovHVHalves; +import com.jogamp.opengl.math.geom.Frustum; +import com.jogamp.opengl.util.stereo.LocationSensorParameter; import com.jogamp.opengl.util.stereo.StereoDevice; import com.jogamp.opengl.util.stereo.StereoDeviceFactory; import com.jogamp.opengl.util.stereo.StereoDeviceRenderer; @@ -69,6 +71,8 @@ public class OVRStereoDevice implements StereoDevice { private final PointImmutable position; private final int dkVersion; + private final LocationSensorParameter locationSensorParams; + public OVRStereoDevice(final StereoDeviceFactory factory, final ovrHmdDesc hmdDesc, final int deviceIndex) { if( null == hmdDesc ) { throw new IllegalArgumentException("Passed null hmdDesc"); @@ -81,6 +85,7 @@ public class OVRStereoDevice implements StereoDevice { this.handle = nativeContext; this.deviceIndex = deviceIndex; this.hmdDesc = hmdDesc; + final ovrFovPort[] defaultOVREyeFov = hmdDesc.getDefaultEyeFov(0, new ovrFovPort[ovrHmdDesc.getEyeRenderOrderArrayLength()]); defaultEyeFov = new FovHVHalves[defaultOVREyeFov.length]; for(int i=0; i<defaultEyeFov.length; i++) { @@ -95,6 +100,21 @@ public class OVRStereoDevice implements StereoDevice { usedSensorBits = 0; supportedSensorBits = OVRUtil.ovrTrackingCaps2SensorBits(hmdDesc.getTrackingCaps()); + LocationSensorParameter _locationSensorParams = null; + if( StereoUtil.usesPositionSensor(supportedSensorBits)) { + try { + final FovHVHalves posFov = FovHVHalves.byRadians(hmdDesc.getCameraFrustumHFovInRadians(), + hmdDesc.getCameraFrustumVFovInRadians()); + final float posZNear = hmdDesc.getCameraFrustumNearZInMeters(); + final float posZFar = hmdDesc.getCameraFrustumFarZInMeters(); + _locationSensorParams = new LocationSensorParameter(new Frustum.FovDesc(posFov, posZNear, posZFar)); + } catch (final IllegalArgumentException iae) { + // probably zNear/zFar issue .. + System.err.println(iae.getMessage()); + } + } + locationSensorParams = _locationSensorParams; + // DK1 delivers unrotated resolution in target orientation // DK2 delivers rotated resolution in target orientation, monitor screen is rotated 90deg clockwise deviceName = hmdDesc.getDisplayDeviceNameAsString(); @@ -132,7 +152,8 @@ public class OVRStereoDevice implements StereoDevice { "], recommended ["+StereoUtil.distortionBitsToString(getRecommendedDistortionBits())+ "], minimum ["+StereoUtil.distortionBitsToString(getMinimumDistortionBits())+"]]"); sb.append(", sensorBits[supported ["+StereoUtil.sensorBitsToString(getSupportedSensorBits())+ - "], enabled ["+StereoUtil.sensorBitsToString(getEnabledSensorBits())+"]]]"); + "], enabled ["+StereoUtil.sensorBitsToString(getEnabledSensorBits())+"]]"); + sb.append(", "+locationSensorParams+"]"); return sb.toString(); } @@ -160,16 +181,22 @@ public class OVRStereoDevice implements StereoDevice { public int getRequiredRotation() { return requiredRotation; } @Override - public float[] getDefaultEyePositionOffset() { - return DEFAULT_EYE_POSITION_OFFSET; - } + public float[] getDefaultEyePositionOffset() { return DEFAULT_EYE_POSITION_OFFSET; } @Override - public final FovHVHalves[] getDefaultFOV() { - return defaultEyeFov; + public final FovHVHalves[] getDefaultFOV() { return defaultEyeFov; } + + @Override + public final LocationSensorParameter getLocationSensorParams() { return locationSensorParams; } + + @Override + public final void resetLocationSensorOrigin() { + if( isValid() && sensorsStarted && StereoUtil.usesPositionSensor(supportedSensorBits)) { + OVR.ovrHmd_RecenterPose(hmdDesc); + } } - public void updateUsedSensorBits(final ovrTrackingState trackingState) { + /* pp */ void updateUsedSensorBits(final ovrTrackingState trackingState) { final int pre = usedSensorBits; if( sensorsStarted && null != trackingState ) { usedSensorBits = StereoDevice.SENSOR_ORIENTATION | @@ -188,7 +215,7 @@ public class OVRStereoDevice implements StereoDevice { @Override public final boolean startSensors(final int desiredSensorBits, final int requiredSensorBits) { - if( !sensorsStarted ) { + if( isValid() && !sensorsStarted ) { if( requiredSensorBits != ( supportedSensorBits & requiredSensorBits ) ) { // required sensors not available if( StereoDevice.DEBUG ) { @@ -228,7 +255,7 @@ public class OVRStereoDevice implements StereoDevice { } @Override public final boolean stopSensors() { - if( sensorsStarted ) { + if( isValid() && sensorsStarted ) { OVR.ovrHmd_ConfigureTracking(hmdDesc, 0, 0); // STOP sensorsStarted = false; usedSensorBits = 0; diff --git a/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDeviceRenderer.java b/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDeviceRenderer.java index 7d05bb7ac..95565dd0f 100644 --- a/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDeviceRenderer.java +++ b/src/oculusvr/classes/jogamp/opengl/oculusvr/OVRStereoDeviceRenderer.java @@ -357,7 +357,7 @@ public class OVRStereoDeviceRenderer implements StereoDeviceRenderer { private final OVREye[] eyes; private final ovrPosef[] ovrEyePoses; private final ovrVector3f[] hmdToEyeViewOffset; - private final ViewerPose eyePoses; + private final ViewerPose viewerPose; private final ovrTrackingState trackingState; private final int distortionBits; private final int textureCount; @@ -431,7 +431,7 @@ public class OVRStereoDeviceRenderer implements StereoDeviceRenderer { hmdToEyeViewOffset = new ovrVector3f[2]; hmdToEyeViewOffset[0] = eyes[0].ovrEyeDesc.getHmdToEyeViewOffset(); hmdToEyeViewOffset[1] = eyes[1].ovrEyeDesc.getHmdToEyeViewOffset(); - eyePoses = new ViewerPose(); + viewerPose = new ViewerPose(); trackingState = ovrTrackingState.create(); sp = null; @@ -551,14 +551,18 @@ public class OVRStereoDeviceRenderer implements StereoDeviceRenderer { // where ovrEyePoses already have hmdToEyeViewOffset applied (IPD .. etc). final ovrPosef pose = trackingState.getHeadPose().getThePose(); final ovrVector3f pos = pose.getPosition(); - eyePoses.setPosition(pos.getX(), pos.getY(), pos.getZ()); - OVRUtil.copyToQuaternion(pose.getOrientation(), eyePoses.orientation); - return eyePoses; + viewerPose.setPosition(pos.getX(), pos.getY(), pos.getZ()); + OVRUtil.copyToQuaternion(pose.getOrientation(), viewerPose.orientation); + + // System.err.println("Viewer: "+OVRUtil.toString(pos)); + // System.err.println("Camera: "+OVRUtil.toString(trackingState.getCameraPose().getPosition())); + // System.err.println("Leveld: "+OVRUtil.toString(trackingState.getLeveledCameraPose().getPosition())); + return viewerPose; } @Override public final ViewerPose getLastViewerPose() { - return eyePoses; + return viewerPose; } @Override diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestBug1146GLContextDialogToolTipAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestBug1146GLContextDialogToolTipAWT.java new file mode 100644 index 000000000..42646c07e --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestBug1146GLContextDialogToolTipAWT.java @@ -0,0 +1,238 @@ +/** + * Copyright 2015 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.AWTException; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Window; +import java.lang.reflect.InvocationTargetException; +import java.util.Locale; + +import javax.swing.AbstractButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.jogamp.common.os.Platform; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLCapabilitiesImmutable; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.DumpGLInfo; +import com.jogamp.opengl.test.junit.util.GLClearColor; +import com.jogamp.opengl.test.junit.util.GLEventListenerCounter; +import com.jogamp.opengl.test.junit.util.UITestCase; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug1146GLContextDialogToolTipAWT extends UITestCase { + static final int NB_TEST = 5; + static final int ACTION_DELAY = 500; + static final int MOVE_DELAY = 2; + static final int MOVE_ITER = 100; + static final int TOOLTIP_WAIT = 3*1000; // 5s + + static AbstractButton findButton(final int depth, final Container c, final String buttonText) { + AbstractButton res = null; + final int cc = c.getComponentCount(); + for(int i=0; null==res && i<cc; i++) { + final Component e = c.getComponent(i); + // System.err.println("["+depth+"]["+i+"]: "+e.getClass().getSimpleName()+": "+e); + if( e instanceof AbstractButton ) { + final AbstractButton b = (AbstractButton) e; + final String bT = b.getText(); + if( buttonText.equals(bT) ) { + res = b; + } + } else if( e instanceof Container ) { + res = findButton(depth+1, (Container)e, buttonText); + } + } + return res; + } + + private void oneTest(final GLCapabilitiesImmutable caps) { + // base dialog + final JDialog dialog = new JDialog((Window) null); + dialog.setMinimumSize(new Dimension(500, 300)); + dialog.setPreferredSize(new Dimension(500, 300)); + + dialog.setModal(false); + + // build accessory + final GLEventListenerCounter glelc1 = new GLEventListenerCounter(); + final GLCanvas canvas1 = new GLCanvas(caps); + canvas1.addGLEventListener(new DumpGLInfo(Platform.getNewline()+Platform.getNewline()+"Pre-ToolTip", false, false, false)); + canvas1.addGLEventListener(new GLClearColor(1f, 0f, 0f, 1f)); + canvas1.addGLEventListener(glelc1); + final JPanel panel1 = new JPanel(new BorderLayout()); + panel1.add(canvas1, BorderLayout.CENTER); + panel1.setPreferredSize(new Dimension(300, 300)); + + final GLEventListenerCounter glelc2 = new GLEventListenerCounter(); + final GLCanvas canvas2 = new GLCanvas(caps); + canvas2.addGLEventListener(new DumpGLInfo(Platform.getNewline()+Platform.getNewline()+"Post-ToolTip", false, false, false)); + canvas2.addGLEventListener(new GLClearColor(0f, 0f, 1f, 1f)); + canvas2.addGLEventListener(glelc2); + final JPanel panel2 = new JPanel(new BorderLayout()); + panel2.add(canvas2, BorderLayout.CENTER); + panel2.setPreferredSize(new Dimension(300, 300)); + + // create file chooser with accessory + final JFileChooser fileChooser = new JFileChooser(); + final String approveButtonText = "Approved"; + fileChooser.setApproveButtonText(approveButtonText); + fileChooser.setApproveButtonToolTipText("Tool-Tip for Approved"); + fileChooser.setAccessory(panel1); + + final Locale l = fileChooser.getLocale(); + final String cancelButtonText = UIManager.getString("FileChooser.cancelButtonText",l); + + // launch robot action .. + new Thread() + { + public void run() + { + try { + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(fileChooser, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(canvas1, true)); + + final Point approveButtonPos; + final AbstractButton approveButton = findButton(0, fileChooser, approveButtonText); + if( null != approveButton ) { + approveButtonPos = approveButton.getLocationOnScreen(); + final Dimension approveButtonSize = approveButton.getSize(); + approveButtonPos.translate(approveButtonSize.width/2, approveButtonSize.height/2); + System.err.println("OK Button: "+approveButton.getClass().getSimpleName()+"; "+approveButton+", "+approveButtonPos); + } else { + System.err.println("OK Button: NULL"); + approveButtonPos = null; + } + final Point cancelButtonPos; + final AbstractButton cancelButton = findButton(0, fileChooser, cancelButtonText); + if( null != approveButton ) { + cancelButtonPos = cancelButton.getLocationOnScreen(); + final Dimension cancelButtonSize = cancelButton.getSize(); + cancelButtonPos.translate(cancelButtonSize.width/2, cancelButtonSize.height/2); + System.err.println("CANCEL Button: "+cancelButton.getClass().getSimpleName()+"; "+cancelButton+", "+cancelButtonPos); + } else { + cancelButtonPos = null; + System.err.println("CANCEL Button: NULL"); + } + final Robot robot = new Robot(); + // hover to 'approve' -> tool tip + if( null != approveButtonPos ) { + AWTRobotUtil.mouseMove(robot, approveButtonPos, MOVE_ITER, MOVE_DELAY); + Thread.sleep(TOOLTIP_WAIT); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + fileChooser.setAccessory(panel2); + fileChooser.validate(); + } } ) ; + } catch (final InterruptedException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(canvas2, true)); + } + if( null != cancelButtonPos ) { + AWTRobotUtil.mouseClick(robot, cancelButtonPos, MOVE_ITER, MOVE_DELAY, ACTION_DELAY); + } else { + // oops .. + fileChooser.cancelSelection(); + } + } catch (final AWTException e1) { + e1.printStackTrace(); + } catch (final InterruptedException e2) { + e2.printStackTrace(); + } + } + }.start(); + + // show file chooser dialog + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + dialog.setVisible(true); + fileChooser.showOpenDialog(dialog); + } } ) ; + } catch (final InterruptedException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + + // dispose of resources + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + canvas1.destroy(); + canvas2.destroy(); + dialog.setVisible(false); + dialog.dispose(); + } } ) ; + } catch (final InterruptedException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + + Assert.assertEquals(1, glelc1.initCount); + Assert.assertEquals(1, glelc2.initCount); + } + + + @Test(timeout=180000) // TO 3 min + public void test01() { + final GLCapabilities caps = new GLCapabilities(GLProfile.getDefault()); + for (int i = 0; i < NB_TEST; i++) { + System.out.println("Iteration " + i + " / " + NB_TEST); + oneTest(caps); + } + } + + public static void main(final String[] pArgs) + { + org.junit.runner.JUnitCore.main(TestBug1146GLContextDialogToolTipAWT.class.getName()); + } +}
\ No newline at end of file diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java index 1a9260219..21b653c69 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java @@ -31,13 +31,15 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.test.junit.util.NEWTGLContext; import com.jogamp.opengl.test.junit.util.UITestCase; +import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.FloatBuffer; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2ES3; -import com.jogamp.opengl.GL2GL3; import com.jogamp.opengl.GLBufferStorage; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLProfile; @@ -50,6 +52,9 @@ import org.junit.runners.MethodSorters; /** * Verifies content of buffer storage's content * as well as general buffer- and buffer-storage tracking. + * <p> + * Implementation uses ByteBuffer and Buffers or NIO API. + * </p> * * @author Luz, et.al. */ @@ -63,9 +68,7 @@ public class TestMapBufferRead01NEWT extends UITestCase { System.err.println("Test requires GL2/GL3 profile."); return; } - final ByteBuffer verticiesBB = ByteBuffer.allocate(4*9); - verticiesBB.order(ByteOrder.nativeOrder()); - testWriteRead01(verticiesBB, false /* useRange */); + testWriteRead01(createVerticesBB(false), false /* useRange */); } @Test public void testWriteRead01bMap() throws InterruptedException { @@ -73,8 +76,7 @@ public class TestMapBufferRead01NEWT extends UITestCase { System.err.println("Test requires GL2/GL3 profile."); return; } - final ByteBuffer verticiesBB = Buffers.newDirectByteBuffer(4*9); - testWriteRead01(verticiesBB, false /* useRange */); + testWriteRead01(createVerticesBB(true), false /* useRange */); } @Test @@ -83,9 +85,7 @@ public class TestMapBufferRead01NEWT extends UITestCase { System.err.println("Test requires GL3 or GLES3 profile."); return; } - final ByteBuffer verticiesBB = ByteBuffer.allocate(4*9); - verticiesBB.order(ByteOrder.nativeOrder()); - testWriteRead01(verticiesBB, true/* useRange */); + testWriteRead01(createVerticesBB(false), true/* useRange */); } @Test public void testWriteRead02bMapRange() throws InterruptedException { @@ -93,11 +93,43 @@ public class TestMapBufferRead01NEWT extends UITestCase { System.err.println("Test requires GL3 or GLES3 profile."); return; } - final ByteBuffer verticiesBB = Buffers.newDirectByteBuffer(4*9); - testWriteRead01(verticiesBB, true /* useRange */); + testWriteRead01(createVerticesBB(true), true /* useRange */); + } + + static final float[] vertexData = new float[] { -0.3f, -0.2f, -0.1f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f }; + + static ByteBuffer createVerticesBB(final boolean useBuffersAPI) { + final ByteBuffer res; + if( useBuffersAPI ) { + res = Buffers.newDirectByteBuffer(Buffers.SIZEOF_FLOAT*vertexData.length); + final FloatBuffer resF = res.asFloatBuffer(); + resF.put(vertexData, 0, vertexData.length).rewind(); + } else { + res = ByteBuffer.allocate(Buffers.SIZEOF_FLOAT*vertexData.length); + res.order(ByteOrder.nativeOrder()); + for(int i=0; i<vertexData.length; i++) { + res.putFloat(vertexData[i]); + } + res.rewind(); + } + if(DEBUG) { + System.err.println("java "+res); + for(int i=0; i < res.capacity(); i+=4) { + System.err.println("java ["+i+"]: "+res.getFloat(i)); + } + } + return res; } private void testWriteRead01(final ByteBuffer verticiesBB, final boolean useRange) throws InterruptedException { + // Validate incoming ByteBuffer first + assertEquals(0, verticiesBB.position()); + assertEquals(Buffers.SIZEOF_FLOAT*vertexData.length, verticiesBB.limit()); + assertEquals(Buffers.SIZEOF_FLOAT*vertexData.length, verticiesBB.capacity()); + assertEquals(Buffers.SIZEOF_FLOAT*vertexData.length, verticiesBB.remaining()); + assertEquals(-0.3f, verticiesBB.getFloat(Buffers.SIZEOF_FLOAT*0), 0.05f); + assertEquals( 0.6f, verticiesBB.getFloat(Buffers.SIZEOF_FLOAT*8), 0.05f); + final GLProfile glp = GLProfile.getMaxProgrammable(true); final GLCapabilities caps = new GLCapabilities(glp); caps.setOnscreen(false); @@ -108,24 +140,6 @@ public class TestMapBufferRead01NEWT extends UITestCase { final int[] vertexBuffer = new int[1]; - verticiesBB.putFloat(-0.3f); - verticiesBB.putFloat(-0.2f); - verticiesBB.putFloat(-0.1f); - - verticiesBB.putFloat(0.1f); - verticiesBB.putFloat(0.2f); - verticiesBB.putFloat(0.3f); - - verticiesBB.putFloat(0.4f); - verticiesBB.putFloat(0.5f); - verticiesBB.putFloat(0.6f); - verticiesBB.rewind(); - if(DEBUG) { - for(int i=0; i < verticiesBB.capacity(); i+=4) { - System.err.println("java "+i+": "+verticiesBB.getFloat(i)); - } - } - gl.glGenBuffers(1, vertexBuffer, 0); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBuffer[0]); @@ -149,7 +163,7 @@ public class TestMapBufferRead01NEWT extends UITestCase { floatOffset = 0; byteOffset = 0; mapByteLength = verticiesBB.capacity(); - bb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2GL3.GL_READ_ONLY); + bb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2ES3.GL_READ_ONLY); } System.err.println("gpu-02 mapped GL_ARRAY_BUFFER, floatOffset "+floatOffset+", byteOffset "+byteOffset+", mapByteLength "+mapByteLength+" -> "+bb); System.err.println("gpu-03 GL_ARRAY_BUFFER -> bufferName "+bufferName+" -> "+bufferStorage); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead02NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead02NEWT.java new file mode 100644 index 000000000..49b158bd1 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead02NEWT.java @@ -0,0 +1,191 @@ +/** + * Copyright 2011 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.acore; + +import com.jogamp.common.nio.Buffers; +import com.jogamp.opengl.test.junit.util.NEWTGLContext; +import com.jogamp.opengl.test.junit.util.UITestCase; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2ES3; +import com.jogamp.opengl.GLBufferStorage; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.FixMethodOrder; +import org.junit.runners.MethodSorters; + +/** + * Verifies content of buffer storage's content + * as well as general buffer- and buffer-storage tracking. + * <p> + * Implementation uses FloatBuffer and Buffers or NIO API. + * </p> + * + * @author Luz, et.al. + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestMapBufferRead02NEWT extends UITestCase { + static final boolean DEBUG = false; + + @Test + public void testWriteRead01aMap() throws InterruptedException { + if(!GLProfile.isAvailable(GLProfile.GL2GL3)) { + System.err.println("Test requires GL2/GL3 profile."); + return; + } + testWriteRead01(createVerticesFB(false), false /* useRange */); + } + @Test + public void testWriteRead01bMap() throws InterruptedException { + if(!GLProfile.isAvailable(GLProfile.GL2GL3)) { + System.err.println("Test requires GL2/GL3 profile."); + return; + } + testWriteRead01(createVerticesFB(true), false /* useRange */); + } + + @Test + public void testWriteRead02aMapRange() throws InterruptedException { + if(!GLProfile.isAvailable(GLProfile.GL3) && !!GLProfile.isAvailable(GLProfile.GLES3)) { + System.err.println("Test requires GL3 or GLES3 profile."); + return; + } + testWriteRead01(createVerticesFB(false), true/* useRange */); + } + @Test + public void testWriteRead02bMapRange() throws InterruptedException { + if(!GLProfile.isAvailable(GLProfile.GL3) && !!GLProfile.isAvailable(GLProfile.GLES3)) { + System.err.println("Test requires GL3 or GLES3 profile."); + return; + } + testWriteRead01(createVerticesFB(true), true /* useRange */); + } + + static final float[] vertexData = new float[] { -0.3f, -0.2f, -0.1f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f }; + + static FloatBuffer createVerticesFB(final boolean useBuffersAPI) { + final FloatBuffer res; + if( useBuffersAPI ) { + res = Buffers.newDirectFloatBuffer(vertexData); + } else { + res = FloatBuffer.allocate(vertexData.length); + for(int i=0; i<vertexData.length; i++) { + res.put(vertexData[i]); + } + res.rewind(); + } + if(DEBUG) { + System.err.println("java "+res); + for(int i=0; i < res.remaining(); i+=4) { + System.err.println("java ["+i+"]: "+res.get(i)); + } + } + return res; + } + + private void testWriteRead01(final FloatBuffer verticiesFB, final boolean useRange) throws InterruptedException { + // Validate incoming ByteBuffer first + assertEquals(0, verticiesFB.position()); + assertEquals(vertexData.length, verticiesFB.limit()); + assertEquals(vertexData.length, verticiesFB.capacity()); + assertEquals(vertexData.length, verticiesFB.remaining()); + assertEquals(-0.3f, verticiesFB.get(0), 0.05f); + assertEquals( 0.6f, verticiesFB.get(8), 0.05f); + + final GLProfile glp = GLProfile.getMaxProgrammable(true); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setOnscreen(false); + final NEWTGLContext.WindowContext winctx = NEWTGLContext.createWindow( + caps, 800, 600, true); + try { + final GL gl = winctx.context.getGL(); + + final int[] vertexBuffer = new int[1]; + + gl.glGenBuffers(1, vertexBuffer, 0); + + gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBuffer[0]); + + gl.glBufferData(GL.GL_ARRAY_BUFFER, Buffers.SIZEOF_FLOAT*verticiesFB.remaining(), verticiesFB, GL2ES3.GL_STATIC_READ); + // gl.glBufferData(GL.GL_ARRAY_BUFFER, Buffers.SIZEOF_FLOAT*verticiesBB.remaining(), verticiesBB, GL.GL_STATIC_DRAW); + + final int bufferName = gl.getBoundBuffer(GL.GL_ARRAY_BUFFER); + final GLBufferStorage bufferStorage = gl.getBufferStorage(bufferName); + System.err.println("gpu-01 GL_ARRAY_BUFFER -> bufferName "+bufferName+" -> "+bufferStorage); + Assert.assertEquals("Buffer storage's bytes-buffer not null before map", null, bufferStorage.getMappedBuffer()); + + final int floatOffset, byteOffset, mapByteLength; + final ByteBuffer bb; + if( useRange ) { + floatOffset = 3; + byteOffset = Buffers.SIZEOF_FLOAT*floatOffset; + mapByteLength = Buffers.SIZEOF_FLOAT*verticiesFB.remaining()-byteOffset; + bb = gl.glMapBufferRange(GL.GL_ARRAY_BUFFER, byteOffset, mapByteLength, GL.GL_MAP_READ_BIT); + } else { + floatOffset = 0; + byteOffset = 0; + mapByteLength = Buffers.SIZEOF_FLOAT*verticiesFB.remaining(); + bb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2ES3.GL_READ_ONLY); + } + System.err.println("gpu-02 mapped GL_ARRAY_BUFFER, floatOffset "+floatOffset+", byteOffset "+byteOffset+", mapByteLength "+mapByteLength+" -> "+bb); + System.err.println("gpu-03 GL_ARRAY_BUFFER -> bufferName "+bufferName+" -> "+bufferStorage); + Assert.assertNotNull(bb); + Assert.assertEquals("BufferStorage size less byteOffset not equals buffer storage size", bufferStorage.getSize()-byteOffset, bb.capacity()); + Assert.assertEquals("BufferStorage's bytes-buffer not equal with mapped bytes-buffer", bufferStorage.getMappedBuffer(), bb); + Assert.assertEquals("Buffer storage size not equals mapByteLength", mapByteLength, bb.remaining()); + + if(DEBUG) { + System.err.println("floatOffset "+floatOffset+", byteOffset "+byteOffset); + for(int i=0; i < bb.remaining(); i+=4) { + System.err.println("gpu "+i+": "+bb.getFloat(i)); + } + } + for(int i=0; i < bb.remaining(); i+=4) { + Assert.assertEquals(verticiesFB.get( (byteOffset+i) / Buffers.SIZEOF_FLOAT ), bb.getFloat(i), 0.0001f); + } + gl.glUnmapBuffer(GL.GL_ARRAY_BUFFER); + Assert.assertEquals("Buffer storage's bytes-buffer not null after unmap", null, bufferStorage.getMappedBuffer()); + } finally { + NEWTGLContext.destroyWindow(winctx); + } + } + public static void main(final String args[]) throws IOException { + final String tstname = TestMapBufferRead02NEWT.class.getName(); + org.junit.runner.JUnitCore.main(tstname); + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedExternalContextAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedExternalContextAWT.java new file mode 100644 index 000000000..81489df17 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedExternalContextAWT.java @@ -0,0 +1,261 @@ +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.EventQueue; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.swing.Timer; + +import org.junit.Test; + +import com.jogamp.common.os.Platform; +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.opengl.*; +import com.jogamp.opengl.test.junit.util.DumpGLInfo; + +/** + * Bug 1160. + * Test for context sharing with an external context. Creates an external GL context, then + * sets up an offscreen drawable which shares with it. The test contains two cases: one + * which creates and repaints the offscreen drawable on the EDT, and one which does so on + * a dedicated thread. On Windows+NVidia, the former fails. + */ +public class TestSharedExternalContextAWT { + + static final int LATCH_COUNT = 5; + + private void doTest(final boolean aUseEDT) throws Exception { + final CountDownLatch testLatch = new CountDownLatch(1); + final CountDownLatch masterLatch = new CountDownLatch(1); + final CountDownLatch slaveLatch = new CountDownLatch(LATCH_COUNT); + final MyGLEventListener listener = new MyGLEventListener(aUseEDT, slaveLatch); + + /** + * For the purpose of this test, this offscreen drawable will be used to create + * an external GL context. In the actual application, the external context + * represents a GL context which lives outside the JVM. + */ + final Runnable runnable = new Runnable() { + public void run() { + System.err.println("Master Thread Start: "+Thread.currentThread().getName()); + final GLProfile glProfile = GLProfile.getDefault(); + final GLCapabilities caps = new GLCapabilities(glProfile); + final GLAutoDrawable buffer = GLDrawableFactory.getDesktopFactory().createOffscreenAutoDrawable( + GLProfile.getDefaultDevice(), caps, null, 512, 512 + ); + // The listener will set up the context sharing in its init() method. + buffer.addGLEventListener(new DumpGLInfo(Platform.getNewline()+Platform.getNewline()+"Master GLContext", false, false, false)); + buffer.addGLEventListener(listener); + buffer.display(); + masterLatch.countDown(); + + // wait until test has finished + try { + testLatch.await(); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + System.err.println("Master Thread End: "+Thread.currentThread().getName()); + } + }; + + // Kick off thread creating the actual external context + // which is suppose to lie outside of the JVM. + // The thread is kept alive, since this detail + // may be required for the OpenGL driver implementation. + final Thread thread = new Thread(runnable); + thread.setDaemon(true); + thread.start(); + masterLatch.await(3, TimeUnit.SECONDS); + + // Wait for slave to finish. + slaveLatch.await(3, TimeUnit.SECONDS); + + // signal master test has finished + testLatch.countDown(); + + // If exceptions occurred, fail. + final Exception e = listener.fException; + if (e != null) { + throw e; + } + } + + @Test + public void test01OnEDT() throws Exception { + doTest(true); + } + + @Test + public void test02OnExecutorThread() throws Exception { + doTest(false); + } + + /** + * Listener that creates an external drawable and an offscreen drawable, with context + * sharing between the two. + */ + private static class MyGLEventListener implements GLEventListener { + GLOffscreenAutoDrawable fOffscreenDrawable; + final boolean fUseEDT; + final CountDownLatch fLatch; + final RecursiveLock masterLock = LockFactory.createRecursiveLock(); + + private Exception fException = null; + + public MyGLEventListener(final boolean aUseEDT, final CountDownLatch aLatch) { + fUseEDT = aUseEDT; + fLatch = aLatch; + } + + @Override + public void init(final GLAutoDrawable drawable) { + // FIXME: We actually need to hook into GLContext make-current lock + masterLock.lock(); + try { + final GL2 gl = drawable.getGL().getGL2(); + gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + gl.glClear(GL.GL_COLOR_BUFFER_BIT); + + System.err.println(); System.err.println(); + System.err.println("Master (orig) Ct: "+drawable.getContext()); + // Create the external context on the caller thread. + final GLContext master = GLDrawableFactory.getDesktopFactory().createExternalGLContext(); + System.err.println(); System.err.println(); + System.err.println("External Context: "+master); + + // This runnable creates an offscreen drawable which shares with the external context. + final Runnable initializer = new Runnable() { + public void run() { + // FIXME: We actually need to hook into GLContext make-current lock + // masterLock.lock(); + try { + fOffscreenDrawable = GLDrawableFactory.getDesktopFactory().createOffscreenAutoDrawable( + GLProfile.getDefaultDevice(), + new GLCapabilities(GLProfile.getDefault()), + null, // new DefaultGLCapabilitiesChooser(), + 512, 512 + ); + fOffscreenDrawable.setSharedContext(master); + fOffscreenDrawable.addGLEventListener(new DumpGLInfo(Platform.getNewline()+Platform.getNewline()+"Slave GLContext", false, false, false)); + + try { + System.err.println(); System.err.println(); + System.err.println("Current: "+GLContext.getCurrent()); + fOffscreenDrawable.display(); + } catch (final GLException e) { + fException = e; + throw e; + } + } finally { + // masterLock.unlock(); + } + } + }; + + /** + * Depending on the test case, invoke the initialization on the EDT or on an + * executor thread. The test also displays the offscreen drawable a few times + * before finishing. + */ + if (fUseEDT) { + // Initialize using invokeLater(). + try { + // We cannot use EventQueue.invokeAndWait(..) since it will + // block this will block the current thread, holding the context! + // The whole issue w/ an external shared context is make-current + // synchronization. JOGL attempts to lock the surface/drawable + // of the master context to avoid concurrent usage. + // The semantic constraints of a shared context are not well defined, + // i.e. some driver may allow creating a shared context w/ a master context + // to be in use - others don't. + // Hence it is up to the user to sync the external master context in this case, + // see 'masterLock' of in this code! + // EventQueue.invokeAndWait(initializer); + EventQueue.invokeLater(initializer); + } catch (final Exception e) { + fException = e; + } + + // Display using a Swing timer, i.e. also on the EDT. + final Timer t = new Timer(200, new ActionListener() { + int i = 0; + + @Override + public void actionPerformed(final ActionEvent e) { + if (++i > LATCH_COUNT) { + return; + } + + System.err.println("Update on EDT"); + fOffscreenDrawable.display(); + fLatch.countDown(); + } + }); + t.start(); + } else { + // Initialize and display using a single-threaded executor. + final ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor(); + exe.submit(initializer); + exe.scheduleAtFixedRate(new Runnable() { + int i = 0; + + @Override + public void run() { + if (++i > LATCH_COUNT) { + return; + } + + System.err.println("Update on Executor thread"); + fOffscreenDrawable.display(); + fLatch.countDown(); + } + }, 0, 200, TimeUnit.MILLISECONDS); + } + } finally { + masterLock.unlock(); + } + } + + @Override + public void dispose(final GLAutoDrawable drawable) { + // FIXME: We actually need to hook into GLContext make-current lock + masterLock.lock(); + try { + } finally { + masterLock.unlock(); + } + } + + @Override + public void display(final GLAutoDrawable drawable) { + // FIXME: We actually need to hook into GLContext make-current lock + masterLock.lock(); + try { + } finally { + masterLock.unlock(); + } + } + + @Override + public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { + // FIXME: We actually need to hook into GLContext make-current lock + masterLock.lock(); + try { + } finally { + masterLock.unlock(); + } + } + } + + public static void main(final String[] pArgs) + { + org.junit.runner.JUnitCore.main(TestSharedExternalContextAWT.class.getName()); + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestVersionSemanticsNOUI.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestVersionSemanticsNOUI.java index 7b8fa077a..bbbd92e5e 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestVersionSemanticsNOUI.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestVersionSemanticsNOUI.java @@ -56,12 +56,13 @@ public class TestVersionSemanticsNOUI extends SingletonJunitCase { static final VersionNumberString curVersionNumber = new VersionNumberString(curVersion.getImplementationVersion()); static final Set<String> excludesDefault; - static final Set<String> excludesStereoPackage; + static final Set<String> excludesStereoPackageAndAppletUtils; static { excludesDefault = new HashSet<String>(); excludesDefault.add("^\\Qjogamp/\\E.*$"); - excludesStereoPackage = new HashSet<String>(excludesDefault); - excludesStereoPackage.add("^\\Qcom/jogamp/opengl/util/stereo/\\E.*$"); + excludesStereoPackageAndAppletUtils = new HashSet<String>(excludesDefault); + excludesStereoPackageAndAppletUtils.add("^\\Qcom/jogamp/opengl/util/stereo/\\E.*$"); + excludesStereoPackageAndAppletUtils.add("^\\Qcom/jogamp/newt/util/applet/\\E.*$"); } @@ -138,7 +139,7 @@ public class TestVersionSemanticsNOUI extends SingletonJunitCase { VersionSemanticsUtil.testVersion(diffCriteria, expectedCompatibilityType, previousJar, preVersionNumber, curVersion.getClass(), currentCL, curVersionNumber, - excludesStereoPackage); + excludesStereoPackageAndAppletUtils); } public static void main(final String args[]) throws IOException { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java index 9b414d7c5..f70df89dc 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java @@ -428,7 +428,8 @@ public class GearsES2 implements StereoGLEventListener, TileRendererBase.TileRen final Quaternion rollPitchYaw = new Quaternion(); // private final float eyeYaw = FloatUtil.PI; // 180 degrees in radians // rollPitchYaw.rotateByAngleY(eyeYaw); - final float[] shiftedEyePos = rollPitchYaw.rotateVector(vec3Tmp1, 0, viewerPose.position, 0); + // final float[] shiftedEyePos = rollPitchYaw.rotateVector(vec3Tmp1, 0, viewerPose.position, 0); + final float[] shiftedEyePos = VectorUtil.copyVec3(vec3Tmp1, 0, viewerPose.position, 0); VectorUtil.scaleVec3(shiftedEyePos, shiftedEyePos, vec3ScalePos); // amplify viewerPose position VectorUtil.addVec3(shiftedEyePos, shiftedEyePos, eyeParam.positionOffset); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/stereo/StereoDemo01.java b/src/test/com/jogamp/opengl/test/junit/jogl/stereo/StereoDemo01.java index c2e808770..0d1f1700d 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/stereo/StereoDemo01.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/stereo/StereoDemo01.java @@ -34,8 +34,10 @@ import java.util.Arrays; import com.jogamp.nativewindow.util.DimensionImmutable; import com.jogamp.nativewindow.util.PointImmutable; import com.jogamp.opengl.GL; +import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.GLRunnable; import jogamp.opengl.util.stereo.GenericStereoDevice; @@ -244,11 +246,6 @@ public class StereoDemo01 { } System.err.println("StereoDevice "+stereoDevice); - // Start the sensor which provides the Rift’s pose and motion. - if( !stereoDevice.startSensors(stereoDevice.getSupportedSensorBits(), 0) ) { - System.err.println("Could not start sensors on device "+deviceIndex); - } - // // // @@ -260,6 +257,11 @@ public class StereoDemo01 { final MonitorDevice monitor = StereoDeviceUtil.getMonitorDevice(stereoDevice, true); final Screen screen = monitor.getScreen(); + // Start the sensor which provides the Rift’s pose and motion. + if( !stereoDevice.startSensors(stereoDevice.getSupportedSensorBits(), 0) ) { + System.err.println("Could not start sensors on device "+deviceIndex); + } + final GLCapabilities caps = new GLCapabilities(GLProfile.getMaxProgrammable(true /* favorHardwareRasterizer */)); final GLWindow window = GLWindow.create(screen, caps); @@ -334,6 +336,24 @@ public class StereoDemo01 { return; } switch(e.getKeySymbol()) { + case KeyEvent.VK_O: { + window.invoke(false, new GLRunnable() { + @Override + public boolean run(final GLAutoDrawable drawable) { + stereoDevice.resetLocationSensorOrigin(); + return true; + } }); + break; + } + case KeyEvent.VK_P: { + window.invoke(false, new GLRunnable() { + @Override + public boolean run(final GLAutoDrawable drawable) { + System.err.println(stereoDeviceRenderer.getLastViewerPose()); + return true; + } }); + break; + } case KeyEvent.VK_R: { if( stereoDevice.getSensorsStarted() ) { stereoDevice.stopSensors(); diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java index d9e9fc0cb..477b761bd 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java +++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java @@ -36,6 +36,8 @@ import java.lang.reflect.InvocationTargetException; import java.util.concurrent.atomic.AtomicInteger; import java.awt.AWTException; import java.awt.EventQueue; +import java.awt.MouseInfo; +import java.awt.Point; import java.awt.Robot; import com.jogamp.nativewindow.NativeWindow; @@ -579,6 +581,25 @@ public class AWTRobotUtil { Assert.assertEquals("Wrong key count", typeCount, counter.getCount()-c0); } + public static void mouseMove(final Robot robot, final Point destination, final int iter, final int delay) { + final Point origin = MouseInfo.getPointerInfo().getLocation(); + for (int i = 1; i <= iter; i++) { + final float alpha = i / (float) iter; + robot.mouseMove((int) (origin.x * (1 - alpha) + destination.x * alpha), + (int) (origin.y * (1 - alpha) + destination.y * alpha)); + robot.delay(delay); + } + } + public static void mouseClick(final Robot robot, final Point pos, final int moveIter, final int moveDelay, final int actionDelay) { + robot.delay(actionDelay); + mouseMove(robot, pos, moveIter, moveDelay); + + robot.delay(actionDelay); + robot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK); + robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK); + robot.delay(actionDelay); + } + static int mouseClick(final int i, final Robot robot, final int mouseButton, final Object obj, final InputEventCountAdapter counter) throws InterruptedException, AWTException, InvocationTargetException { diff --git a/src/test/com/jogamp/opengl/test/junit/util/DumpGLInfo.java b/src/test/com/jogamp/opengl/test/junit/util/DumpGLInfo.java index a2887112f..76f73989a 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/DumpGLInfo.java +++ b/src/test/com/jogamp/opengl/test/junit/util/DumpGLInfo.java @@ -34,10 +34,32 @@ import com.jogamp.opengl.JoglVersion; public class DumpGLInfo implements GLEventListener { + final String header; + final boolean withGLAvailability; + final boolean withCapabilities; + final boolean withExtensions; + + public DumpGLInfo(final String header, final boolean withGLAvailability, final boolean withCapabilities, final boolean withExtensions) { + this.header = header; + this.withGLAvailability = withGLAvailability; + this.withCapabilities = withCapabilities; + this.withExtensions = withExtensions; + } + public DumpGLInfo() { + this.header = null; + this.withGLAvailability = true; + this.withCapabilities = true; + this.withExtensions = true; + } public void init(final GLAutoDrawable drawable) { final GL gl = drawable.getGL(); - System.err.println(JoglVersion.getGLInfo(gl, null, true)); + if( null != header ) { + System.err.println(header); + } + System.err.println(JoglVersion.getGLInfo(gl, null, withGLAvailability, withCapabilities, withExtensions)); + System.err.println("Drawable: "+drawable.getDelegatedDrawable().getClass().getSimpleName()); + System.err.println(drawable.getChosenGLCapabilities()); } public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { diff --git a/src/test/com/jogamp/opengl/test/junit/util/GLClearColor.java b/src/test/com/jogamp/opengl/test/junit/util/GLClearColor.java new file mode 100644 index 000000000..7a19ffe6f --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/util/GLClearColor.java @@ -0,0 +1,61 @@ +/** + * Copyright 2010 JogAmp Community. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.util; + + +import com.jogamp.opengl.*; +import com.jogamp.opengl.JoglVersion; + + +public class GLClearColor implements GLEventListener { + private final float red, green, blue, alpha; + + public GLClearColor(final float red, final float green, final float blue, final float alpha) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + } + public void init(final GLAutoDrawable drawable) { + final GL gl = drawable.getGL(); + gl.glClearColor(red, green, blue, alpha); + } + + public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { + } + + public void display(final GLAutoDrawable drawable) { + final GL gl = drawable.getGL(); + gl.glClearColor(red, green, blue, alpha); + gl.glClear(GL.GL_COLOR_BUFFER_BIT); + } + + public void dispose(final GLAutoDrawable drawable) { + } +} |