diff options
author | Sven Gothel <[email protected]> | 2013-10-27 17:51:08 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2013-10-27 17:51:08 +0100 |
commit | 7f7a23dd0ddf106e6f0c69fc2a05ff92ac56200e (patch) | |
tree | 562e5835aecbdd5994d1e85657b3b948f23ff785 /src/jogl | |
parent | ff3832bf24f02fc44a7494be49d210cacce43977 (diff) |
Bug 776 GLContext Sharing: Refine API for relaxed and lazy GLContext sharing ; Fix GLContext memory contract (volatile)
(Unit test remarks see below)
- Add shared GLContext queries
- Refined GLContextShareSet:
- Use IdentityHashMap since GLContext's can only be identical w/ same reference (footprint, performance)
- Add API doc for clarification
- Add methods:
- ArrayList<GLContext> getCreatedShares(final GLContext context)
- ArrayList<GLContext> getDestroyedShares(final GLContext context)
- Use 'final' where possible
- Add GLContext methods:
- boolean isShared()
- List<GLContext> getCreatedShares()
- List<GLContext> getDestroyedShares()
- Add GLSharedContextSetter interface defining setting a shared GLContext
directly (GLContext) or via a GLAutoDrawable:
- setSharedContext(GLContext)
- setSharedAutoDrawable(GLAutoDrawable)
Both cause initialization/creation of GLAutoDrawable's drawable/context to be postponed,
if the shared GLContext is not yet created natively or
the shared GLAutoDrawable's GLContext does not yet exist.
Most of impl. resides in GLDrawableHelper
Implemented in:
- GLAutoDrawableBase, GLOffscreenAutoDrawable
- GLWindow
- AWT GLCanvas
TODO:
- GLJPanel
- SWT GLCanvas
- GLDrawableFactory:
- Add 'GLOffscreenAutoDrawable createOffscreenAutoDrawable(..)' variant w/o passing the
optional shared GLContext _and_ specifying lazy GLContext
creation. This allows to benefit from GLSharedContextSetter contract.
Lazy GLContext creation is performed at 2st display() call at the latest.
All JOGL code and unit tests use this new method now.
- Mark 'createOffscreenAutoDrawable(..)' w/ shared GLContext argument
and immediate GLContext creation deprecated - shall be removed in 2.2.0
- Make reference to GLContext and it's native handle volatile
Since we rely on the query 'GLContext.isCreated()' to properly allow GLAutoDrawable's to query whether
a shared GLContext is natively created (already), the handle must be volatile
since such query and the actual creation may operate on different threads.
+++++
- Add/Refine shared GLContext unit tests demonstrating diff. sharing methods.
All variants of using shared GLContext:
com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBO*
Most convenient way to share via setSharedAutoDrawable(GLAutoDrawable):
com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2[NEWT|AWT]3
AWT use w/ JTabbedPane using setSharedAutoDrawable(GLAutoDrawable):
com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextWithJTabbedPaneAWT
Diffstat (limited to 'src/jogl')
15 files changed, 506 insertions, 164 deletions
diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java index ce58d29c1..6b1bb0e5e 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -64,11 +64,18 @@ import jogamp.opengl.GLDrawableImpl; */ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAutoDrawable { /** + * <p> + * The {@link GLContext} can be assigned later manually via {@link GLAutoDrawable#setContext(GLContext, boolean) setContext(ctx)} + * <i>or</i> it will be created <i>lazily</i> at the 1st {@link GLAutoDrawable#display() display()} method call.<br> + * <i>Lazy</i> {@link GLContext} creation will take a shared {@link GLContext} into account + * which has been set {@link #setSharedContext(GLContext) directly} + * or {@link #setSharedAutoDrawable(GLAutoDrawable) via another GLAutoDrawable}. + * </p> * @param drawable a valid {@link GLDrawable}, may not be {@link GLDrawable#isRealized() realized} yet. * @param context a valid {@link GLContext}, * may not have been made current (created) yet, * may not be associated w/ <code>drawable<code> yet, - * may be <code>null</code> for lazy initialization + * may be <code>null</code> for lazy initialization at 1st {@link #display()}. * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. * @param ownDevice pass <code>true</code> if {@link AbstractGraphicsDevice#close()} shall be issued, * otherwise pass <code>false</code>. Closing the device is required in case diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 1a3e1e0c0..5e3731984 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -242,7 +242,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { private class DisposeGLEventListenerAction implements Runnable { private GLEventListener listener; - private boolean remove; + private final boolean remove; private DisposeGLEventListenerAction(GLEventListener listener, boolean remove) { this.listener = listener; this.remove = remove; @@ -677,7 +677,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public GLContext getContext() { - return null != drawable ? context : null; + return context; } @Override diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java index 3662223f4..46dc73003 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java @@ -159,20 +159,20 @@ public class TextRenderer { static final int kTotalBufferSizeBytesTex = kTotalBufferSizeCoordsTex * 4; static final int kSizeInBytes_OneVertices_VertexData = kCoordsPerVertVerts * 4; static final int kSizeInBytes_OneVertices_TexData = kCoordsPerVertTex * 4; - private Font font; - private boolean antialiased; - private boolean useFractionalMetrics; + private final Font font; + private final boolean antialiased; + private final boolean useFractionalMetrics; // Whether we're attempting to use automatic mipmap generation support private boolean mipmap; private RectanglePacker packer; private boolean haveMaxSize; - private RenderDelegate renderDelegate; + private final RenderDelegate renderDelegate; private TextureRenderer cachedBackingStore; private Graphics2D cachedGraphics; private FontRenderContext cachedFontRenderContext; - private Map<String, Rect> stringLocations = new HashMap<String, Rect>(); - private GlyphProducer mGlyphProducer; + private final Map<String, Rect> stringLocations = new HashMap<String, Rect>(); + private final GlyphProducer mGlyphProducer; private int numRenderCycles; @@ -905,8 +905,8 @@ public class TextRenderer { private void debug(GL gl) { dbgFrame = new Frame("TextRenderer Debug Output"); - GLCanvas dbgCanvas = new GLCanvas(new GLCapabilities(gl.getGLProfile()), null, - GLContext.getCurrent(), null); + GLCanvas dbgCanvas = new GLCanvas(new GLCapabilities(gl.getGLProfile())); + dbgCanvas.setSharedContext(GLContext.getCurrent()); dbgCanvas.addGLEventListener(new DebugListener(gl, dbgFrame)); dbgFrame.add(dbgCanvas); @@ -1085,7 +1085,7 @@ public class TextRenderer { static class TextData { // Back-pointer to String this TextData describes, if it // represents a String rather than a single glyph - private String str; + private final String str; // If this TextData represents a single glyph, this is its // unicode ID @@ -1096,7 +1096,7 @@ public class TextRenderer { // 2D coordinate system) at which the string must be rasterized in // order to fit within the rectangle -- the leftmost point of the // baseline. - private Point origin; + private final Point origin; // This represents the pre-normalized rectangle, which fits // within the rectangle on the backing store. We keep a @@ -1104,7 +1104,7 @@ public class TextRenderer { // prevent bleeding of adjacent letters when using GL_LINEAR // filtering for rendering. The origin of this rectangle is // equivalent to the origin above. - private Rectangle2D origRect; + private final Rectangle2D origRect; private boolean used; // Whether this text was used recently @@ -1375,7 +1375,7 @@ public class TextRenderer { // // A temporary to prevent excessive garbage creation - private char[] singleUnicode = new char[1]; + private final char[] singleUnicode = new char[1]; /** A Glyph represents either a single unicode glyph or a substring of characters to be drawn. The reason for the dual @@ -1497,10 +1497,10 @@ public class TextRenderer { int width = (int) origRect.getWidth(); int height = (int) origRect.getHeight(); - float tx1 = xScale * (float) texturex / (float) renderer.getWidth(); + float tx1 = xScale * texturex / renderer.getWidth(); float ty1 = yScale * (1.0f - ((float) texturey / (float) renderer.getHeight())); - float tx2 = xScale * (float) (texturex + width) / (float) renderer.getWidth(); + float tx2 = xScale * (texturex + width) / renderer.getWidth(); float ty2 = yScale * (1.0f - ((float) (texturey + height) / (float) renderer.getHeight())); @@ -1829,7 +1829,7 @@ public class TextRenderer { GL2 gl = GLContext.getCurrentGL().getGL2(); TextureRenderer renderer = getBackingStore(); - Texture texture = renderer.getTexture(); // triggers texture uploads. Maybe this should be more obvious? + renderer.getTexture(); // triggers texture uploads. Maybe this should be more obvious? mVertCoords.rewind(); mTexCoords.rewind(); @@ -1872,7 +1872,7 @@ public class TextRenderer { private void drawIMMEDIATE() { if (mOutstandingGlyphsVerticesPipeline > 0) { TextureRenderer renderer = getBackingStore(); - Texture texture = renderer.getTexture(); // triggers texture uploads. Maybe this should be more obvious? + renderer.getTexture(); // triggers texture uploads. Maybe this should be more obvious? GL2 gl = GLContext.getCurrentGL().getGL2(); gl.glBegin(GL2.GL_QUADS); diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index e83d60b66..5c6c7073a 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -44,12 +44,14 @@ import java.nio.IntBuffer; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; +import java.util.List; import java.util.Set; import javax.media.nativewindow.AbstractGraphicsDevice; import jogamp.opengl.Debug; import jogamp.opengl.GLContextImpl; +import jogamp.opengl.GLContextShareSet; import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; @@ -205,7 +207,7 @@ public abstract class GLContext { protected final RecursiveLock lock = LockFactory.createRecursiveLock(); /** The underlying native OpenGL context */ - protected long contextHandle; + protected volatile long contextHandle; protected GLContext() { resetStates(true); @@ -242,6 +244,21 @@ public abstract class GLContext { drawableRetargeted = false; } + /** Returns true if this GLContext is shared, otherwise false. */ + public final boolean isShared() { + return GLContextShareSet.isShared(this); + } + + /** Returns a new list of created GLContext shared with this GLContext. */ + public final List<GLContext> getCreatedShares() { + return GLContextShareSet.getCreatedShares(this); + } + + /** Returns a new list of destroyed GLContext shared with this GLContext. */ + public final List<GLContext> getDestroyedShares() { + return GLContextShareSet.getDestroyedShares(this); + } + /** * Returns the instance of {@link GLRendererQuirks}, allowing one to determine workarounds. * @return instance of {@link GLRendererQuirks} if context was made current once, otherwise <code>null</code>. @@ -590,7 +607,7 @@ public abstract class GLContext { sb.append(toHexString(hashCode())); sb.append(", handle "); sb.append(toHexString(contextHandle)); - sb.append(", "); + sb.append(", isShared "+isShared()+", "); sb.append(getGL()); sb.append(",\n\t quirks: "); if(null != glRendererQuirks) { diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 26bafd961..817dff8ad 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -475,7 +475,8 @@ public abstract class GLDrawableFactory { * <p> * In case the passed {@link GLCapabilitiesImmutable} contains default values, i.e. * {@link GLCapabilitiesImmutable#isOnscreen() caps.isOnscreen()} <code> == true</code>, - * it is auto-configured. The latter will set offscreen and also FBO <i>or</i> Pbuffer, whichever is available in that order. + * it is auto-configured. Auto configuration will set {@link GLCapabilitiesImmutable caps} to offscreen + * and FBO <i>or</i> Pbuffer, whichever is available in that order. * </p> * <p> * A FBO based auto drawable, {@link GLOffscreenAutoDrawable.FBO}, is created if both {@link GLCapabilitiesImmutable#isFBO() caps.isFBO()} @@ -501,12 +502,62 @@ public abstract class GLDrawableFactory { * the creation of the Offscreen to fail. * * @see #createOffscreenDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) + * @deprecated Use {@link #createOffscreenAutoDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) */ public abstract GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice device, GLCapabilitiesImmutable caps, GLCapabilitiesChooser chooser, int width, int height, GLContext shareWith) throws GLException; + + /** + * Creates a {@link GLDrawable#isRealized() realized} {@link GLOffscreenAutoDrawable} + * incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. + * <p> + * The {@link GLOffscreenAutoDrawable}'s {@link GLDrawable} is {@link GLDrawable#isRealized() realized} + * <i>without</i> an assigned {@link GLContext}.<br> + * The {@link GLContext} can be assigned later manually via {@link GLAutoDrawable#setContext(GLContext, boolean) setContext(ctx)} + * <i>or</i> it will be created <i>lazily</i> at the 1st {@link GLAutoDrawable#display() display()} method call.<br> + * <i>Lazy</i> {@link GLContext} creation will take a shared {@link GLContext} into account + * which has been set {@link GLOffscreenAutoDrawable#setSharedContext(GLContext) directly} + * or {@link GLOffscreenAutoDrawable#setSharedAutoDrawable(GLAutoDrawable) via another GLAutoDrawable}. + * </p> + * <p> + * In case the passed {@link GLCapabilitiesImmutable} contains default values, i.e. + * {@link GLCapabilitiesImmutable#isOnscreen() caps.isOnscreen()} <code> == true</code>, + * it is auto-configured. Auto configuration will set {@link GLCapabilitiesImmutable caps} to offscreen + * and FBO <i>or</i> Pbuffer, whichever is available in that order. + * </p> + * <p> + * A FBO based auto drawable, {@link GLOffscreenAutoDrawable.FBO}, is created if both {@link GLCapabilitiesImmutable#isFBO() caps.isFBO()} + * and {@link GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) canCreateFBO(device, caps.getGLProfile())} is true. + * </p> + * <p> + * A Pbuffer based auto drawable is created if both {@link GLCapabilitiesImmutable#isPBuffer() caps.isPBuffer()} + * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice, GLProfile) canCreateGLPbuffer(device)} is true. + * </p> + * <p> + * If neither FBO nor Pbuffer is available, + * a simple pixmap/bitmap auto drawable is created, which is unlikely to be hardware accelerated. + * </p> + * + * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be <code>null</code> for the platform's default device. + * @param caps the requested GLCapabilties + * @param chooser the custom chooser, may be null for default + * @param width the requested offscreen width + * @param height the requested offscreen height + * @return the created and initialized offscreen {@link GLOffscreenAutoDrawable} instance + * + * @throws GLException if any window system-specific errors caused + * the creation of the Offscreen to fail. + * + * @see #createOffscreenDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) + */ + public abstract GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice device, + GLCapabilitiesImmutable caps, + GLCapabilitiesChooser chooser, + int width, int height) throws GLException; + /** * Creates an {@link GLDrawable#isRealized() unrealized} offscreen {@link GLDrawable} * incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. @@ -625,7 +676,7 @@ public abstract class GLDrawableFactory { * </p> * * See the note in the overview documentation on - * <a href="../../../overview-summary.html#SHARING">context sharing</a>. + * <a href="../../../spec-summary.html#SHARING">context sharing</a>. * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be <code>null</code> for the platform's default device. * @param capabilities the requested capabilities diff --git a/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java index be90d935f..d34edaf2e 100644 --- a/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java @@ -40,7 +40,7 @@ import com.jogamp.opengl.FBObject; * with it's {@link #setSize(int, int)} functionality. * </p> */ -public interface GLOffscreenAutoDrawable extends GLAutoDrawable { +public interface GLOffscreenAutoDrawable extends GLAutoDrawable, GLSharedContextSetter { /** * Resize this auto drawable. diff --git a/src/jogl/classes/javax/media/opengl/GLSharedContextSetter.java b/src/jogl/classes/javax/media/opengl/GLSharedContextSetter.java new file mode 100644 index 000000000..d5a10931e --- /dev/null +++ b/src/jogl/classes/javax/media/opengl/GLSharedContextSetter.java @@ -0,0 +1,78 @@ +/** + * Copyright 2013 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 javax.media.opengl; + +/** + * Adds capabilities to set a shared {@link GLContext} directly or via an {@link GLAutoDrawable}. + * <p> + * Warning: Don't reference this interface directly, since it may end up in {@link GLAutoDrawable} + * </p> + */ +public interface GLSharedContextSetter extends GLAutoDrawable { + /** + * Specifies an {@link GLContext OpenGL context}, which shall be shared by this {@link GLAutoDrawable}'s {@link GLContext}. + * <p> + * Since the {@link GLDrawable drawable} and {@link GLContext context} is created + * at {@link GLAutoDrawable#initialization GLAutoDrawable initialization} + * this method shall be called beforehand to have any effect. + * </p> + * <p> + * A set <i>sharedContext</i> will block context creation, i.e. {@link GLAutoDrawable#initialization GLAutoDrawable initialization}, + * as long it is not {@link GLContext#isCreated() created natively}. + * </p> + * + * @param sharedContext The OpenGL context to be shared by this {@link GLAutoDrawable}'s {@link GLContext}. + * @throws IllegalStateException if a {@link #setSharedContext(GLContext) shared GLContext} + * or {@link #setSharedAutoDrawable(GLAutoDrawable) shared GLAutoDrawable} is already set, + * the given sharedContext is null or equal to this {@link GLAutoDrawable}'s context. + * @see #setSharedAutoDrawable(GLAutoDrawable) + */ + void setSharedContext(GLContext sharedContext) throws IllegalStateException; + + /** + * Specifies an {@link GLAutoDrawable}, which {@link GLContext OpenGL context} shall be shared by this {@link GLAutoDrawable}'s {@link GLContext}. + * <p> + * Since the {@link GLDrawable drawable} and {@link GLContext context} is created + * at {@link GLAutoDrawable#initialization GLAutoDrawable initialization} + * this method shall be called beforehand to have any effect. + * </p> + * <p> + * A set <i>sharedAutoDrawable</i> will block context creation, i.e. {@link GLAutoDrawable#initialization GLAutoDrawable initialization}, + * as long it's {@link GLContext} is <code>null</code> + * or has not been {@link GLContext#isCreated() created natively}. + * </p> + * + * @param sharedContext The GLAutoDrawable, which OpenGL context shall be shared by this {@link GLAutoDrawable}'s {@link GLContext}. + * @throws IllegalStateException if a {@link #setSharedContext(GLContext) shared GLContext} + * or {@link #setSharedAutoDrawable(GLAutoDrawable) shared GLAutoDrawable} is already set, + * the given sharedAutoDrawable is null or equal to this GLAutoDrawable. + * @see #setSharedContext(GLContext) + */ + void setSharedAutoDrawable(GLAutoDrawable sharedAutoDrawable) throws IllegalStateException; +} diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 8757c7a26..b070ddd7d 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -81,6 +81,7 @@ import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; +import javax.media.opengl.GLSharedContextSetter; import javax.media.opengl.Threading; import com.jogamp.common.GlueGenVersion; @@ -114,7 +115,7 @@ import jogamp.opengl.awt.AWTTilePainter; interfaces when adding a heavyweight doesn't work either because of Z-ordering or LayoutManager problems. * - * <h5><A NAME="java2dgl">Offscreen Layer Remarks</A></h5> + * <h5><a name="offscreenlayer">Offscreen Layer Remarks</a></h5> * * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} * maybe called to use an offscreen drawable (FBO or PBuffer) allowing @@ -124,7 +125,7 @@ import jogamp.opengl.awt.AWTTilePainter; * is being called if {@link GLCapabilitiesImmutable#isOnscreen()} is <code>false</code>. * </p> * - * <h5><A NAME="java2dgl">Java2D OpenGL Remarks</A></h5> + * <h5><a name="java2dgl">Java2D OpenGL Remarks</a></h5> * * To avoid any conflicts with a potential Java2D OpenGL context,<br> * you shall consider setting the following JVM properties:<br> @@ -141,7 +142,7 @@ import jogamp.opengl.awt.AWTTilePainter; * <li><pre>sun.java2d.noddraw=true</pre></li> * </ul> * - * <h5><A NAME="backgrounderase">Disable Background Erase</A></h5> + * <h5><a name="backgrounderase">Disable Background Erase</a></h5> * * GLCanvas tries to disable background erase for the AWT Canvas * before native peer creation (X11) and after it (Windows), <br> @@ -153,7 +154,7 @@ import jogamp.opengl.awt.AWTTilePainter; */ @SuppressWarnings("serial") -public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosingProtocol, OffscreenLayerOption, AWTPrintLifecycle { +public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosingProtocol, OffscreenLayerOption, AWTPrintLifecycle, GLSharedContextSetter { private static final boolean DEBUG = Debug.debug("GLCanvas"); @@ -162,18 +163,20 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing 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 GLContextImpl context; + private volatile GLContextImpl context; private volatile boolean sendReshape = false; // volatile: maybe written by EDT w/o locking // copy of the cstr args, mainly for recreation - private GLCapabilitiesImmutable capsReqUser; - private GLCapabilitiesChooser chooser; - private GLContext shareWith; + private final GLCapabilitiesImmutable capsReqUser; + private final GLCapabilitiesChooser chooser; private int additionalCtxCreationFlags = 0; - private GraphicsDevice device; + private final GraphicsDevice device; private boolean shallUseOffscreenLayer = false; - private AWTWindowClosingProtocol awtWindowClosingProtocol = + protected GLContext sharedContext = null; + protected GLAutoDrawable sharedAutoDrawable = null; + + private final AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { @Override public void run() { @@ -207,6 +210,8 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing * * @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device. * @see GLCanvas#GLCanvas(javax.media.opengl.GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, javax.media.opengl.GLContext, java.awt.GraphicsDevice) + * @deprecated Use {@link #GLCanvas(GLCapabilitiesImmutable)} + * and set shared GLContext via {@link #setSharedContext(GLContext)} or {@link #setSharedAutoDrawable(GLAutoDrawable)}. */ public GLCanvas(GLCapabilitiesImmutable capsReqUser, GLContext shareWith) throws GLException @@ -219,17 +224,39 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing default set of capabilities is used. The GLCapabilitiesChooser specifies the algorithm for selecting one of the available GLCapabilities for the component; a DefaultGLCapabilitesChooser + is used if null is passed for this argument. + The passed GraphicsDevice indicates the screen on + which to create the GLCanvas; the GLDrawableFactory uses the + default screen device of the local GraphicsEnvironment if null + is passed for this argument. + * @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device. + */ + public GLCanvas(GLCapabilitiesImmutable capsReqUser, + GLCapabilitiesChooser chooser, + GraphicsDevice device) + throws GLException + { + this(capsReqUser, chooser, null, device); + } + + /** Creates a new GLCanvas component. The passed GLCapabilities + specifies the OpenGL capabilities for the component; if null, a + default set of capabilities is used. The GLCapabilitiesChooser + specifies the algorithm for selecting one of the available + GLCapabilities for the component; a DefaultGLCapabilitesChooser is used if null is passed for this argument. The passed GLContext specifies an OpenGL context with which to share textures, display lists and other OpenGL state, and may be null if sharing is not desired. See the note in the overview documentation on <a - href="../../../overview-summary.html#SHARING">context + href="../../../spec-summary.html#SHARING">context sharing</a>. The passed GraphicsDevice indicates the screen on which to create the GLCanvas; the GLDrawableFactory uses the default screen device of the local GraphicsEnvironment if null is passed for this argument. * @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device. + * @deprecated Use {@link #GLCanvas(GLCapabilitiesImmutable, GLCapabilitiesChooser, GraphicsDevice)} + * and set shared GLContext via {@link #setSharedContext(GLContext)} or {@link #setSharedAutoDrawable(GLAutoDrawable)}. */ public GLCanvas(GLCapabilitiesImmutable capsReqUser, GLCapabilitiesChooser chooser, @@ -266,11 +293,21 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // instantiation will be issued in addNotify() this.capsReqUser = capsReqUser; this.chooser = chooser; - this.shareWith = shareWith; + this.sharedContext = shareWith; this.device = device; } @Override + public final void setSharedContext(GLContext sharedContext) throws IllegalStateException { + helper.setSharedContext(this.context, sharedContext); + } + + @Override + public final void setSharedAutoDrawable(GLAutoDrawable sharedAutoDrawable) throws IllegalStateException { + helper.setSharedAutoDrawable(this, sharedAutoDrawable); + } + + @Override public final Object getUpstreamWidget() { return this; } @@ -383,7 +420,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing destroyImpl( true ); // recreation! awtConfig = config; - createDrawableAndContext( true ); + createJAWTDrawableAndContext(); validateGLDrawable(); } else { awtConfig = config; @@ -592,7 +629,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // after native peer is valid: Windows disableBackgroundErase(); - createDrawableAndContext( true ); + createJAWTDrawableAndContext(); // init drawable by paint/display makes the init sequence more equal // for all launch flavors (applet/javaws/..) @@ -608,22 +645,35 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } - private void createDrawableAndContext(boolean createJAWTWindow) { + private void createJAWTDrawableAndContext() { if ( !Beans.isDesignTime() ) { - if( createJAWTWindow ) { - jawtWindow = (JAWTWindow) NativeWindowFactory.getNativeWindow(this, awtConfig); - jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); - } + jawtWindow = (JAWTWindow) NativeWindowFactory.getNativeWindow(this, awtConfig); + jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); jawtWindow.lockSurface(); try { drawable = (GLDrawableImpl) GLDrawableFactory.getFactory(capsReqUser.getGLProfile()).createGLDrawable(jawtWindow); - context = (GLContextImpl) drawable.createContext(shareWith); - context.setContextCreationFlags(additionalCtxCreationFlags); + createContextImpl(drawable); } finally { jawtWindow.unlockSurface(); } } } + private boolean createContextImpl(final GLDrawable drawable) { + final GLContext[] shareWith = { null }; + if( !helper.isSharedGLContextPending(shareWith) ) { + context = (GLContextImpl) drawable.createContext(shareWith[0]); + context.setContextCreationFlags(additionalCtxCreationFlags); + if(DEBUG) { + System.err.println(getThreadName()+": Context created: has shared "+(null != shareWith[0])); + } + return true; + } else { + if(DEBUG) { + System.err.println(getThreadName()+": Context !created: pending share"); + } + return false; + } + } private boolean validateGLDrawable() { if( Beans.isDesignTime() || !isDisplayable() ) { @@ -631,17 +681,22 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } final GLDrawable _drawable = drawable; if ( null != _drawable ) { - if( _drawable.isRealized() ) { - return true; - } - if( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) { - return false; // early out! + boolean res = _drawable.isRealized(); + if( !res ) { + // re-try drawable creation + if( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) { + return false; // early out! + } + setRealized(true); + res = _drawable.isRealized(); + if(DEBUG) { + System.err.println(getThreadName()+": Realized Drawable: isRealized "+res+", "+_drawable.toString()); + // Thread.dumpStack(); + } } - setRealized(true); - final boolean res = _drawable.isRealized(); - if(DEBUG) { - System.err.println(getThreadName()+": Realized Drawable: isRealized "+res+", "+_drawable.toString()); - // Thread.dumpStack(); + if( res && null == context ) { + // re-try context creation + res = createContextImpl(_drawable); // pending creation. } return res; } @@ -791,8 +846,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, - printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, - null); + printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLCanvas.this, printGLAD); printDrawable = printGLAD.getDelegatedDrawable(); } @@ -1251,7 +1305,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private class DisposeGLEventListenerAction implements Runnable { GLEventListener listener; - private boolean remove; + private final boolean remove; private DisposeGLEventListenerAction(GLEventListener listener, boolean remove) { this.listener = listener; this.remove = remove; diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 84db62515..93e8b2c0b 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -108,22 +108,23 @@ import com.jogamp.opengl.util.texture.TextureState; support. Provided for compatibility with Swing user interfaces when adding a heavyweight doesn't work either because of Z-ordering or LayoutManager problems. - <P> + <p> The GLJPanel can be made transparent by creating it with a GLCapabilities object with alpha bits specified and calling {@link #setOpaque}(false). Pixels with resulting OpenGL alpha values less - than 1.0 will be overlaid on any underlying Swing rendering. </P> - <P> + than 1.0 will be overlaid on any underlying Swing rendering. + </p> + <p> This component attempts to use hardware-accelerated rendering via FBO or pbuffers and falls back on to software rendering if none of the former are available using {@link GLDrawableFactory#createOffscreenDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) GLDrawableFactory.createOffscreenDrawable(..)}.<br/> - </P> - <P> + </p> + <p> In case FBO is used and GLSL is available, a fragment shader is utilized to flip the FBO texture vertically. This hardware-accelerated step can be disabled via system property <code>jogl.gljpanel.noglsl</code>. See <a href="#fboGLSLVerticalFlip">details here</a>. - </P> - <P> + </p> + <p> The OpenGL path is concluded by copying the rendered pixels an {@link BufferedImage} via {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)} for later Java2D composition. </p> @@ -210,7 +211,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing return singleAWTGLPixelBufferProvider; } - private GLDrawableHelper helper = new GLDrawableHelper(); + private final GLDrawableHelper helper = new GLDrawableHelper(); private volatile boolean isInitialized; // @@ -219,10 +220,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private AWTGLPixelBufferProvider customPixelBufferProvider = null; /** Single buffered offscreen caps */ private GLCapabilitiesImmutable offscreenCaps; - private GLProfile glProfile; - private GLDrawableFactoryImpl factory; - private GLCapabilitiesChooser chooser; - private GLContext shareWith; + private final GLProfile glProfile; + private final GLDrawableFactoryImpl factory; + private final GLCapabilitiesChooser chooser; + private final GLContext shareWith; private int additionalCtxCreationFlags = 0; // Lazy reshape notification: reshapeWidth -> panelWidth -> backend.width @@ -248,13 +249,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private volatile Backend backend; // Used by all backends either directly or indirectly to hook up callbacks - private Updater updater = new Updater(); + private final Updater updater = new Updater(); private boolean oglPipelineUsable() { return null == customPixelBufferProvider && useJava2DGLPipeline && java2DGLPipelineOK; } - private AWTWindowClosingProtocol awtWindowClosingProtocol = + private final AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { @Override public void run() { @@ -289,7 +290,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing GLContext specifies an OpenGL context with which to share textures, display lists and other OpenGL state, and may be null if sharing is not desired. See the note in the overview documentation on - <a href="../../../overview-summary.html#SHARING">context sharing</a>. + <a href="../../../spec-summary.html#SHARING">context sharing</a>. <P> Note: Sharing cannot be enabled using J2D OpenGL FBO sharing, since J2D GL Context must be shared and we can only share one context. @@ -572,8 +573,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, - printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, - null); + printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); printDrawable = printGLAD.getDelegatedDrawable(); } @@ -1158,7 +1158,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private class DisposeGLEventListenerAction implements Runnable { GLEventListener listener; - private boolean remove; + private final boolean remove; private DisposeGLEventListenerAction(GLEventListener listener, boolean remove) { this.listener = listener; this.remove = remove; @@ -1268,12 +1268,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing protected IntBuffer readBackIntsForCPUVFlip; // Implementation using software rendering - private GLDrawableImpl offscreenDrawable; + private volatile GLDrawableImpl offscreenDrawable; private boolean offscreenIsFBO; private FBObject fboFlipped; private GLSLTextureRaster glslTextureRaster; - private GLContextImpl offscreenContext; + private volatile GLContextImpl offscreenContext; private boolean flipVertical; // For saving/restoring of OpenGL state during ReadPixels @@ -1694,11 +1694,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private GLContext joglContext; // State captured from Java2D OpenGL context necessary in order to // properly render into Java2D back buffer - private int[] drawBuffer = new int[1]; - private int[] readBuffer = new int[1]; + private final int[] drawBuffer = new int[1]; + private final int[] readBuffer = new int[1]; // This is required when the FBO option of the Java2D / OpenGL // pipeline is active - private int[] frameBuffer = new int[1]; + private final int[] frameBuffer = new int[1]; // Current (as of this writing) NVidia drivers have a couple of bugs // relating to the sharing of framebuffer and renderbuffer objects // between contexts. It appears we have to (a) reattach the color diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index bb2983399..42d0a2ec4 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -45,8 +45,10 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; +import javax.media.opengl.GLOffscreenAutoDrawable; import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; +import javax.media.opengl.GLSharedContextSetter; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.opengl.GLAutoDrawableDelegate; @@ -59,17 +61,18 @@ import com.jogamp.opengl.GLStateKeeper; * * @see GLAutoDrawable * @see GLAutoDrawableDelegate + * @see GLOffscreenAutoDrawable + * @see GLOffscreenAutoDrawableImpl * @see GLPBufferImpl - * @see GLWindow + * @see com.jogamp.newt.opengl.GLWindow */ -public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeeper, FPSCounter { +public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeeper, FPSCounter, GLSharedContextSetter { public static final boolean DEBUG = GLDrawableImpl.DEBUG; - protected final GLDrawableHelper helper = new GLDrawableHelper(); protected final FPSCounterImpl fpsCounter = new FPSCounterImpl(); protected volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access - protected GLContextImpl context; + protected volatile GLContextImpl context; protected boolean preserveGLELSAtDestroy; protected GLEventListenerState glels; protected GLStateKeeper.Listener glStateKeeperListener; @@ -79,12 +82,19 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe protected volatile boolean sendDestroy = false; // volatile: maybe written by WindowManager thread w/o locking /** + * <p> + * The {@link GLContext} can be assigned later manually via {@link GLAutoDrawable#setContext(GLContext, boolean) setContext(ctx)} + * <i>or</i> it will be created <i>lazily</i> at the 1st {@link GLAutoDrawable#display() display()} method call.<br> + * <i>Lazy</i> {@link GLContext} creation will take a shared {@link GLContext} into account + * which has been set {@link #setSharedContext(GLContext) directly} + * or {@link #setSharedAutoDrawable(GLAutoDrawable) via another GLAutoDrawable}. + * </p> * @param drawable upstream {@link GLDrawableImpl} instance, * may be <code>null</code> for lazy initialization * @param context upstream {@link GLContextImpl} instance, * may not have been made current (created) yet, * may not be associated w/ <code>drawable<code> yet, - * may be <code>null</code> for lazy initialization + * may be <code>null</code> for lazy initialization at 1st {@link #display()}. * @param ownsDevice pass <code>true</code> if {@link AbstractGraphicsDevice#close()} shall be issued, * otherwise pass <code>false</code>. Closing the device is required in case * the drawable is created w/ it's own new instance, e.g. offscreen drawables, @@ -103,6 +113,16 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe resetFPSCounter(); } + @Override + public final void setSharedContext(GLContext sharedContext) throws IllegalStateException { + helper.setSharedContext(this.context, sharedContext); + } + + @Override + public final void setSharedAutoDrawable(GLAutoDrawable sharedAutoDrawable) throws IllegalStateException { + helper.setSharedAutoDrawable(this, sharedAutoDrawable); + } + /** Returns the recursive lock object of the upstream implementation, which synchronizes multithreaded access on top of {@link NativeSurface#lockSurface()}. */ protected abstract RecursiveLock getLock(); @@ -142,16 +162,16 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } /** - * Pulls the {@link GLEventListenerState} from this {@link GLAutoDrawable}. + * Preserves the {@link GLEventListenerState} from this {@link GLAutoDrawable}. * - * @return <code>true</code> if the {@link GLEventListenerState} is pulled successfully from this {@link GLAutoDrawable}, + * @return <code>true</code> if the {@link GLEventListenerState} is preserved successfully from this {@link GLAutoDrawable}, * otherwise <code>false</code>. * - * @throws IllegalStateException if the {@link GLEventListenerState} is already pulled + * @throws IllegalStateException if the {@link GLEventListenerState} is already preserved * - * @see #pushGLEventListenerState() + * @see #restoreGLEventListenerState() */ - protected final boolean pullGLEventListenerState() throws IllegalStateException { + protected final boolean preserveGLEventListenerState() throws IllegalStateException { if( null != glels ) { throw new IllegalStateException("GLEventListenerState already pulled"); } @@ -166,15 +186,15 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } /** - * Pushes a previously {@link #pullGLEventListenerState() pulled} {@link GLEventListenerState} to this {@link GLAutoDrawable}. + * Restores a previously {@link #preserveGLEventListenerState() preserved} {@link GLEventListenerState} to this {@link GLAutoDrawable}. * - * @return <code>true</code> if the {@link GLEventListenerState} was previously {@link #pullGLEventListenerState() pulled} - * and is pushed successfully to this {@link GLAutoDrawable}, + * @return <code>true</code> if the {@link GLEventListenerState} was previously {@link #preserveGLEventListenerState() preserved} + * and is moved successfully to this {@link GLAutoDrawable}, * otherwise <code>false</code>. * - * @see #pullGLEventListenerState() + * @see #preserveGLEventListenerState() */ - protected final boolean pushGLEventListenerState() { + protected final boolean restoreGLEventListenerState() { if( null != glels ) { glels.moveTo(this); glels = null; @@ -320,7 +340,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe protected void destroyImplInLock() { if( preserveGLELSAtDestroy ) { preserveGLStateAtDestroy(false); - pullGLEventListenerState(); + preserveGLEventListenerState(); } if( null != context ) { if( context.isCreated() ) { @@ -389,7 +409,25 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe final RecursiveLock _lock = getLock(); _lock.lock(); try { - if( null != context ) { + if( null == context ) { + boolean contextCreated = false; + final GLDrawableImpl _drawable = drawable; + if ( null != _drawable && _drawable.isRealized() && 0<_drawable.getWidth()*_drawable.getHeight() ) { + final GLContext[] shareWith = { null }; + if( !helper.isSharedGLContextPending(shareWith) ) { + if( !restoreGLEventListenerState() ) { + context = (GLContextImpl) _drawable.createContext(shareWith[0]); + context.setContextCreationFlags(additionalCtxCreationFlags); + contextCreated = true; + // surface is locked/unlocked implicit by context's makeCurrent/release + helper.invokeGL(_drawable, context, defaultDisplayAction, defaultInitAction); + } + } + } + if(DEBUG) { + System.err.println("GLAutoDrawableBase.defaultDisplay: contextCreated "+contextCreated); + } + } else { // surface is locked/unlocked implicit by context's makeCurrent/release helper.invokeGL(drawable, context, defaultDisplayAction, defaultInitAction); } diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index dff55488d..377ebd9f5 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -429,7 +429,7 @@ public abstract class GLContextImpl extends GLContext { contextHandle = 0; glDebugHandler = null; // this maybe impl. in a platform specific way to release remaining shared ctx. - if(GLContextShareSet.contextDestroyed(this) && !GLContextShareSet.hasCreatedSharedLeft(this)) { + if( GLContextShareSet.contextDestroyed(this) && !GLContextShareSet.hasCreatedSharedLeft(this) ) { GLContextShareSet.unregisterSharing(this); } resetStates(false); @@ -647,7 +647,7 @@ public abstract class GLContextImpl extends GLContext { additionalCtxCreationFlags |= GLContext.CTX_OPTION_DEBUG ; } - final GLContextImpl shareWith = (GLContextImpl) GLContextShareSet.getShareContext(this); + final GLContextImpl shareWith = (GLContextImpl) GLContextShareSet.getCreatedShare(this); if (null != shareWith) { shareWith.getDrawableImpl().lockSurface(); } diff --git a/src/jogl/classes/jogamp/opengl/GLContextShareSet.java b/src/jogl/classes/jogamp/opengl/GLContextShareSet.java index 70ade34b7..483767b44 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextShareSet.java +++ b/src/jogl/classes/jogamp/opengl/GLContextShareSet.java @@ -40,7 +40,8 @@ package jogamp.opengl; -import java.util.HashMap; +import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; @@ -59,15 +60,15 @@ public class GLContextShareSet { // This class is implemented using a HashMap which maps from all shared contexts // to a share set, containing all shared contexts itself. - private static final Map<GLContext, ShareSet> shareMap = new HashMap<GLContext, ShareSet>(); + private static final Map<GLContext, ShareSet> shareMap = new IdentityHashMap<GLContext, ShareSet>(); private static final Object dummyValue = new Object(); private static class ShareSet { - private Map<GLContext, Object> allShares = new HashMap<GLContext, Object>(); - private Map<GLContext, Object> createdShares = new HashMap<GLContext, Object>(); - private Map<GLContext, Object> destroyedShares = new HashMap<GLContext, Object>(); + private final Map<GLContext, Object> allShares = new IdentityHashMap<GLContext, Object>(); + private final Map<GLContext, Object> createdShares = new IdentityHashMap<GLContext, Object>(); + private final Map<GLContext, Object> destroyedShares = new IdentityHashMap<GLContext, Object>(); - public void add(GLContext ctx) { + public void add(final GLContext ctx) { if (allShares.put(ctx, dummyValue) == null) { if (ctx.isCreated()) { createdShares.put(ctx, dummyValue); @@ -85,9 +86,9 @@ public class GLContextShareSet { return destroyedShares.keySet(); } - public GLContext getCreatedShare(GLContext ignore) { - for (Iterator<GLContext> iter = createdShares.keySet().iterator(); iter.hasNext(); ) { - GLContext ctx = iter.next(); + public GLContext getCreatedShare(final GLContext ignore) { + for (final Iterator<GLContext> iter = createdShares.keySet().iterator(); iter.hasNext(); ) { + final GLContext ctx = iter.next(); if (ctx != ignore) { return ctx; } @@ -95,21 +96,21 @@ public class GLContextShareSet { return null; } - public void contextCreated(GLContext ctx) { - Object res = destroyedShares.remove(ctx); + public void contextCreated(final GLContext ctx) { + final Object res = destroyedShares.remove(ctx); assert res != null : "State of ShareSet corrupted; thought context " + ctx + " should have been in destroyed set but wasn't"; - res = createdShares.put(ctx, dummyValue); - assert res == null : "State of ShareSet corrupted; thought context " + + final Object res2 = createdShares.put(ctx, dummyValue); + assert res2 == null : "State of ShareSet corrupted; thought context " + ctx + " shouldn't have been in created set but was"; } - public void contextDestroyed(GLContext ctx) { - Object res = createdShares.remove(ctx); + public void contextDestroyed(final GLContext ctx) { + final Object res = createdShares.remove(ctx); assert res != null : "State of ShareSet corrupted; thought context " + ctx + " should have been in created set but wasn't"; - res = destroyedShares.put(ctx, dummyValue); - assert res == null : "State of ShareSet corrupted; thought context " + + final Object res2 = destroyedShares.put(ctx, dummyValue); + assert res2 == null : "State of ShareSet corrupted; thought context " + ctx + " shouldn't have been in destroyed set but was"; } } @@ -117,7 +118,7 @@ public class GLContextShareSet { /** Indicate that contexts <code>share1</code> and <code>share2</code> will share textures and display lists. Both must be non-null. */ - public static synchronized void registerSharing(GLContext share1, GLContext share2) { + public static synchronized void registerSharing(final GLContext share1, final GLContext share2) { if (share1 == null || share2 == null) { throw new IllegalArgumentException("Both share1 and share2 must be non-null"); } @@ -138,7 +139,7 @@ public class GLContextShareSet { } } - public static synchronized void unregisterSharing(GLContext lastContext) { + public static synchronized void unregisterSharing(final GLContext lastContext) { if (lastContext == null) { throw new IllegalArgumentException("Last context is null"); } @@ -166,7 +167,25 @@ public class GLContextShareSet { } } - private static synchronized Set<GLContext> getCreatedSharedImpl(GLContext context) { + /** Returns true if the given GLContext is shared, otherwise false. */ + public static synchronized boolean isShared(final GLContext context) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + final ShareSet share = entryFor(context); + return share != null; + } + + /** Returns one created GLContext shared with the given <code>context</code>, otherwise return <code>null</code>. */ + public static synchronized GLContext getCreatedShare(final GLContext context) { + final ShareSet share = entryFor(context); + if (share == null) { + return null; + } + return share.getCreatedShare(context); + } + + private static synchronized Set<GLContext> getCreatedSharesImpl(final GLContext context) { if (context == null) { throw new IllegalArgumentException("context is null"); } @@ -176,50 +195,56 @@ public class GLContextShareSet { } return null; } - - public static synchronized boolean isShared(GLContext context) { + private static synchronized Set<GLContext> getDestroyedSharesImpl(final GLContext context) { if (context == null) { throw new IllegalArgumentException("context is null"); } final ShareSet share = entryFor(context); - return share != null; + if (share != null) { + return share.getDestroyedShares(); + } + return null; } + /** Returns true if the given GLContext has shared and created GLContext left including itself, otherwise false. */ public static synchronized boolean hasCreatedSharedLeft(GLContext context) { - final Set<GLContext> s = getCreatedSharedImpl(context); - return null != s && s.size()>0 ; + final Set<GLContext> s = getCreatedSharesImpl(context); + return null != s && s.size() > 0; } - /** currently not used .. - public static synchronized Set<GLContext> getCreatedShared(GLContext context) { - final Set<GLContext> s = getCreatedSharedImpl(context); - if (s == null) { - throw new GLException("context is unknown: "+context); - } - return s; + /** Returns a new array-list of created GLContext shared with the given GLContext. */ + public static synchronized ArrayList<GLContext> getCreatedShares(final GLContext context) { + final ArrayList<GLContext> otherShares = new ArrayList<GLContext>(); + final Set<GLContext> createdShares = getCreatedSharesImpl(context); + if( null != createdShares ) { + for (final Iterator<GLContext> iter = createdShares.iterator(); iter.hasNext(); ) { + final GLContext ctx = iter.next(); + if (ctx != context) { + otherShares.add(ctx); + } + } + } + return otherShares; } - public static synchronized Set<GLContext> getDestroyedShared(GLContext context) { - if (context == null) { - throw new IllegalArgumentException("context is null"); - } - ShareSet share = entryFor(context); - if (share == null) { - throw new GLException("context is unknown: "+context); - } - return share.getDestroyedShares(); - } */ - - public static synchronized GLContext getShareContext(GLContext contextToCreate) { - ShareSet share = entryFor(contextToCreate); - if (share == null) { - return null; - } - return share.getCreatedShare(contextToCreate); + /** Returns a new array-list of destroyed GLContext shared with the given GLContext. */ + public static synchronized ArrayList<GLContext> getDestroyedShares(final GLContext context) { + final ArrayList<GLContext> otherShares = new ArrayList<GLContext>(); + final Set<GLContext> destroyedShares = getDestroyedSharesImpl(context); + if( null != destroyedShares ) { + for (final Iterator<GLContext> iter = destroyedShares.iterator(); iter.hasNext(); ) { + final GLContext ctx = iter.next(); + if (ctx != context) { + otherShares.add(ctx); + } + } + } + return otherShares; } - public static synchronized boolean contextCreated(GLContext context) { - ShareSet share = entryFor(context); + /** Mark the given GLContext as being created. */ + public static synchronized boolean contextCreated(final GLContext context) { + final ShareSet share = entryFor(context); if (share != null) { share.contextCreated(context); return true; @@ -227,8 +252,9 @@ public class GLContextShareSet { return false; } - public static synchronized boolean contextDestroyed(GLContext context) { - ShareSet share = entryFor(context); + /** Mark the given GLContext as being destroyed. */ + public static synchronized boolean contextDestroyed(final GLContext context) { + final ShareSet share = entryFor(context); if (share != null) { share.contextDestroyed(context); return true; @@ -245,9 +271,9 @@ public class GLContextShareSet { currently only needed in a fairly esoteric case, when the Java2D/JOGL bridge is active, but the GLBufferSizeTracker mechanism is now always required.) */ - public static void synchronizeBufferObjectSharing(GLContext olderContextOrNull, GLContext newContext) { - GLContextImpl older = (GLContextImpl) olderContextOrNull; - GLContextImpl newer = (GLContextImpl) newContext; + public static void synchronizeBufferObjectSharing(final GLContext olderContextOrNull, final GLContext newContext) { + final GLContextImpl older = (GLContextImpl) olderContextOrNull; + final GLContextImpl newer = (GLContextImpl) newContext; GLBufferSizeTracker tracker = null; if (older != null) { tracker = older.getBufferSizeTracker(); @@ -264,20 +290,20 @@ public class GLContextShareSet { // Internals only below this point - private static ShareSet entryFor(GLContext context) { - return (ShareSet) shareMap.get(context); + private static ShareSet entryFor(final GLContext context) { + return shareMap.get(context); } - private static void addEntry(GLContext context, ShareSet share) { + private static void addEntry(final GLContext context, final ShareSet share) { if (shareMap.get(context) == null) { shareMap.put(context, share); } } - private static ShareSet removeEntry(GLContext context) { - return (ShareSet) shareMap.remove(context); + private static ShareSet removeEntry(final GLContext context) { + return shareMap.remove(context); } - protected static String toHexString(long hex) { + private static String toHexString(long hex) { return "0x" + Long.toHexString(hex); } } diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 1e4cb38fa..ecb9f7dd1 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -313,6 +313,19 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } @Override + public final GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice deviceReq, + GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, + int width, int height) { + final GLDrawable drawable = createOffscreenDrawable( deviceReq, capsRequested, chooser, width, height ); + drawable.setRealized(true); + if(drawable instanceof GLFBODrawableImpl) { + return new GLOffscreenAutoDrawableImpl.FBOImpl( (GLFBODrawableImpl)drawable, null, null, null ); + } + return new GLOffscreenAutoDrawableImpl( drawable, null, null, null); + } + + @Override public final GLDrawable createOffscreenDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 4ce6a7121..cf5d7a206 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -82,6 +82,10 @@ public class GLDrawableHelper { private GLAnimatorControl animatorCtrl; private static Runnable nop = new Runnable() { @Override public void run() {} }; + private GLContext sharedContext; + private GLAutoDrawable sharedAutoDrawable; + + public GLDrawableHelper() { reset(); } @@ -98,6 +102,60 @@ public class GLDrawableHelper { glRunnables.clear(); } animatorCtrl = null; + sharedContext = null; + sharedAutoDrawable = null; + } + + public final void setSharedContext(GLContext thisContext, GLContext sharedContext) throws IllegalStateException { + if( null == sharedContext ) { + throw new IllegalStateException("Null shared GLContext"); + } + if( thisContext == sharedContext ) { + throw new IllegalStateException("Shared GLContext same as local"); + } + if( null != this.sharedContext ) { + throw new IllegalStateException("Shared GLContext already set"); + } + if( null != this.sharedAutoDrawable ) { + throw new IllegalStateException("Shared GLAutoDrawable already set"); + } + this.sharedContext = sharedContext; + } + + public final void setSharedAutoDrawable(GLAutoDrawable thisAutoDrawable, GLAutoDrawable sharedAutoDrawable) throws IllegalStateException { + if( null == sharedAutoDrawable ) { + throw new IllegalStateException("Null shared GLAutoDrawable"); + } + if( thisAutoDrawable == sharedAutoDrawable ) { + throw new IllegalStateException("Shared GLAutoDrawable same as this"); + } + if( null != this.sharedContext ) { + throw new IllegalStateException("Shared GLContext already set"); + } + if( null != this.sharedAutoDrawable ) { + throw new IllegalStateException("Shared GLAutoDrawable already set"); + } + this.sharedAutoDrawable = sharedAutoDrawable; + } + + /** + * @param shared returns the shared GLContext, based on set shared GLAutoDrawable + * or GLContext. Maybe null if none is set. + * @return true if initialization is pending due to a set shared GLAutoDrawable or GLContext + * which is not ready yet. Otherwise false. + */ + public boolean isSharedGLContextPending(GLContext[] shared) { + final GLContext shareWith; + final boolean pending; + if ( null != sharedAutoDrawable ) { + shareWith = sharedAutoDrawable.getContext(); + pending = null == shareWith || !shareWith.isCreated(); + } else { + shareWith = sharedContext; + pending = null != shareWith && !shareWith.isCreated(); + } + shared[0] = shareWith; + return pending; } @Override @@ -612,7 +670,7 @@ public class GLDrawableHelper { public final void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { synchronized(listenersLock) { for (int i=0; i < listeners.size(); i++) { - reshape((GLEventListener) listeners.get(i), drawable, x, y, width, height, 0==i /* setViewport */, true /* checkInit */); + reshape(listeners.get(i), drawable, x, y, width, height, 0==i /* setViewport */, true /* checkInit */); } } } diff --git a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java index f175acf28..345f08e4c 100644 --- a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java @@ -48,7 +48,7 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen * @param context a valid {@link GLContext}, * may not have been made current (created) yet, * may not be associated w/ <code>drawable<code> yet, - * may be <code>null</code> for lazy initialization + * may be <code>null</code> for lazy initialization at 1st {@link #display()}. * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. * @param lock optional upstream lock, may be null */ |