-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathLwjglCanvas.java
More file actions
1063 lines (949 loc) · 35.4 KB
/
LwjglCanvas.java
File metadata and controls
1063 lines (949 loc) · 35.4 KB
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) 2009-2026 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.system.lwjgl;
import com.jme3.input.JoyInput;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.TouchInput;
import com.jme3.input.awt.AwtKeyInput;
import com.jme3.input.awt.AwtMouseInput;
import com.jme3.input.lwjgl.SdlJoystickInput;
import com.jme3.math.Vector2f;
import com.jme3.system.AppSettings;
import com.jme3.system.Displays;
import com.jme3.system.JmeCanvasContext;
import com.jme3.system.lwjglx.LwjglxGLPlatform;
import java.awt.AWTException;
import java.awt.Canvas;
import java.awt.Component;
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.geom.AffineTransform;
import javax.swing.SwingUtilities;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.Version;
import org.lwjgl.awthacks.NonClearGraphics;
import org.lwjgl.awthacks.NonClearGraphics2D;
import org.lwjgl.opengl.awt.GLData;
import org.lwjgl.system.Configuration;
import org.lwjgl.opencl.APPLEGLSharing;
import org.lwjgl.opencl.KHRGLSharing;
import org.lwjgl.opengl.CGL;
import org.lwjgl.opengl.WGL;
import org.lwjgl.system.Platform;
import static org.lwjgl.system.MemoryUtil.*;
import static com.jme3.system.lwjglx.LwjglxDefaultGLPlatform.*;
/**
* Class <code>LwjglCanvas</code> that integrates <a href="https://github.com/LWJGLX/lwjgl3-awt">LWJGLX</a>
* which allows using AWT-Swing components.
*
* <p>
* If <b>LwjglCanvas</b> throws an exception due to configuration problems, we can debug as follows:
* <br>
* - In <code>AppSettings</code>, set this property to enable a debug that displays
* the effective data for the context.
* <pre><code>
* ....
* AppSettings settings = new AppSettings(true);
* settings.putBoolean("GLDataEffectiveDebug", true);
* ...
* </code></pre>
*
* <p>
* <b>NOTE:</b> If running <code>LwjglCanvas</code> on older machines, the <code>SRGB | Gamma Correction</code> option
* will raise an exception, so it should be disabled.
* <pre><code>
* ....
* AppSettings settings = new AppSettings(true);
* settings.setGammaCorrection(false);
* ...
* </code></pre>
*
* @author wil
*/
public class LwjglCanvas extends LwjglWindow implements JmeCanvasContext, Runnable {
/** Logger class. */
private static final Logger LOGGER = Logger.getLogger(LwjglCanvas.class.getName());
/** GL versions map. */
private static final Map<String, Consumer<GLData>> RENDER_CONFIGS = new HashMap<>();
/*
Register the different versions.
*/
static {
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL30, (data) -> {
data.majorVersion = 3;
data.minorVersion = 0;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL31, (data) -> {
data.majorVersion = 3;
data.minorVersion = 1;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL32, (data) -> {
data.majorVersion = 3;
data.minorVersion = 2;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL33, (data) -> {
data.majorVersion = 3;
data.minorVersion = 3;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL40, (data) -> {
data.majorVersion = 4;
data.minorVersion = 0;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL41, (data) -> {
data.majorVersion = 4;
data.minorVersion = 1;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL42, (data) -> {
data.majorVersion = 4;
data.minorVersion = 2;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL43, (data) -> {
data.majorVersion = 4;
data.minorVersion = 3;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL44, (data) -> {
data.majorVersion = 4;
data.minorVersion = 4;
data.profile = GLData.Profile.COMPATIBILITY;
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL45, (data) -> {
data.majorVersion = 4;
data.minorVersion = 5;
data.profile = GLData.Profile.COMPATIBILITY;
});
}
/**
* An AWT <code>java.awt.Canvas</code> that supports to be drawn on using OpenGL.
*/
private class LwjglAWTGLCanvas extends Canvas {
/**
* A {@link com.jme3.system.lwjglx.LwjglxGLPlatform} object.
* @see org.lwjgl.opengl.awt.PlatformGLCanvas
*/
private LwjglxGLPlatform platformCanvas;
/** The OpenGL context (LWJGL3-AWT). */
private long context;
/**
* Information object used to create the OpenGL context.
*/
private GLData data;
/** Effective data to initialize the context. */
private GLData effective;
/**
* Constructor of the <code>LwjglAWTGLCanva</code> class where objects are
* initialized for OpenGL-AWT rendering
*
* @param data A {@link org.lwjgl.opengl.awt.GLData} object
*/
public LwjglAWTGLCanvas(GLData data) {
this.effective = new GLData();
this.context = NULL;
this.data = data;
try {
platformCanvas = createLwjglxGLPlatform();
} catch (UnsupportedOperationException e) {
listener.handleError(e.getLocalizedMessage(), e);
}
}
/**
* (non-Javadoc)
* @see java.awt.Component#addComponentListener(java.awt.event.ComponentListener)
* @param l object-listener
*/
@Override
public synchronized void addComponentListener(ComponentListener l) {
super.addComponentListener(l);
}
/**
* This is where the OpenGL rendering context is generated.
*/
public void createContext() {
try {
context = platformCanvas.create(this, data, effective);
} catch (AWTException e) {
listener.handleError("Exception while creating the OpenGL context", e);
}
}
/** (non-Javadoc) */
public boolean hasContext() {
synchronized (lock) {
return context != NULL;
}
}
/**
* Make the canvas' context current. It is highly recommended that the
* context is only made current inside the AWT thread (for example in an
* overridden paintGL()).
*/
public void makeCurrent() {
synchronized (lock) {
if (context == NULL) {
throw new IllegalStateException("Canvas not yet displayable");
}
platformCanvas.makeCurrent(context);
}
}
/**
* Release the rendering context
*/
public void releaseContext() {
synchronized (lock) {
platformCanvas.makeCurrent(NULL);
}
}
/**
* Returns the effective data (recommended or ideal) to initialize the
* LWJGL3-AWT context.
*
* @return A {@link org.lwjgl.opengl.awt.GLData} object
*/
public GLData getGLDataEffective() {
return effective;
}
/**
* To start drawing on the AWT surface, the AWT threads must be locked to
* avoid conflicts when drawing on the canvas.
*/
public void lock() {
synchronized (lock) {
try {
platformCanvas.lock();// <- MUST lock on Linux
} catch (AWTException e) {
listener.handleError("Failed to lock Canvas", e);
}
}
}
/**
* Unlock the current AWT thread to continue updating the user interface.
*/
public void unlock() {
synchronized (lock) {
try {
platformCanvas.unlock();// <- MUST unlock on Linux
} catch (AWTException e) {
listener.handleError("Failed to unlock Canvas", e);
}
}
}
/**
* Frees up the drawing surface
*/
public void doDisposeCanvas() {
platformCanvas.dispose();
}
/**
* This is where you actually draw on the canvas (framebuffer).
*/
public void swapBuffers() {
platformCanvas.swapBuffers();
}
/**
* (non-Javadoc)
* @see java.awt.Component#addNotify()
*/
@Override
public void addNotify() {
super.addNotify();
/* you have to notify if the canvas is visible to draw on it. */
synchronized (lock) {
hasNativePeer.set(true);
}
requestFocusInWindow();
}
/**
* (non-Javadoc)
* @see java.awt.Component#removeNotify()
*/
@Override
public void removeNotify() {
if (needClose.get()) {
LOGGER.log(Level.FINE, "EDT: Application is stopped. Not restoring canvas.");
super.removeNotify();
return;
}
synchronized (lock) {
// prepare for a possible re-adding
hasNativePeer.set(false);
reinitcontext.set(true);
while (reinitcontext.get()) {
try {
lock.wait();
} catch (InterruptedException ex) {
super.removeNotify();
return;
}
}
reinitcontext.set(false);
}
// GL context is dead at this point
LOGGER.log(Level.FINE, "EDT: Acknowledged receipt of canvas death");
super.removeNotify();
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjglx.LwjglxGLPlatform#destroy()
*/
public void destroy() {
platformCanvas.destroy();
}
/** (non-Javadoc) */
public void deleteContext() {
platformCanvas.deleteContext(context);
}
/**
* Returns Graphics object that ignores {@link java.awt.Graphics#clearRect(int, int, int, int)}
* calls.
* <p>
* This is done so that the frame buffer will not be cleared by AWT/Swing internals.
*
* @see org.lwjgl.awthacks.NonClearGraphics2D
* @see org.lwjgl.awthacks.NonClearGraphics
* @return Graphics
*/
@Override
public Graphics getGraphics() {
Graphics graphics = super.getGraphics();
if (graphics instanceof Graphics2D) {
return new NonClearGraphics2D((Graphics2D) graphics);
}
return new NonClearGraphics(graphics);
}
}
/** Canvas-AWT. */
private final LwjglAWTGLCanvas canvas;
/**
* Configuration data to start the AWT context, this is used by the
* {@code lwjgl-awt} library.
*/
private final GLData glData;
/** Used to notify the canvas status ({@code remove()/add()}). */
private final AtomicBoolean hasNativePeer = new AtomicBoolean(false);
/**
* It is used to create the initial context and all the resources that will
* be activated only once.
*/
private final AtomicBoolean initialize = new AtomicBoolean(false);
/** Notify the context reintegration, invalidating the current renderer. */
private final AtomicBoolean reinitcontext = new AtomicBoolean(false);
/** Notify if there is a change in canvas dimensions. */
private final AtomicBoolean needResize = new AtomicBoolean(false);
/** Notify if there are changes to the canvas scales. */
private final AtomicBoolean needRescale = new AtomicBoolean(false);
/**
* Flag that uses the context to check if it is initialized or not, this prevents
* it from being initialized multiple times and potentially breaking the JVM.
*/
private final AtomicBoolean contextFlag = new AtomicBoolean(false);
/** lock-object. */
private final Object lock = new Object();
/** Scale of the component in {@code x} */
private float xScale = 1;
/** Scale of the component in {@code y} */
private float yScale = 1;
/** Framebuffer width. */
private int framebufferWidth = 1;
/** Framebuffer height. */
private int framebufferHeight = 1;
/** AWT keyboard input manager. */
private AwtKeyInput keyInput;
/** AWT mouse input manager. */
private AwtMouseInput mouseInput;
/**
* Generate a new OpenGL context (<code>LwjglCanvas</code>) to integrate
* AWT/Swing with JME3 in your desktop applications.
*/
public LwjglCanvas() {
super(Type.Canvas);
glData = new GLData();
canvas = new LwjglAWTGLCanvas(glData);
canvas.setIgnoreRepaint(true);
// To determine the size of the framebuffer every time the user resizes
// the canvas (this works if the component has a parent)
canvas.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
synchronized (lock) {
updateSizes();
}
}
});
}
/**
* Check if the canvas is displayed, that is, if it has a parent that has set it up.
* <p>
* It is very important that this verification be done so that LWJGL3-AWT works correctly.
*
* @return returns <code>true</code> if the canvas is ready to draw; otherwise
* returns <code>false</code>
*/
public boolean checkVisibilityState() {
if (!hasNativePeer.get()) {
return false;
}
return canvas.isDisplayable() && canvas.isShowing();
}
/**
* Here the entire GL context is rendered and initialized.
*/
@Override
public void run() {
if (listener == null) {
throw new IllegalStateException(
"SystemListener is not set on context! Must set with JmeContext.setSystemListener()."
);
}
LOGGER.log(Level.FINE, "Using LWJGL {0}", Version.getVersion());
while (true) {
if (needResize.getAndSet(false)) {
settings.setResolution(framebufferWidth, framebufferHeight);
listener.reshape(framebufferWidth, framebufferHeight);
}
if (needRescale.getAndSet(false)) {
listener.rescale(xScale, yScale);
}
synchronized (lock) {
if (reinitcontext.getAndSet(false)) {
LOGGER.log(Level.FINE, "LWJGX: Destroying display ..");
try {
if (renderer != null) {
renderer.invalidateState();
renderer.cleanup();
}
canvas.releaseContext();
canvas.deleteContext();
canvas.doDisposeCanvas();
canvas.context = NULL;
} finally {
renderable.set(false);
lock.notifyAll();
}
}
}
if (checkVisibilityState()) {
// HACK: All components of the thread hosted in initInt() must be
// called after the context is created, but this is only valid
// if the canvas is validated by AWT, so it is created at "runtime".
if (!initialize.getAndSet(true)) {
if (!initInThread()) {
LOGGER.log(Level.SEVERE, "Display initialization failed. Cannot continue.");
break;
}
} else {
if (!canvas.hasContext()) {
LOGGER.log(Level.FINE, "AWT: Creating display ..");
createContext(settings);
reinitContext();
listener.gainFocus();
}
}
// HACK: In this thread, let OpenGL handle the heavy lifting,
// blocking the AWT/Swing EDT only to draw the corresponding
// buffer, thus preventing the user interface from freezing
// with demanding scenes.
runLoop();
// All this does is call swapBuffers().
// If the canvas is not active, there's no need to waste time
// doing that.
if (renderable.get() && canvas.hasContext() && canvas.isValid()) {
try {
if (allowSwapBuffers && autoFlush) {
// calls swap buffers | lock, etc.
try {
canvas.lock();
canvas.swapBuffers();
} finally {
canvas.unlock();
}
// Sync the display on some systems.
Toolkit.getDefaultToolkit().sync();
}
} catch (Throwable ex) {
listener.handleError("Error while swapping buffers", ex);
}
}
} else {
// HACK: If the GL context is not rendering, the thread will
// enter a waiting state, thus avoiding CPU overload.
try {
Thread.sleep(16);
} catch (InterruptedException ignore) { }
}
if (needClose.get()) {
break;
}
}
deinitInThread();
}
/**
* execute one iteration of the render loop in the OpenGL thread
*/
@Override
protected void runLoop() {
// If a restart is required, lets recreate the context.
if (needRestart.getAndSet(false)) {
restartContext();
}
if (!created.get()) {
throw new IllegalStateException();
}
listener.update();
// Subclasses just call GLObjectManager. Clean up objects here.
// It is safe ... for now.
if (renderer != null) {
renderer.postFrame();
}
if (autoFlush) {
if (frameRateLimit != getSettings().getFrameRate()) {
setFrameRateLimit(getSettings().getFrameRate());
}
} else if (frameRateLimit != 20) {
setFrameRateLimit(20);
}
Sync.sync(frameRateLimit);
}
/**
* (non-Javadoc)
* @see com.jme3.system.JmeContext#destroy(boolean)
* @param waitFor boolean
*/
@Override
public void destroy(boolean waitFor) {
super.destroy(waitFor);
this.contextFlag.set(false);
this.initialize.set(false);
}
/**
* (non-Javadoc)
* @see com.jme3.system.JmeContext#create(boolean)
* @param waitFor boolean
*/
@Override
public void create(boolean waitFor) {
if (this.contextFlag.get()) {
return;
}
// create context
super.create(waitFor);
this.contextFlag.set(true);
}
/**(non-Javadoc)
* @param createdVal boolean
*/
@Override
protected void waitFor(boolean createdVal) {
// AWT together with LWJGLX cannot handle waitFor() in the best way,
// since the context is created on the fly.
if (createdVal) {
LOGGER.log(Level.WARNING, "create(true) is not supported for AWT!");
}
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#destroyContext()
*/
@Override
protected void destroyContext() {
synchronized (lock) {
canvas.destroy();
}
super.destroyContext();
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#createContext(com.jme3.system.AppSettings)
* @param settings A {@link com.jme3.system.AppSettings} object
*/
@Override
protected void createContext(AppSettings settings) {
if (!settings.isX11PlatformPreferred() && isWayland()) {
LOGGER.log(Level.WARNING, "LWJGLX and AWT/Swing only work with X11, so XWayland will be used for GLX.");
}
// HACK: For LWJGLX to work in Wyland, it is necessary to use GLX via
// XWayland, so LWJGL must be forced to load GLX as a native API.
// This is because LWJGLX does not provide an EGL context.
if (isWayland()) {
Configuration.OPENGL_CONTEXT_API.set("native");
}
RENDER_CONFIGS.computeIfAbsent(settings.getRenderer(), (t) -> {
return (data) -> {
data.majorVersion = 2;
data.minorVersion = 0;
};
}).accept(glData);
if (settings.getBitsPerPixel() == 24) {
glData.redSize = 8;
glData.greenSize = 8;
glData.blueSize = 8;
} else if (settings.getBitsPerPixel() == 16) {
glData.redSize = 5;
glData.greenSize = 6;
glData.blueSize = 5;
}
// Enable vsync for LWJGL3-AWT
if (settings.isVSync()) {
glData.swapInterval = 1;
} else {
glData.swapInterval = 0;
}
glData.alphaSize = settings.getAlphaBits();
glData.sRGB = settings.isGammaCorrection(); // Not compatible with very old devices
glData.depthSize = settings.getDepthBits();
glData.stencilSize = settings.getStencilBits();
glData.samples = settings.getSamples();
glData.stereo = settings.useStereo3D();
glData.debug = settings.isGraphicsDebug();
glData.api = GLData.API.GL;
allowSwapBuffers = settings.isSwapBuffers();
canvas.createContext();
canvas.makeCurrent();
SwingUtilities.invokeLater(() -> {
canvas.validate();
});
// This will activate the "effective data" scrubber.
if (settings.getBoolean("GLDataEffectiveDebug")) {
LOGGER.log(Level.INFO, "[ DEBUGGER ] :Effective data to initialize the LWJGL3-AWT context\n{0}",
getPrintContextInitInfo(canvas.getGLDataEffective()));
}
// Create OpenCL
if (settings.isOpenCLSupport()) {
initOpenCL(canvas.context, (properties, context) -> {
switch (Platform.get()) {
case WINDOWS:
properties.put(KHRGLSharing.CL_GL_CONTEXT_KHR)
.put(context)
.put(KHRGLSharing.CL_WGL_HDC_KHR)
.put(WGL.wglGetCurrentDC());
break;
case FREEBSD:
case LINUX:
properties.put(KHRGLSharing.CL_GL_CONTEXT_KHR)
.put(context)
.put(KHRGLSharing.CL_GLX_DISPLAY_KHR)
.put(getX11Display(canvas.platformCanvas));
break;
case MACOSX:
properties.put(APPLEGLSharing.CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE)
.put(CGL.CGLGetShareGroup(CGL.CGLGetCurrentContext()));
break;
default:
break; // Unknown Platform, do nothing.
}
return null;
});
}
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#getKeyInput()
* @return KeyInput
*/
@Override
public KeyInput getKeyInput() {
if (keyInput == null) {
keyInput = new AwtKeyInput();
keyInput.setInputSource(canvas);
}
return keyInput;
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#getMouseInput()
* @return MouseInput
*/
@Override
public MouseInput getMouseInput() {
if (mouseInput == null) {
mouseInput = new AwtMouseInput();
mouseInput.setInputSource(canvas);
}
return mouseInput;
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#getJoyInput()
* @return JoyInput
*/
@Override
public JoyInput getJoyInput() {
if (joyInput == null) {
String mapper = settings.getJoysticksMapper();
if (AppSettings.JOYSTICKS_LEGACY_MAPPER.equals(mapper)
|| AppSettings.JOYSTICKS_XBOX_LEGACY_MAPPER.equals(mapper)) {
LOGGER.log(Level.WARNING, () -> "LWJGX does not support this configuration: " + mapper);
}
joyInput = new SdlJoystickInput(settings);
}
return joyInput;
}
/** (non-Javadoc) */
@Override public TouchInput getTouchInput() { return null; }
/** (non-Javadoc) */
@Override public void setTitle(String title) { }
/** (non-Javadoc) */
@Override protected void showWindow() { }
/** (non-Javadoc) */
@Override protected void setWindowIcon(final AppSettings settings) { }
/**(non-Javadoc) */
@Override public Vector2f getWindowContentScale(Vector2f store) {
return store == null ? new Vector2f() : store;
}
/**
* {@inheritDoc }
*/
@Override
protected void updateSizes() {
synchronized (lock) {
GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
if (gc == null) {
return;
}
AffineTransform at = gc.getDefaultTransform();
float sx = (float) at.getScaleX(),
sy = (float) at.getScaleY();
int fw = (int) (canvas.getWidth() * sx);
int fh = (int) (canvas.getHeight() * sy);
if (fw != framebufferWidth || fh != framebufferHeight) {
framebufferWidth = Math.max(fw, 1);
framebufferHeight = Math.max(fh, 1);
needResize.set(true);
}
if (xScale != sx || yScale != sy) {
xScale = sx;
yScale = sy;
needRescale.set(true);
}
}
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglContext#printContextInitInfo()
*/
@Override
protected void printContextInitInfo() {
super.printContextInitInfo();
LOGGER.log(Level.INFO, "Initializing LWJGL3-AWT with jMonkeyEngine\n{0}", getPrintContextInitInfo(glData));
}
/**
* Returns a string with the information obtained from <code>GLData</code>
* so that it can be displayed.
*
* @param glData context information
* @return String
*/
protected String getPrintContextInitInfo(GLData glData) {
StringBuilder sb = new StringBuilder();
sb.append(" * Double Buffer: ").append(glData.doubleBuffer);
sb.append('\n')
.append(" * Stereo: ").append(glData.stereo);
sb.append('\n')
.append(" * Red Size: ").append(glData.redSize);
sb.append('\n')
.append(" * Green Size: ").append(glData.greenSize);
sb.append('\n')
.append(" * Blue Size: ").append(glData.blueSize);
sb.append('\n')
.append(" * Alpha Size: ").append(glData.alphaSize);
sb.append('\n')
.append(" * Depth Size: ").append(glData.depthSize);
sb.append('\n')
.append(" * Stencil Size: ").append(glData.stencilSize);
sb.append('\n')
.append(" * Accum Red Size: ").append(glData.accumRedSize);
sb.append('\n')
.append(" * Accum Green Size: ").append(glData.accumGreenSize);
sb.append('\n')
.append(" * Accum Blue Size: ").append(glData.accumBlueSize);
sb.append('\n')
.append(" * Accum Alpha Size: ").append(glData.accumAlphaSize);
sb.append('\n')
.append(" * Sample Buffers: ").append(glData.sampleBuffers);
sb.append('\n')
.append(" * Share Context: ").append(glData.shareContext);
sb.append('\n')
.append(" * Major Version: ").append(glData.majorVersion);
sb.append('\n')
.append(" * Minor Version: ").append(glData.minorVersion);
sb.append('\n')
.append(" * Forward Compatible: ").append(glData.forwardCompatible);
sb.append('\n')
.append(" * Profile: ").append(glData.profile);
sb.append('\n')
.append(" * API: ").append(glData.api);
sb.append('\n')
.append(" * Debug: ").append(glData.debug);
sb.append('\n')
.append(" * Swap Interval: ").append(glData.swapInterval);
sb.append('\n')
.append(" * SRGB (Gamma Correction): ").append(glData.sRGB);
sb.append('\n')
.append(" * Pixel Format Float: ").append(glData.pixelFormatFloat);
sb.append('\n')
.append(" * Context Release Behavior: ").append(glData.contextReleaseBehavior);
sb.append('\n')
.append(" * Color Samples NV: ").append(glData.colorSamplesNV);
sb.append('\n')
.append(" * Swap Group NV: ").append(glData.swapGroupNV);
sb.append('\n')
.append(" * Swap Barrier NV: ").append(glData.swapBarrierNV);
sb.append('\n')
.append(" * Robustness: ").append(glData.robustness);
sb.append('\n')
.append(" * Lose Context On Reset: ").append(glData.loseContextOnReset);
sb.append('\n')
.append(" * Context Reset Isolation: ").append(glData.contextResetIsolation);
return String.valueOf(sb);
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#getFramebufferHeight()
* @return int
*/
@Override
public int getFramebufferHeight() {
return this.framebufferHeight;
}
/**
* (non-Javadoc)
* @see com.jme3.system.lwjgl.LwjglWindow#getFramebufferWidth()
* @return int
*/
@Override
public int getFramebufferWidth() {
return this.framebufferWidth;
}
/**
* {@inheritDoc }
*/
@Override
public long getWindowHandle() {
return canvas.context;
}
/** (non-Javadoc) */
@Override
public int getWindowXPosition() {
Component component = SwingUtilities.getRoot(canvas);
if (component == null) {
return 0;
}
return component.getX();
}
/** (non-Javadoc) */
@Override
public int getWindowYPosition() {
Component component = SwingUtilities.getRoot(canvas);
if (component == null) {
return 0;
}
return component.getY();
}
/**
* {@inheritDoc }
*/
@Override
public Displays getDisplays() {
Displays displays = new Displays();
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
if (environment == null) {
return displays;
}