-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathPSurfaceJOGL.java
1368 lines (1131 loc) · 44.7 KB
/
PSurfaceJOGL.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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-23 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.opengl;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import com.jogamp.common.util.IOUtil;
import com.jogamp.common.util.IOUtil.ClassResources;
import com.jogamp.nativewindow.NativeSurface;
import com.jogamp.nativewindow.ScalableSurface;
import com.jogamp.nativewindow.util.Dimension;
import com.jogamp.nativewindow.util.PixelFormat;
import com.jogamp.nativewindow.util.PixelRectangle;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.GLDrawableFactory;
import com.jogamp.nativewindow.MutableGraphicsConfiguration;
import com.jogamp.nativewindow.WindowClosingProtocol;
import com.jogamp.newt.Display;
import com.jogamp.newt.Display.PointerIcon;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.Screen;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PSurface;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
import processing.awt.PImageAWT;
// have this removed by 4.0 final
import processing.awt.ShimAWT;
public class PSurfaceJOGL implements PSurface {
/** Selected GL profile */
static public GLProfile profile;
public PJOGL pgl;
protected GLWindow window;
protected FPSAnimator animator;
protected Rectangle screenRect;
private Thread drawExceptionHandler;
protected PApplet sketch;
protected PGraphics graphics;
protected int sketchWidthRequested;
protected int sketchHeightRequested;
protected int sketchWidth;
protected int sketchHeight;
protected Display display;
protected Screen screen;
protected Rectangle displayRect;
protected Throwable drawException;
private final Object drawExceptionMutex = new Object();
protected NewtCanvasAWT canvas;
protected static GLAutoDrawable sharedDrawable;
protected static ArrayList<FPSAnimator> animators = new ArrayList<>();
private final static Object sharedSyncMutex = new Object();
private Object syncMutex;
protected int windowScaleFactor;
protected float[] currentPixelScale = { 0, 0 };
public PSurfaceJOGL(PGraphics graphics) {
this.graphics = graphics;
this.pgl = (PJOGL) ((PGraphicsOpenGL) graphics).pgl;
}
public void initOffscreen(PApplet sketch) {
this.sketch = sketch;
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
if (window != null) {
canvas = new NewtCanvasAWT(window);
canvas.setBounds(0, 0, window.getWidth(), window.getHeight());
canvas.setFocusable(true);
}
}
public void initFrame(PApplet sketch) {
this.sketch = sketch;
initIcons();
// For 4.0.2, swapped the order to do initGL() before initDisplay()
// https://github.com/processing/processing4/issues/544
initGL();
initDisplay();
initWindow();
initListeners();
initAnimator();
}
public Object getNative() {
return window;
}
protected void initDisplay() {
display = NewtFactory.createDisplay(null);
display.addReference();
screen = NewtFactory.createScreen(display, 0);
screen.addReference();
int displayNum = sketch.sketchDisplay();
displayRect = getDisplayBounds(displayNum);
}
// TODO This code is mostly copied from code found in PSurfaceAWT.
// It should probably be merged to avoid divergence. [fry 211122]
static protected Rectangle getDisplayBounds(int displayNum) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] awtDevices = ge.getScreenDevices();
GraphicsDevice awtDisplayDevice = null;
if (displayNum > 0) { // if -1, use the default device
if (displayNum <= awtDevices.length) {
awtDisplayDevice = awtDevices[displayNum-1];
} else {
System.err.format("Display %d does not exist, " +
"using the default display instead.%n", displayNum);
for (int i = 0; i < awtDevices.length; i++) {
System.err.format("Display %d is %s%n", i+1, awtDevices[i]);
}
}
// } else if (0 < awtDevices.length) {
// TODO this seems like a bad idea: in lots of situations [0] will *not*
// be the default device. Not sure why this was added instead of
// just using getDefaultScreenDevice() below. [fry 211122]
// TODO Removing for 4.2, clean this code on next visit. [fry 230218]
// awtDisplayDevice = awtDevices[0];
}
if (awtDisplayDevice == null) {
awtDisplayDevice = ge.getDefaultScreenDevice();
}
//return awtDisplayDevice.getDefaultConfiguration().getBounds();
Rectangle bounds = awtDisplayDevice.getDefaultConfiguration().getBounds();
float uiScale = Float.parseFloat(System.getProperty("sun.java2d.uiScale", "1.0"));
return new Rectangle((int) (uiScale * bounds.getX()),
(int) (uiScale * bounds.getY()),
(int) (uiScale * bounds.getWidth()),
(int) (uiScale * bounds.getHeight()));
}
protected void initGL() {
if (profile == null) {
if (PJOGL.profile == 1) {
try {
profile = GLProfile.getGL2ES1();
} catch (GLException ex) {
profile = GLProfile.getMaxFixedFunc(true);
}
} else if (PJOGL.profile == 2) {
try {
profile = GLProfile.getGL2ES2();
// workaround for https://jogamp.org/bugzilla/show_bug.cgi?id=1347
if (!profile.isHardwareRasterizer()) {
GLProfile hardware = GLProfile.getMaxProgrammable(true);
if (hardware.isGL2ES2()) {
profile = hardware;
}
}
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
} else if (PJOGL.profile == 3) {
try {
profile = GLProfile.getGL2GL3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL3()) {
PGraphics.showWarning("Requested profile GL3 but is not available, got: " + profile);
}
} else if (PJOGL.profile == 4) {
try {
profile = GLProfile.getGL4ES3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL4()) {
PGraphics.showWarning("Requested profile GL4 but is not available, got: " + profile);
}
} else throw new RuntimeException(PGL.UNSUPPORTED_GLPROF_ERROR);
}
// Setting up the desired capabilities;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
// caps.setPBuffer(false);
// caps.setFBO(false);
// pgl.reqNumSamples = PGL.smoothToSamples(graphics.smooth);
caps.setSampleBuffers(true);
caps.setNumSamples(PGL.smoothToSamples(graphics.smooth));
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
pgl.setCaps(caps);
if (sharedDrawable == null) {
// Create a shared drawable to enable context sharing across multiple GL windows
// https://jogamp.org/deployment/jogamp-next/javadoc/jogl/javadoc/com/jogamp/opengl/GLSharedContextSetter.html
sharedDrawable = GLDrawableFactory.getFactory(profile).createDummyAutoDrawable(null, true, caps, null);
sharedDrawable.display();
}
}
// To properly deal with synchronization when context sharing across multiple drawables (windows), we need a
// synchronization mutex object to ensure that rendering of each frame completes in their respective animator thread:
// https://jogamp.org/deployment/jogamp-next/javadoc/jogl/javadoc/com/jogamp/opengl/GLSharedContextSetter.html#synchronization
private Object getSyncMutex(GLAutoDrawable drawable) {
pgl.getGL(drawable);
if (pgl.needSharedObjectSync()) {
syncMutex = sharedSyncMutex;
} else {
if (syncMutex == null) {
syncMutex = new Object();
}
}
return syncMutex;
}
protected void initWindow() {
window = GLWindow.create(screen, pgl.getCaps());
// Make sure that we pass the window close through to exit(), otherwise
// we're likely to have OpenGL try to shut down halfway through rendering
// a frame. Particularly problematic for complex/slow apps.
// https://github.com/processing/processing/issues/4690
window.setDefaultCloseOperation(WindowClosingProtocol.WindowClosingMode.DO_NOTHING_ON_CLOSE);
// macOS pixel density is handled transparently by the OS
windowScaleFactor =
(PApplet.platform == PConstants.MACOS) ? 1 : sketch.pixelDensity;
boolean spanDisplays = sketch.sketchDisplay() == PConstants.SPAN;
screenRect = spanDisplays ?
// TODO probably need to apply this to the spanning version [fry 230218]
new Rectangle(screen.getX(), screen.getY(),
screen.getWidth(), screen.getHeight()) :
new Rectangle((int) displayRect.getX(),
(int) displayRect.getY(),
(int) displayRect.getWidth(),
(int) displayRect.getHeight());
// new Rectangle((int) (uiScale * displayRect.getX()),
// (int) (uiScale * displayRect.getY()),
// (int) (uiScale * displayRect.getWidth()),
// (int) (uiScale * displayRect.getHeight()));
// Set the displayWidth/Height variables inside PApplet, so that they're
// usable and can even be returned by the sketchWidth()/Height() methods.
sketch.displayWidth = screenRect.width;
sketch.displayHeight = screenRect.height;
// Sometimes the window manager or OS will resize the window.
// Keep track of the requested width/height to notify the user.
sketchWidthRequested = sketch.sketchWidth();
sketchHeightRequested = sketch.sketchHeight();
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
boolean fullScreen = sketch.sketchFullScreen();
// Before 3.x, we would set the window to full screen when the requested
// width/height was the size of the screen. But not everyone *wants* that
// to be full screen (they might want to drag the window, or who knows),
// so that code was removed because fullScreen() is easy to use instead.
// https://github.com/processing/processing/issues/3545
if (fullScreen || spanDisplays) {
// sketchWidth = (int) (uiScale * screenRect.width / windowScaleFactor);
// sketchHeight = (int) (uiScale * screenRect.height / windowScaleFactor);
sketchWidth = screenRect.width / windowScaleFactor;
sketchHeight = screenRect.height / windowScaleFactor;
}
sketch.setSize(sketchWidth, sketchHeight);
// https://jogamp.org/deployment/jogamp-next/javadoc/jogl/javadoc/com/jogamp/newt/opengl/GLWindow.html#setSurfaceScale(float%5B%5D)
float surfaceScale =
(graphics.is2X() && PApplet.platform == PConstants.MACOS) ?
ScalableSurface.AUTOMAX_PIXELSCALE :
ScalableSurface.IDENTITY_PIXELSCALE;
window.setSurfaceScale(new float[] { surfaceScale, surfaceScale });
window.setSize(sketchWidth * windowScaleFactor, sketchHeight * windowScaleFactor);
window.setResizable(false);
setSize(sketchWidth, sketchHeight);
if (fullScreen) {
PApplet.hideMenuBar();
if (spanDisplays) {
window.setFullscreen(screen.getMonitorDevices());
} else {
window.setUndecorated(true);
window.setTopLevelPosition((int) displayRect.getX(), (int) displayRect.getY());
window.setTopLevelSize((int) displayRect.getWidth(), (int) displayRect.getHeight());
}
}
window.setSharedAutoDrawable(sharedDrawable);
}
protected void initListeners() {
window.addMouseListener(new NEWTMouseListener());
window.addKeyListener(new NEWTKeyListener());
window.addWindowListener(new NEWTWindowListener());
window.addGLEventListener(new DrawListener());
}
protected void initAnimator() {
if (PApplet.platform == PConstants.WINDOWS) {
// Force Windows to keep timer resolution high by creating a dummy
// thread that sleeps for a time that is not a multiple of 10 ms.
// See section titled "Clocks and Timers on Windows" in this post:
// https://web.archive.org/web/20160308031939/https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
Thread highResTimerThread = new Thread(() -> {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ignore) { }
}, "HighResTimerThread");
highResTimerThread.setDaemon(true);
highResTimerThread.start();
}
animator = new FPSAnimator(window, 60);
animators.add(animator);
drawException = null;
animator.setUncaughtExceptionHandler((animator, drawable, cause) -> {
synchronized (drawExceptionMutex) {
drawException = cause;
drawExceptionMutex.notify();
}
});
drawExceptionHandler = new Thread(() -> {
synchronized (drawExceptionMutex) {
try {
while (drawException == null) {
drawExceptionMutex.wait();
}
Throwable cause = drawException.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof UnsatisfiedLinkError) {
throw new UnsatisfiedLinkError(cause.getMessage());
} else if (cause == null) {
throw new RuntimeException(drawException.getMessage());
} else {
throw new RuntimeException(cause);
}
} catch (InterruptedException ignored) { }
}
});
drawExceptionHandler.start();
}
@Override
public void setTitle(final String title) {
display.getEDTUtil().invoke(false, () -> window.setTitle(title));
}
@Override
public void setVisible(final boolean visible) {
display.getEDTUtil().invoke(false, () -> window.setVisible(visible));
}
@Override
public void setResizable(final boolean resizable) {
display.getEDTUtil().invoke(false, () -> window.setResizable(resizable));
}
public void setIcon(PImage icon) {
PGraphics.showWarning("Window icons for OpenGL sketches can only be set in settings()\n" +
"using PJOGL.setIcon(filename).");
}
@Override
public void setAlwaysOnTop(final boolean always) {
display.getEDTUtil().invoke(false, () -> window.setAlwaysOnTop(always));
}
protected void initIcons() {
IOUtil.ClassResources res;
if (PJOGL.icons == null || PJOGL.icons.length == 0) {
// Default Processing icons
final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
String[] iconImages = new String[sizes.length];
for (int i = 0; i < sizes.length; i++) {
iconImages[i] = "/icon/icon-" + sizes[i] + ".png";
}
res = new ClassResources(iconImages,
PApplet.class.getClassLoader(),
PApplet.class);
} else {
// Loading custom icons from user-provided files.
String[] iconImages = new String[PJOGL.icons.length];
for (int i = 0; i < PJOGL.icons.length; i++) {
iconImages[i] = resourceFilename(PJOGL.icons[i]);
}
res = new ClassResources(iconImages,
sketch.getClass().getClassLoader(),
sketch.getClass());
}
NewtFactory.setWindowIcons(res);
}
private String resourceFilename(String filename) {
// The code below comes from PApplet.createInputRaw() with a few adaptations
InputStream stream;
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(sketch.dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = sketch.sketchFile(filename);
}
if (file.exists() && !file.isDirectory()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException ignored) { }
}
stream = new FileInputStream(file);
stream.close();
return file.getCanonicalPath();
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException | SecurityException ignored) { }
ClassLoader cl = sketch.getClass().getClassLoader();
try {
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// https://download.processing.org/bugzilla/359.html
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return "data/" + filename;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// https://download.processing.org/bugzilla/389.html
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return filename;
}
}
} catch (IOException ignored) { }
try {
// attempt to load from a local file
try {
String path = sketch.dataPath(filename);
stream = new FileInputStream(path);
stream.close();
return path;
} catch (IOException ignored) { }
try {
String path = sketch.sketchPath(filename);
stream = new FileInputStream(path);
stream.close();
return path;
} catch (Exception ignored) { }
try {
stream = new FileInputStream(filename);
stream.close();
return filename;
} catch (IOException ignored) { }
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return "";
}
@Override
public void placeWindow(int[] location, int[] editorLocation) {
if (sketch.sketchFullScreen()) {
return;
}
int x = window.getX() - window.getInsets().getLeftWidth();
int y = window.getY() - window.getInsets().getTopHeight();
int w = window.getWidth() + window.getInsets().getTotalWidth();
int h = window.getHeight() + window.getInsets().getTotalHeight();
if (location != null) {
window.setTopLevelPosition(location[0], location[1]);
} else if (editorLocation != null) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - w > 10) {
// if it fits to the left of the window
window.setTopLevelPosition(locationX - w, locationY);
} else { // doesn't fit
locationX = (sketch.displayWidth - w) / 2;
locationY = (sketch.displayHeight - h) / 2;
window.setTopLevelPosition(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
window.setTopLevelPosition(screenRect.x + (screenRect.width - sketchWidth) / 2,
screenRect.y + (screenRect.height - sketchHeight) / 2);
}
Point frameLoc = new Point(x, y);
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. https://download.processing.org/bugzilla/1508.html
window.setTopLevelPosition(frameLoc.x, 30);
}
}
public void placePresent(int stopColor) {
float scale = getPixelScale();
pgl.initPresentMode(0.5f * (screenRect.width/scale - sketchWidth),
0.5f * (screenRect.height/scale - sketchHeight), stopColor);
PApplet.hideMenuBar();
window.setUndecorated(true);
window.setTopLevelPosition((int) displayRect.getX(), (int) displayRect.getY());
window.setTopLevelSize((int) displayRect.getWidth(), (int) displayRect.getHeight());
}
/*
public void setupExternalMessages() {
external = true;
}
*/
public void startThread() {
if (animator != null) {
animator.start();
}
}
public void pauseThread() {
if (animator != null) {
animator.pause();
}
}
public void resumeThread() {
if (animator != null) {
animator.resume();
}
}
public boolean stopThread() {
if (drawExceptionHandler != null) {
drawExceptionHandler.interrupt();
drawExceptionHandler = null;
}
if (animator != null) {
// Stops all other animators to avoid exceptions when closing a window in a multiple window configuration
for (FPSAnimator ani: animators) {
if (ani != animator) ani.stop();
}
return animator.stop();
} else {
return false;
}
}
public boolean isStopped() {
if (animator != null) {
return !animator.isAnimating();
} else {
return true;
}
}
public void setLocation(final int x, final int y) {
display.getEDTUtil().invoke(false, () -> window.setTopLevelPosition(x, y));
}
public void setSize(int wide, int high) {
if (pgl.presentMode()) return;
// When the surface is set to resizable via surface.setResizable(true),
// a crash may occur if the user sets the window to size zero.
// https://github.com/processing/processing/issues/5052
if (high <= 0) {
high = 1;
}
if (wide <= 0) {
wide = 1;
}
boolean changed = sketch.width != wide || sketch.height != high;
sketchWidth = wide;
sketchHeight = high;
sketch.setSize(wide, high);
graphics.setSize(wide, high);
if (changed) {
window.setSize(wide * windowScaleFactor, high * windowScaleFactor);
}
}
public float getPixelScale() {
if (graphics.pixelDensity == 1) {
return 1;
}
if (PApplet.platform == PConstants.MACOS) {
return getCurrentPixelScale();
}
return 2;
}
protected float getCurrentPixelScale() {
// Even if the graphics are retina, the user might have moved the window
// into a non-retina monitor, so we need to check
return window.getCurrentSurfaceScale(currentPixelScale)[0];
}
public Component getComponent() {
return canvas;
}
public void setSmooth(int level) {
pgl.reqNumSamples = level;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
caps.setSampleBuffers(true);
caps.setNumSamples(pgl.reqNumSamples);
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
NativeSurface target = window.getNativeSurface();
MutableGraphicsConfiguration config = (MutableGraphicsConfiguration) target.getGraphicsConfiguration();
config.setChosenCapabilities(caps);
}
public void setFrameRate(float fps) {
if (fps < 1) {
PGraphics.showWarning(
"The OpenGL renderer cannot have a frame rate lower than 1.\n" +
"Your sketch will run at 1 frame per second.");
fps = 1;
} else if (fps > 1000) {
PGraphics.showWarning(
"The OpenGL renderer cannot have a frame rate higher than 1000.\n" +
"Your sketch will run at 1000 frames per second.");
fps = 1000;
}
if (animator != null) {
animator.stop();
animator.setFPS((int)fps);
pgl.setFps(fps);
animator.start();
}
}
public void requestFocus() {
display.getEDTUtil().invoke(false, () -> window.requestFocus());
}
public class DrawListener implements GLEventListener {
private boolean isInit = false;
public void display(GLAutoDrawable drawable) {
if (!isInit) return;
if (display.getEDTUtil().isCurrentThreadEDT()) {
// For some unknown reason, a few frames of the animator run on
// the EDT. For those, we just skip this draw call to avoid badness.
// See below for explanation of this two line hack.
pgl.beginRender();
pgl.endRender(sketch.sketchWindowColor());
return;
}
if (sketch.frameCount == 0) {
if (sketchWidth != sketchWidthRequested || sketchHeight != sketchHeightRequested) {
if (!sketch.sketchFullScreen()) {
// don't show the message when using fullScreen()
PGraphics.showWarning(
"The sketch has been resized from " +
"%dx%d to %dx%d by the operating system.%n" +
"This happened outside Processing, " +
"and may be a limitation of the OS or window manager.",
sketchWidthRequested, sketchHeightRequested, sketchWidth, sketchHeight);
}
}
requestFocus();
}
if (!sketch.finished) {
synchronized (getSyncMutex(drawable)) {
pgl.getGL(drawable);
int prevFrameCount = sketch.frameCount;
sketch.handleDraw();
if (prevFrameCount == sketch.frameCount || sketch.finished) {
// This hack allows the FBO layer to be swapped normally even if
// the sketch is no looping or finished because it does not call draw(),
// otherwise background artifacts may occur (depending on the hardware/drivers).
pgl.beginRender();
pgl.endRender(sketch.sketchWindowColor());
}
PGraphicsOpenGL.completeFinishedPixelTransfers();
}
}
if (sketch.exitCalled()) {
PGraphicsOpenGL.completeAllPixelTransfers();
sketch.dispose(); // calls stopThread(), which stops the animator.
sketch.exitActual();
}
}
public void dispose(GLAutoDrawable drawable) {
// do nothing, sketch.dispose() will be called with exitCalled()
}
public void init(GLAutoDrawable drawable) {
if (display.getEDTUtil().isCurrentThreadEDT()) {
return;
}
synchronized (getSyncMutex(drawable)) {
pgl.init(drawable);
sketch.start();
int c = graphics.backgroundColor;
pgl.clearColor(((c >> 16) & 0xff) / 255f,
((c >> 8) & 0xff) / 255f,
(c & 0xff) / 255f,
((c >> 24) & 0xff) / 255f);
pgl.clear(PGL.COLOR_BUFFER_BIT);
isInit = true;
}
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
if (!isInit) return;
if (display.getEDTUtil().isCurrentThreadEDT()) {
return;
}
synchronized (getSyncMutex(drawable)) {
pgl.resetFBOLayer();
float scale = PApplet.platform == PConstants.MACOS ?
getCurrentPixelScale() : getPixelScale();
setSize((int) (w / scale), (int) (h / scale));
}
}
}
protected class NEWTWindowListener implements com.jogamp.newt.event.WindowListener {
public NEWTWindowListener() {
super();
}
@Override
public void windowGainedFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = true;
sketch.focusGained();
}
@Override
public void windowLostFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = false;
sketch.focusLost();
}
@Override
public void windowDestroyNotify(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowDestroyed(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowMoved(com.jogamp.newt.event.WindowEvent arg0) {
/*
if (external) {
sketch.frameMoved(window.getX(), window.getY());
}
*/
sketch.postWindowMoved(window.getX(), window.getY());
}
@Override
public void windowRepaint(com.jogamp.newt.event.WindowUpdateEvent arg0) {
}
@Override
public void windowResized(com.jogamp.newt.event.WindowEvent arg0) {
sketch.postWindowResized(window.getWidth(), window.getHeight());
}
}
// NEWT mouse listener
protected class NEWTMouseListener extends com.jogamp.newt.event.MouseAdapter {
public NEWTMouseListener() {
super();
}
@Override
public void mousePressed(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.PRESS);
}
@Override
public void mouseReleased(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.RELEASE);
}
@Override
public void mouseClicked(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.CLICK);
}
@Override
public void mouseDragged(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.DRAG);
}
@Override
public void mouseMoved(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.MOVE);
}
@Override
public void mouseWheelMoved(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.WHEEL);
}
@Override
public void mouseEntered(com.jogamp.newt.event.MouseEvent e) {
// System.out.println("enter");
nativeMouseEvent(e, MouseEvent.ENTER);
}
@Override
public void mouseExited(com.jogamp.newt.event.MouseEvent e) {
// System.out.println("exit");
nativeMouseEvent(e, MouseEvent.EXIT);
}
}
// NEWT key listener
protected class NEWTKeyListener extends com.jogamp.newt.event.KeyAdapter {
public NEWTKeyListener() {
super();
}
@Override
public void keyPressed(com.jogamp.newt.event.KeyEvent e) {
nativeKeyEvent(e, KeyEvent.PRESS);
}
@Override
public void keyReleased(com.jogamp.newt.event.KeyEvent e) {
nativeKeyEvent(e, KeyEvent.RELEASE);