aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java
blob: cd5a16c9eef742cce44d35492b8e93f84ad7c950 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
 * Copyright (c) 2010-2023 JogAmp Community. All rights reserved.
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 */

package jogamp.opengl;

import com.jogamp.nativewindow.AbstractGraphicsDevice;
import com.jogamp.nativewindow.NativeSurface;
import com.jogamp.nativewindow.ProxySurface;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GLCapabilitiesImmutable;
import com.jogamp.opengl.GLContext;
import com.jogamp.opengl.GLDrawable;
import com.jogamp.opengl.GLDrawableFactory;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.GLProfile;

import com.jogamp.common.ExceptionUtils;

public abstract class GLDrawableImpl implements GLDrawable {
  protected static final boolean DEBUG = GLDrawableFactoryImpl.DEBUG;

  protected GLDrawableImpl(final GLDrawableFactory factory, final NativeSurface comp, final boolean realized) {
      this(factory, comp, (GLCapabilitiesImmutable) comp.getGraphicsConfiguration().getRequestedCapabilities(), realized);
  }

  protected GLDrawableImpl(final GLDrawableFactory factory, final NativeSurface comp, final GLCapabilitiesImmutable requestedCapabilities, final boolean realized) {
      this.factory = factory;
      this.surface = comp;
      this.realized = realized;
      this.requestedCapabilities = requestedCapabilities;
  }

  public final GLDrawableFactoryImpl getFactoryImpl() {
    return (GLDrawableFactoryImpl) getFactory();
  }

