-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
GLJPanel.java
2401 lines (2151 loc) · 93.8 KB
/
GLJPanel.java
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 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:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*
* Sun gratefully acknowledges that this software was originally authored
* and developed by Kenneth Bradley Russell and Christopher John Kline.
*/
package javax.media.opengl.awt;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.Beans;
import java.nio.IntBuffer;
import java.util.List;
import javax.media.nativewindow.AbstractGraphicsDevice;
import javax.media.nativewindow.NativeSurface;
import javax.media.nativewindow.SurfaceUpdatedListener;
import javax.media.nativewindow.WindowClosingProtocol;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL2ES3;
import javax.media.opengl.GL2GL3;
import javax.media.opengl.GLAnimatorControl;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLCapabilitiesChooser;
import javax.media.opengl.GLCapabilitiesImmutable;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawable;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLException;
import javax.media.opengl.GLFBODrawable;
import javax.media.opengl.GLProfile;
import javax.media.opengl.GLRunnable;
import javax.media.opengl.GLSharedContextSetter;
import javax.media.opengl.Threading;
import javax.swing.JPanel;
import jogamp.nativewindow.jawt.JAWTUtil;
import jogamp.opengl.Debug;
import jogamp.opengl.GLContextImpl;
import jogamp.opengl.GLDrawableFactoryImpl;
import jogamp.opengl.GLDrawableHelper;
import jogamp.opengl.GLDrawableImpl;
import jogamp.opengl.awt.AWTTilePainter;
import jogamp.opengl.awt.Java2D;
import jogamp.opengl.util.glsl.GLSLTextureRaster;
import com.jogamp.common.util.awt.AWTEDTExecutor;
import com.jogamp.nativewindow.awt.AWTPrintLifecycle;
import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol;
import com.jogamp.opengl.FBObject;
import com.jogamp.opengl.GLRendererQuirks;
import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes;
import com.jogamp.opengl.util.GLPixelBuffer.SingletonGLPixelBufferProvider;
import com.jogamp.opengl.util.GLDrawableUtil;
import com.jogamp.opengl.util.GLPixelStorageModes;
import com.jogamp.opengl.util.TileRenderer;
import com.jogamp.opengl.util.awt.AWTGLPixelBuffer;
import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.AWTGLPixelBufferProvider;
import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.SingleAWTGLPixelBufferProvider;
import com.jogamp.opengl.util.texture.TextureState;
/** A lightweight Swing component which provides OpenGL rendering
support. Provided for compatibility with Swing user interfaces
when adding a heavyweight doesn't work either because of
Z-ordering or LayoutManager problems.
<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>
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>
<a name="verticalFlip">
In case</a> the drawable {@link #isGLOriented()} and {@link #setSkipGLOrientationVerticalFlip(boolean) vertical flip is not skipped},
this component performs the required vertical flip to bring the content from OpenGL's orientation into AWT's orientation.
See details about <a href="#fboGLSLVerticalFlip">FBO and GLSL vertical flipping</a>.
</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>
<p>
In case {@link #setSkipGLOrientationVerticalFlip(boolean) vertical-flip is not skipped} and <a href="#fboGLSLVerticalFlip">GLSL based vertical-flip</a> is not performed,
{@link System#arraycopy(Object, int, Object, int, int) System.arraycopy(..)} is used line by line.
This step causes more CPU load per frame and is not hardware-accelerated.
</p>
<p>
Finally the Java2D compositioning takes place via via {@link Graphics#drawImage(java.awt.Image, int, int, int, int, java.awt.image.ImageObserver) Graphics.drawImage(...)}
on the prepared {@link BufferedImage} as described above.
</p>
<P>
* Please read <a href="GLCanvas.html#java2dgl">Java2D OpenGL Remarks</a>.
* </P>
*
<a name="fboGLSLVerticalFlip"><h5>FBO / GLSL Vertical Flip</h5></a>
In case FBO is used and GLSL is available and {@link #setSkipGLOrientationVerticalFlip(boolean) vertical flip is not skipped}, 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>.
<p>
The FBO / GLSL code path uses one texture-unit and binds the FBO texture to it's active texture-target,
see {@link #setTextureUnit(int)} and {@link #getTextureUnit()}.
</p>
<p>
The active and dedicated texture-unit's {@link GL#GL_TEXTURE_2D} state is preserved via {@link TextureState}.
See also {@link Texture#textureCallOrder Order of Texture Commands}.
</p>
<p>
The current gl-viewport is preserved.
</p>
<p>
<i>Warning (Bug 842)</i>: Certain GL states other than viewport and texture (see above)
influencing rendering, will also influence the GLSL vertical flip, e.g. {@link GL#glFrontFace(int) glFrontFace}({@link GL#GL_CCW}).
It is recommended to reset those states to default when leaving the {@link GLEventListener#display(GLAutoDrawable)} method!
We may change this behavior in the future, i.e. preserve all influencing states.
</p>
*/
@SuppressWarnings("serial")
public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosingProtocol, AWTPrintLifecycle, GLSharedContextSetter {
private static final boolean DEBUG;
private static final boolean DEBUG_VIEWPORT;
private static final boolean USE_GLSL_TEXTURE_RASTERIZER;
private static final boolean SKIP_VERTICAL_FLIP_DEFAULT;
private static final boolean SKIP_HIDPI;
/** Indicates whether the Java 2D OpenGL pipeline is requested by user. */
private static final boolean java2dOGLEnabledByProp;
/** Indicates whether the Java 2D OpenGL pipeline is enabled, resource-compatible and requested by user. */
private static final boolean useJava2DGLPipeline;
/** Indicates whether the Java 2D OpenGL pipeline's usage is error free. */
private static boolean java2DGLPipelineOK;
static {
Debug.initSingleton();
DEBUG = Debug.debug("GLJPanel");
DEBUG_VIEWPORT = Debug.isPropertyDefined("jogl.debug.GLJPanel.Viewport", true);
USE_GLSL_TEXTURE_RASTERIZER = !Debug.isPropertyDefined("jogl.gljpanel.noglsl", true);
SKIP_VERTICAL_FLIP_DEFAULT = Debug.isPropertyDefined("jogl.gljpanel.noverticalflip", true);
SKIP_HIDPI = Debug.isPropertyDefined("jogl.gljpanel.nohidpi", true);
boolean enabled = Debug.getBooleanProperty("sun.java2d.opengl", false);
java2dOGLEnabledByProp = enabled && !Debug.isPropertyDefined("jogl.gljpanel.noogl", true);
enabled = false;
if( java2dOGLEnabledByProp ) {
// Force eager initialization of part of the Java2D class since
// otherwise it's likely it will try to be initialized while on
// the Queue Flusher Thread, which is not allowed
if (Java2D.isOGLPipelineResourceCompatible() && Java2D.isFBOEnabled()) {
if( null != Java2D.getShareContext(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()) ) {
enabled = true;
}
}
}
useJava2DGLPipeline = enabled;
java2DGLPipelineOK = enabled;
if( DEBUG ) {
System.err.println("GLJPanel: DEBUG_VIEWPORT "+DEBUG_VIEWPORT);
System.err.println("GLJPanel: USE_GLSL_TEXTURE_RASTERIZER "+USE_GLSL_TEXTURE_RASTERIZER);
System.err.println("GLJPanel: SKIP_VERTICAL_FLIP_DEFAULT "+SKIP_VERTICAL_FLIP_DEFAULT);
System.err.println("GLJPanel: java2dOGLEnabledByProp "+java2dOGLEnabledByProp);
System.err.println("GLJPanel: useJava2DGLPipeline "+useJava2DGLPipeline);
System.err.println("GLJPanel: java2DGLPipelineOK "+java2DGLPipelineOK);
}
}
private static SingleAWTGLPixelBufferProvider singleAWTGLPixelBufferProvider = null;
private static synchronized SingleAWTGLPixelBufferProvider getSingleAWTGLPixelBufferProvider() {
if( null == singleAWTGLPixelBufferProvider ) {
singleAWTGLPixelBufferProvider = new SingleAWTGLPixelBufferProvider( true /* allowRowStride */ );
}
return singleAWTGLPixelBufferProvider;
}
private final GLDrawableHelper helper;
private boolean autoSwapBufferMode;
private volatile boolean isInitialized;
//
// Data used for either pbuffers or pixmap-based offscreen surfaces
//
private AWTGLPixelBufferProvider customPixelBufferProvider = null;
/** Single buffered offscreen caps */
private GLCapabilitiesImmutable offscreenCaps;
private final GLProfile glProfile;
private final GLDrawableFactoryImpl factory;
private final GLCapabilitiesChooser chooser;
private int additionalCtxCreationFlags = 0;
// Lazy reshape notification: reshapeWidth -> panelWidth -> backend.width
private boolean handleReshape = false;
private boolean sendReshape = true;
// For handling reshape events lazily: reshapeWidth -> panelWidth -> backend.width
private int reshapeWidth;
private int reshapeHeight;
private int reshapeScale;
// Width of the actual GLJPanel: reshapeWidth -> panelWidth -> backend.width
private int panelWidth = 0;
private int panelHeight = 0;
private int panelScale = 0;
// These are always set to (0, 0) except when the Java2D / OpenGL
// pipeline is active
private int viewportX;
private int viewportY;
private int requestedTextureUnit = 0; // default
// The backend in use
private volatile Backend backend;
private boolean skipGLOrientationVerticalFlip = SKIP_VERTICAL_FLIP_DEFAULT;
// Used by all backends either directly or indirectly to hook up callbacks
private final Updater updater = new Updater();
private boolean oglPipelineUsable() {
return null == customPixelBufferProvider && useJava2DGLPipeline && java2DGLPipelineOK;
}
private volatile boolean isShowing;
private final HierarchyListener hierarchyListener = new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
isShowing = GLJPanel.this.isShowing();
}
};
private final AWTWindowClosingProtocol awtWindowClosingProtocol =
new AWTWindowClosingProtocol(this, new Runnable() {
@Override
public void run() {
GLJPanel.this.destroy();
}
}, null);
/** Creates a new GLJPanel component with a default set of OpenGL
capabilities and using the default OpenGL capabilities selection
mechanism.
* @throws GLException if no default profile is available for the default desktop device.
*/
public GLJPanel() throws GLException {
this(null);
}
/** Creates a new GLJPanel component with the requested set of
OpenGL capabilities, using the default OpenGL capabilities
selection mechanism.
* @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device.
*/
public GLJPanel(GLCapabilitiesImmutable userCapsRequest) throws GLException {
this(userCapsRequest, null, null);
}
/** Creates a new GLJPanel 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.
* @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device.
*/
public GLJPanel(GLCapabilitiesImmutable userCapsRequest, GLCapabilitiesChooser chooser)
throws GLException
{
this(userCapsRequest, chooser, null);
}
/** Creates a new GLJPanel 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="../../../spec-overview.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.
* @throws GLException if no GLCapabilities are given and no default profile is available for the default desktop device.
* @deprecated Use {@link #GLJPanel(GLCapabilitiesImmutable, GLCapabilitiesChooser)}
* and set shared GLContext via {@link #setSharedContext(GLContext)} or {@link #setSharedAutoDrawable(GLAutoDrawable)}.
*/
public GLJPanel(GLCapabilitiesImmutable userCapsRequest, GLCapabilitiesChooser chooser, GLContext shareWith)
throws GLException
{
super();
// Works around problems on many vendors' cards; we don't need a
// back buffer for the offscreen surface anyway
{
GLCapabilities caps;
if (userCapsRequest != null) {
caps = (GLCapabilities) userCapsRequest.cloneMutable();
} else {
caps = new GLCapabilities(GLProfile.getDefault(GLProfile.getDefaultDevice()));
}
caps.setDoubleBuffered(false);
offscreenCaps = caps;
}
this.glProfile = offscreenCaps.getGLProfile();
this.factory = GLDrawableFactoryImpl.getFactoryImpl(glProfile);
this.chooser = chooser;
helper = new GLDrawableHelper();
if( null != shareWith ) {
helper.setSharedContext(null, shareWith);
}
autoSwapBufferMode = helper.getAutoSwapBufferMode();
this.setFocusable(true); // allow keyboard input!
this.addHierarchyListener(hierarchyListener);
this.isShowing = isShowing();
}
/**
* Attempts to initialize the backend, if not initialized yet.
* <p>
* If backend is already initialized method returns <code>true</code>.
* </p>
* <p>
* If <code>offthread</code> is <code>true</code>, initialization will kicked off
* on a <i>short lived</i> arbitrary thread and method returns immediately.<br/>
* If platform supports such <i>arbitrary thread</i> initialization method returns
* <code>true</code>, otherwise <code>false</code>.
* </p>
* <p>
* If <code>offthread</code> is <code>false</code>, initialization be performed
* on the current thread and method returns after initialization.<br/>
* Method returns <code>true</code> if initialization was successful, otherwise <code>false</code>.
* <p>
* @param offthread
*/
public final boolean initializeBackend(boolean offthread) {
if( offthread ) {
new Thread(getThreadName()+"-GLJPanel_Init") {
public void run() {
if( !isInitialized ) {
initializeBackendImpl();
}
} }.start();
return true;
} else {
if( !isInitialized ) {
return initializeBackendImpl();
} else {
return true;
}
}
}
@Override
public final void setSharedContext(GLContext sharedContext) throws IllegalStateException {
helper.setSharedContext(this.getContext(), sharedContext);
}
@Override
public final void setSharedAutoDrawable(GLAutoDrawable sharedAutoDrawable) throws IllegalStateException {
helper.setSharedAutoDrawable(this, sharedAutoDrawable);
}
public AWTGLPixelBufferProvider getCustomPixelBufferProvider() { return customPixelBufferProvider; }
/**
* @param custom custom {@link AWTGLPixelBufferProvider}
* @throws IllegalArgumentException if <code>custom</code> is <code>null</code>
* @throws IllegalStateException if backend is already realized, i.e. this instanced already painted once.
*/
public void setPixelBufferProvider(AWTGLPixelBufferProvider custom) throws IllegalArgumentException, IllegalStateException {
if( null == custom ) {
throw new IllegalArgumentException("Null PixelBufferProvider");
}
if( null != backend ) {
throw new IllegalStateException("Backend already realized.");
}
customPixelBufferProvider = custom;
}
@Override
public final Object getUpstreamWidget() {
return this;
}
@Override
public void display() {
if( isShowing || ( printActive && isVisible() ) ) {
if (EventQueue.isDispatchThread()) {
// Want display() to be synchronous, so call paintImmediately()
paintImmediately(0, 0, getWidth(), getHeight());
} else {
// Multithreaded redrawing of Swing components is not allowed,
// so do everything on the event dispatch thread
try {
EventQueue.invokeAndWait(paintImmediatelyAction);
} catch (Exception e) {
throw new GLException(e);
}
}
}
}
protected void dispose() {
if(DEBUG) {
System.err.println(getThreadName()+": GLJPanel.dispose() - start");
// Thread.dumpStack();
}
if (backend != null && backend.getContext() != null) {
boolean animatorPaused = false;
GLAnimatorControl animator = getAnimator();
if(null!=animator) {
animatorPaused = animator.pause();
}
if(backend.getContext().isCreated()) {
Threading.invoke(true, disposeAction, getTreeLock());
}
if(null != backend) {
// not yet destroyed due to backend.isUsingOwnThreadManagment() == true
backend.destroy();
isInitialized = false;
}
if(animatorPaused) {
animator.resume();
}
}
if(DEBUG) {
System.err.println(getThreadName()+": GLJPanel.dispose() - stop");
}
}
/**
* Just an alias for removeNotify
*/
@Override
public void destroy() {
removeNotify();
}
/** Overridden to cause OpenGL rendering to be performed during
repaint cycles. Subclasses which override this method must call
super.paintComponent() in their paintComponent() method in order
to function properly. <P>
<DL><DD><CODE>paintComponent</CODE> in class <CODE>javax.swing.JComponent</CODE></DD></DL> */
@Override
protected void paintComponent(final Graphics g) {
if (Beans.isDesignTime()) {
// Make GLJPanel behave better in NetBeans GUI builder
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
FontMetrics fm = g.getFontMetrics();
String name = getName();
if (name == null) {
name = getClass().getName();
int idx = name.lastIndexOf('.');
if (idx >= 0) {
name = name.substring(idx + 1);
}
}
Rectangle2D bounds = fm.getStringBounds(name, g);
g.setColor(Color.WHITE);
g.drawString(name,
(int) ((getWidth() - bounds.getWidth()) / 2),
(int) ((getHeight() + bounds.getHeight()) / 2));
return;
}
if( !isInitialized ) {
initializeBackendImpl();
}
if (!isInitialized || printActive) {
return;
}
// NOTE: must do this when the context is not current as it may
// involve destroying the pbuffer (current context) and
// re-creating it -- tricky to do properly while the context is
// current
if( !printActive ) {
if (handleReshape) {
handleReshape = false;
sendReshape = handleReshape();
}
if( isShowing ) {
updater.setGraphics(g);
backend.doPaintComponent(g);
}
}
}
/** Overridden to track when this component is added to a container.
Subclasses which override this method must call
super.addNotify() in their addNotify() method in order to
function properly. <P>
<DL><DD><CODE>addNotify</CODE> in class <CODE>java.awt.Component</CODE></DD></DL> */
@Override
public void addNotify() {
super.addNotify();
awtWindowClosingProtocol.addClosingListener();
if (DEBUG) {
System.err.println(getThreadName()+": GLJPanel.addNotify()");
}
}
/** 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
function properly. <P>
<DL><DD><CODE>removeNotify</CODE> in class <CODE>java.awt.Component</CODE></DD></DL> */
@Override
public void removeNotify() {
awtWindowClosingProtocol.removeClosingListener();
dispose();
super.removeNotify();
}
/** Overridden to cause {@link GLDrawableHelper#reshape} to be
called on all registered {@link GLEventListener}s. Subclasses
which override this method must call super.reshape() in
their reshape() method in order to function properly. <P>
*
* {@inheritDoc}
*/
@SuppressWarnings("deprecation")
@Override
public void reshape(int x, int y, int width, int height) {
super.reshape(x, y, width, height);
final int scale = getPixelScale();
final int scaledWidth = scale * width;
final int scaledHeight = scale * height;
if( DEBUG ) {
System.err.println(getThreadName()+": GLJPanel.reshape.0 "+this.getName()+" resize"+(printActive?"WithinPrint":"")+
" [ this "+getWidth()+"x"+getHeight()+", pixelScale "+scale+
", panel "+panelWidth+"x"+panelHeight +
", reshape: " +reshapeWidth+"x"+reshapeHeight +
"] -> "+(printActive?"[skipped] ":"") + width+"x"+height+" * "+scale+" -> "+scaledWidth+"x"+scaledHeight);
}
if( !printActive ) {
reshapeWidth = scaledWidth;
reshapeHeight = scaledHeight;
reshapeScale = scale;
handleReshape = true;
}
}
private volatile boolean printActive = false;
private GLAnimatorControl printAnimator = null;
private GLAutoDrawable printGLAD = null;
private AWTTilePainter printAWTTiles = null;
@Override
public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) {
printActive = true;
final int componentCount = isOpaque() ? 3 : 4;
final TileRenderer printRenderer = new TileRenderer();
printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG);
AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT);
}
private final Runnable setupPrintOnEDT = new Runnable() {
@Override
public void run() {
if( !isInitialized ) {
initializeBackendImpl();
}
if (!isInitialized) {
if(DEBUG) {
System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable not valid yet");
}
printActive = false;
return; // not yet available ..
}
if( !isVisible() ) {
if(DEBUG) {
System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, panel not visible");
}
printActive = false;
return; // not yet available ..
}
sendReshape = false; // clear reshape flag
handleReshape = false; // ditto
printAnimator = helper.getAnimator();
if( null != printAnimator ) {
printAnimator.remove(GLJPanel.this);
}
printGLAD = GLJPanel.this; // default: re-use
final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable();
final int printNumSamples = printAWTTiles.getNumSamples(caps);
GLDrawable printDrawable = printGLAD.getDelegatedDrawable();
final boolean reqNewGLADSamples = printNumSamples != caps.getNumSamples();
final boolean reqNewGLADSize = printAWTTiles.customTileWidth != -1 && printAWTTiles.customTileWidth != printDrawable.getWidth() ||
printAWTTiles.customTileHeight != -1 && printAWTTiles.customTileHeight != printDrawable.getHeight();
final boolean reqNewGLAD = reqNewGLADSamples || reqNewGLADSize ;
if( DEBUG ) {
System.err.println("AWT print.setup: reqNewGLAD "+reqNewGLAD+"[ samples "+reqNewGLADSamples+", size "+reqNewGLADSize+"], "+
", drawableSize "+printDrawable.getWidth()+"x"+printDrawable.getHeight()+
", customTileSize "+printAWTTiles.customTileWidth+"x"+printAWTTiles.customTileHeight+
", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+
", numSamples "+printAWTTiles.customNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator);
}
if( reqNewGLAD ) {
caps.setDoubleBuffered(false);
caps.setOnscreen(false);
caps.setSampleBuffers(0 < printNumSamples);
caps.setNumSamples(printNumSamples);
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);
GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD);
printDrawable = printGLAD.getDelegatedDrawable();
}
printAWTTiles.setGLOrientation( !GLJPanel.this.skipGLOrientationVerticalFlip && printGLAD.isGLOriented(), printGLAD.isGLOriented() );
printAWTTiles.renderer.setTileSize(printDrawable.getWidth(), printDrawable.getHeight(), 0);
printAWTTiles.renderer.attachAutoDrawable(printGLAD);
if( DEBUG ) {
System.err.println("AWT print.setup "+printAWTTiles);
System.err.println("AWT print.setup AA "+printNumSamples+", "+caps);
System.err.println("AWT print.setup printGLAD: "+printGLAD.getWidth()+"x"+printGLAD.getHeight()+", "+printGLAD);
System.err.println("AWT print.setup printDraw: "+printDrawable.getWidth()+"x"+printDrawable.getHeight()+", "+printDrawable);
}
}
};
@Override
public void releasePrint() {
if( !printActive ) {
throw new IllegalStateException("setupPrint() not called");
}
sendReshape = false; // clear reshape flag
handleReshape = false; // ditto
AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, releasePrintOnEDT);
}
private final Runnable releasePrintOnEDT = new Runnable() {
@Override
public void run() {
if( DEBUG ) {
System.err.println(getThreadName()+": GLJPanel.releasePrintOnEDT.0 "+printAWTTiles);
}
printAWTTiles.dispose();
printAWTTiles= null;
if( printGLAD != GLJPanel.this ) {
GLDrawableUtil.swapGLContextAndAllGLEventListener(printGLAD, GLJPanel.this);
printGLAD.destroy();
}
printGLAD = null;
if( null != printAnimator ) {
printAnimator.add(GLJPanel.this);
printAnimator = null;
}
// trigger reshape, i.e. gl-viewport and -listener - this component might got resized!
final int awtWidth = GLJPanel.this.getWidth();
final int awtHeight= GLJPanel.this.getHeight();
final int scale = getPixelScale();
final int scaledAWTWidth = scale * awtWidth;
final int scaledAWTHeight= scale * awtHeight;
final GLDrawable drawable = GLJPanel.this.getDelegatedDrawable();
if( scaledAWTWidth != panelWidth || scaledAWTHeight != panelHeight ||
drawable.getWidth() != panelWidth || drawable.getHeight() != panelHeight ) {
// -> !( awtSize == panelSize == drawableSize )
if ( DEBUG ) {
System.err.println(getThreadName()+": GLJPanel.releasePrintOnEDT.0: resizeWithinPrint panel " +panelWidth+"x"+panelHeight + " @ scale "+panelScale+
", draw "+drawable.getWidth()+"x"+drawable.getHeight()+
" -> " + awtWidth+"x"+awtHeight+" * "+scale+" -> "+scaledAWTWidth+"x"+scaledAWTHeight);
}
reshapeWidth = scaledAWTWidth;
reshapeHeight = scaledAWTHeight;
reshapeScale = scale;
sendReshape = handleReshape(); // reshapeSize -> panelSize, backend reshape w/ GL reshape
} else {
sendReshape = true; // only GL reshape
}
printActive = false;
display();
}
};
@Override
public void print(Graphics graphics) {
if( !printActive ) {
throw new IllegalStateException("setupPrint() not called");
}
if(DEBUG && !EventQueue.isDispatchThread()) {
System.err.println(getThreadName()+": Warning: GLCanvas print - not called from AWT-EDT");
// we cannot dispatch print on AWT-EDT due to printing internal locking ..
}
sendReshape = false; // clear reshape flag
handleReshape = false; // ditto
final Graphics2D g2d = (Graphics2D)graphics;
try {
printAWTTiles.setupGraphics2DAndClipBounds(g2d, getWidth(), getHeight());
final TileRenderer tileRenderer = printAWTTiles.renderer;
if( DEBUG ) {
System.err.println("AWT print.0: "+tileRenderer);
}
if( !tileRenderer.eot() ) {
try {
do {
if( printGLAD != GLJPanel.this ) {
tileRenderer.display();
} else {
backend.doPlainPaint();
}
} while ( !tileRenderer.eot() );
if( DEBUG ) {
System.err.println("AWT print.1: "+printAWTTiles);
}
} finally {
tileRenderer.reset();
printAWTTiles.resetGraphics2D();
}
}
} catch (NoninvertibleTransformException nte) {
System.err.println("Catched: Inversion failed of: "+g2d.getTransform());
nte.printStackTrace();
}
if( DEBUG ) {
System.err.println("AWT print.X: "+printAWTTiles);
}
}
@Override
protected void printComponent(Graphics g) {
if( DEBUG ) {
System.err.println("AWT printComponent.X: "+printAWTTiles);
}
print(g);
}
@Override
public void setOpaque(boolean opaque) {
if (backend != null) {
backend.setOpaque(opaque);
}
super.setOpaque(opaque);
}
@Override
public void addGLEventListener(GLEventListener listener) {
helper.addGLEventListener(listener);
}
@Override
public void addGLEventListener(int index, GLEventListener listener) {
helper.addGLEventListener(index, listener);
}
@Override
public int getGLEventListenerCount() {
return helper.getGLEventListenerCount();
}
@Override
public GLEventListener getGLEventListener(int index) throws IndexOutOfBoundsException {
return helper.getGLEventListener(index);
}
@Override
public boolean areAllGLEventListenerInitialized() {
return helper.areAllGLEventListenerInitialized();
}
@Override
public boolean getGLEventListenerInitState(GLEventListener listener) {
return helper.getGLEventListenerInitState(listener);
}
@Override
public void setGLEventListenerInitState(GLEventListener listener, boolean initialized) {
helper.setGLEventListenerInitState(listener, initialized);
}
@Override
public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove) {
final DisposeGLEventListenerAction r = new DisposeGLEventListenerAction(listener, remove);
if (EventQueue.isDispatchThread()) {
r.run();
} else {
// Multithreaded redrawing of Swing components is not allowed,
// so do everything on the event dispatch thread
try {
EventQueue.invokeAndWait(r);
} catch (Exception e) {
throw new GLException(e);
}
}
return r.listener;
}
@Override
public GLEventListener removeGLEventListener(GLEventListener listener) {
return helper.removeGLEventListener(listener);
}
@Override
public void setAnimator(GLAnimatorControl animatorControl) {
helper.setAnimator(animatorControl);
}
@Override
public GLAnimatorControl getAnimator() {
return helper.getAnimator();
}
@Override
public final Thread setExclusiveContextThread(Thread t) throws GLException {
return helper.setExclusiveContextThread(t, getContext());
}
@Override
public final Thread getExclusiveContextThread() {
return helper.getExclusiveContextThread();
}
@Override
public boolean invoke(boolean wait, GLRunnable glRunnable) {
return helper.invoke(this, wait, glRunnable);
}
@Override
public boolean invoke(final boolean wait, final List<GLRunnable> glRunnables) {
return helper.invoke(this, wait, glRunnables);
}
@Override
public GLContext createContext(GLContext shareWith) {
final Backend b = backend;
if ( null == b ) {
return null;
}
return b.createContext(shareWith);
}
@Override
public void setRealized(boolean realized) {
}
@Override
public boolean isRealized() {
return isInitialized;
}
@Override
public GLContext setContext(GLContext newCtx, boolean destroyPrevCtx) {
final Backend b = backend;
if ( null == b ) {
return null;
}
final GLContext oldCtx = b.getContext();
GLDrawableHelper.switchContext(b.getDrawable(), oldCtx, destroyPrevCtx, newCtx, additionalCtxCreationFlags);
b.setContext(newCtx);
return oldCtx;
}
@Override
public final GLDrawable getDelegatedDrawable() {
final Backend b = backend;
if ( null == b ) {
return null;
}
return b.getDrawable();
}
@Override
public GLContext getContext() {
final Backend b = backend;
if ( null == b ) {
return null;
}
return b.getContext();
}
@Override
public GL getGL() {
if (Beans.isDesignTime()) {
return null;
}
GLContext context = getContext();
return (context == null) ? null : context.getGL();
}
@Override
public GL setGL(GL gl) {
GLContext context = getContext();
if (context != null) {
context.setGL(gl);
return gl;
}
return null;
}
@Override
public void setAutoSwapBufferMode(boolean enable) {
this.autoSwapBufferMode = enable;
boolean backendHandlesSwapBuffer = false;
if( isInitialized ) {
final Backend b = backend;
if ( null != b ) {
backendHandlesSwapBuffer= b.handlesSwapBuffer();
}
}
if( !backendHandlesSwapBuffer ) {
helper.setAutoSwapBufferMode(enable);
}
}
@Override
public boolean getAutoSwapBufferMode() {
return autoSwapBufferMode;
}
@Override
public void swapBuffers() {
if( isInitialized ) {
final Backend b = backend;
if ( null != b ) {
b.swapBuffers();
}
}
}
@Override
public void setContextCreationFlags(int flags) {
additionalCtxCreationFlags = flags;
}
@Override
public int getContextCreationFlags() {