  @Override
  public final void swapBuffers() throws GLException {
    if( !realized ) { // volatile OK (locked below)
        return; // destroyed already
    }
    final int lockRes = lockSurface(); // it's recursive, so it's ok within [makeCurrent .. release]
    if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) {
        return;
    }
    try {
        if( realized ) { // volatile OK
            final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable)surface.getGraphicsConfiguration().getChosenCapabilities();
            if ( caps.getDoubleBuffered() ) {
                if(!surface.surfaceSwap()) {
                    swapBuffersImpl(true);
                }
            } else {
                final GLContext ctx = GLContext.getCurrent();
                if(null!=ctx && ctx.getGLDrawable()==this) {
                    ctx.getGL().glFlush();
                }
                swapBuffersImpl(false);
            }
        }
    } finally {
        unlockSurface();
    }
    surface.surfaceUpdated(this, surface, System.currentTimeMillis());
  }

  /**
   * Platform and implementation depending surface swap.
   * <p>The surface is locked.</p>
   * <p>
   * If <code>doubleBuffered</code> is <code>true</code>,
   * an actual platform dependent surface swap shall be executed.
   * </p>
   * <p>
   * If <code>doubleBuffered</code> is <code>false</code>,
   * {@link GL#glFlush()} has been called already and
   * the implementation may execute implementation specific code.
   * </p>
   * @param doubleBuffered indicates whether double buffering is enabled, see above.
   */
  protected abstract void swapBuffersImpl(boolean doubleBuffered);

  public final static String toHexString(final long hex) {
    return "0x" + Long.toHexString(hex);
  }

  @Override
  public final GLProfile getGLProfile() {
    return requestedCapabilities.getGLProfile();
  }

  @Override
  public final GLCapabilitiesImmutable getChosenGLCapabilities() {
    return  (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities();
  }

  @Override
  public final GLCapabilitiesImmutable getRequestedGLCapabilities() {
    return requestedCapabilities;
  }

  @Override
  public NativeSurface getNativeSurface() {
    return surface;
  }

  /**
   * called with locked surface @ setRealized(false) or @ lockSurface(..) when surface changed
   * <p>
   * Must be paired w/ {@link #createHandle()}.
   * </p>
   */
  protected void destroyHandle() {}

  /**
   * called with locked surface @ setRealized(true) or @ lockSurface(..) when surface changed
   * <p>
   * Must be paired w/ {@link #destroyHandle()}.
   * </p>
   */
  protected void createHandle() {}

  @Override
  public long getHandle() {
    return surface.getSurfaceHandle();
  }

  @Override
  public final GLDrawableFactory getFactory() {
    return factory;
  }

  @Override
  public final void setRealized(final boolean realizedArg) {
    if ( realized != realizedArg ) { // volatile: OK (locked below)
        final boolean isProxySurface = surface instanceof ProxySurface;
        if(DEBUG) {
            System.err.println(getThreadName() + ": setRealized: drawable "+getClass().getSimpleName()+", surface "+surface.getClass().getSimpleName()+", isProxySurface "+isProxySurface+": "+realized+" -> "+realizedArg);
            ExceptionUtils.dumpStack(System.err);
        }
        final AbstractGraphicsDevice aDevice = surface.getGraphicsConfiguration().getScreen().getDevice();
        if(realizedArg) {
            if(isProxySurface) {
                ((ProxySurface)surface).createNotify();
            }
            if(NativeSurface.LOCK_SURFACE_NOT_READY >= surface.lockSurface()) {
                throw new GLException("GLDrawableImpl.setRealized(true): Surface not ready (lockSurface)");
            }
        } else {
            aDevice.lock();
        }
        try {
            if ( realized != realizedArg ) { // volatile: OK
                realized = realizedArg;
                if(realizedArg) {
                    setRealizedImpl();
                    createHandle();
                } else {
                    destroyHandle();
                    setRealizedImpl();
                }
            }
        } finally {
            if(realizedArg) {
                surface.unlockSurface();
            } else {
                aDevice.unlock();
                if(isProxySurface) {
                    ((ProxySurface)surface).destroyNotify();
                }
            }
        }
    } else if(DEBUG) {
        System.err.println(getThreadName() + ": setRealized: "+getClass().getName()+" "+this.realized+" == "+realizedArg);
    }
  }

  /**
   * Platform specific realization of drawable
   */
  protected abstract void setRealizedImpl();

  /**
   * Callback for special implementations, allowing
   * <ul>
   *   <li>to associate bound context to this drawable (bound == true)
   *       or to remove such association (bound == false).</li>
   *   <li>to trigger GLContext/GLDrawable related lifecycle: <code>construct</code>, <code>destroy</code>.</li>
   * </ul>
   * <p>
   * If <code>bound</code> is <code>true</code>, the context is current and being newly associated w/ this drawable.
   * </p>
   * <p>
   * If <code>bound</code> is <code>false</code>, the context is still current and will be unbound (released and destroyed, or simply disassociated).
   * </p>
   * <p>
   * Being called by {@link GLContextImpl#associateDrawable(boolean)}.
   * </p>
   * @param ctx the just bounded or unbounded context
   * @param bound if <code>true</code> create an association, otherwise remove it
   */
  protected void associateContext(final GLContext ctx, final boolean bound) { }

  /**
   * Callback for special implementations, allowing GLContext to trigger GL related lifecycle: <code>makeCurrent</code>, <code>release</code>.
   * <p>
   * If <code>current</code> is <code>true</code>, the context has just been made current.
   * </p>
   * <p>
   * If <code>current</code> is <code>false</code>, the context is still current and will be release after this method returns.
   * </p>
   * <p>
   * Being called by {@link GLContextImpl#contextMadeCurrent(boolean)}.
   * </p>
   * @see #associateContext(GLContext, boolean)
   */
  protected void contextMadeCurrent(final GLContext glc, final boolean current) { }

  /** Callback for special implementations, allowing GLContext to fetch a custom default render framebuffer. Defaults to zero.*/
  protected int getDefaultDrawFramebuffer() { return 0; }
  /** Callback for special implementations, allowing GLContext to fetch a custom default read framebuffer. Defaults to zero. */
  protected int getDefaultReadFramebuffer() { return 0; }

  /** Callback for special implementations, allowing GLContext to fetch a custom default draw buffer of current framebuffer. */
  protected int getDefaultDrawBuffer(final GL gl) {
      if( gl.isGLES() || getChosenGLCapabilities().getDoubleBuffered() ) {
          // Note-1: Neither ES1 nor ES2 supports selecting the read buffer via glDrawBuffer
          // Note-2: ES3 only supports GL_BACK, GL_NONE or GL_COLOR_ATTACHMENT0+i
          return GL.GL_BACK;
      }
      return GL.GL_FRONT;
  }

  /** Callback for special implementations, allowing GLContext to fetch a custom default read buffer of current framebuffer. */
  protected int getDefaultReadBuffer(final GL gl, final boolean hasDedicatedDrawableRead) {
      if( gl.isGLES() || hasDedicatedDrawableRead || getChosenGLCapabilities().getDoubleBuffered() ) {
          // Note-1: Neither ES1 nor ES2 supports selecting the read buffer via glReadBuffer
          // Note-2: ES3 only supports GL_BACK, GL_NONE or GL_COLOR_ATTACHMENT0+i
          return GL.GL_BACK;
      }
      return GL.GL_FRONT ;
  }

  @Override
  public final boolean isRealized() {
    return realized;
  }

  @Override
  public int getSurfaceWidth() {
    return surface.getSurfaceWidth();
  }

  @Override
  public int getSurfaceHeight() {
    return surface.getSurfaceHeight();
  }

  @Override
  public boolean isGLOriented() {
      return true;
  }

  /**
   * {@link NativeSurface#lockSurface() Locks} the underlying windowing toolkit's {@link NativeSurface surface}.
   * <p>
   * <i>If</i> drawable is {@link #setRealized(boolean) realized},
   * the {@link #getHandle() drawable handle} is valid after successfully {@link NativeSurface#lockSurface() locking}
   * it's {@link NativeSurface surface} until being {@link #unlockSurface() unlocked}.
   * </p>
   * <p>
   * In case the {@link NativeSurface surface} has changed as indicated by it's
   * {@link NativeSurface#lockSurface() lock} result {@link NativeSurface#LOCK_SURFACE_CHANGED},
   * the implementation is required to update this information as needed within it's implementation.
   * </p>
   *
   * @see NativeSurface#lockSurface()
   * @see #getHandle()
   */
  public final int lockSurface() throws GLException {
    final int lockRes = surface.lockSurface();
    if ( NativeSurface.LOCK_SURFACE_CHANGED == lockRes && realized ) {
        // Update the drawable handle, in case the surface handle has changed.
        final long _handle1 = getHandle();
        destroyHandle();
        createHandle();
        final long _handle2 = getHandle();
        if(DEBUG) {
            if( _handle1 != _handle2) {
                System.err.println(getThreadName() + ": Drawable handle changed: "+toHexString(_handle1)+" -> "+toHexString(_handle2));
            }
        }
    }
    return lockRes;

  }

  /**
   * {@link NativeSurface#unlockSurface() Unlocks} the underlying windowing toolkit {@link NativeSurface surface},
   * which may render the {@link #getHandle() drawable handle} invalid.
   *
   * @see NativeSurface#unlockSurface()
   * @see #getHandle()
   */
  public final void unlockSurface() {
    surface.unlockSurface();
  }

  @Override
  public String toString() {
    return getClass().getSimpleName()+"[Realized "+isRealized()+
                ",\n\tFactory   "+getFactory()+
                ",\n\tHandle    "+toHexString(getHandle())+
                ",\n\tSurface   "+getNativeSurface()+"]";
  }

  protected static String getThreadName() { return Thread.currentThread().getName(); }

  protected final GLDrawableFactory factory;
  protected final NativeSurface surface;
  protected final GLCapabilitiesImmutable requestedCapabilities;

  // Indicates whether the surface (if an onscreen context) has been
  // realized. Plausibly, before the surface is realized the JAWT
  // should return an error or NULL object from some of its
  // operations; this appears to be the case on Win32 but is not true
  // at least with Sun's current X11 implementation (1.4.x), which
  // crashes with no other error reported if the DrawingSurfaceInfo is
  // fetched from a locked DrawingSurface during the validation as a
  // result of calling show() on the main thread. To work around this
  // we prevent any JAWT or OpenGL operations from being done until
  // addNotify() is called on the surface.
  protected volatile boolean realized;

}