JOGL v2.6.0-rc-20250706
JOGL, High-Performance Graphics Binding for Java™ (public API).
GearsES2.java
Go to the documentation of this file.
1/**
2 * Copyright (C) 2011 JogAmp Community. All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 */
21package com.jogamp.opengl.test.junit.jogl.demos.es2;
22
23import com.jogamp.common.nio.Buffers;
24import com.jogamp.math.Matrix4f;
25import com.jogamp.math.Quaternion;
26import com.jogamp.math.Vec3f;
27import com.jogamp.math.util.PMVMatrix4f;
28import com.jogamp.newt.Window;
29import com.jogamp.newt.event.GestureHandler;
30import com.jogamp.newt.event.KeyAdapter;
31import com.jogamp.newt.event.KeyEvent;
32import com.jogamp.newt.event.KeyListener;
33import com.jogamp.newt.event.MouseEvent;
34import com.jogamp.newt.event.MouseListener;
35import com.jogamp.newt.event.PinchToZoomGesture;
36import com.jogamp.newt.event.GestureHandler.GestureEvent;
37import com.jogamp.opengl.GLRendererQuirks;
38import com.jogamp.opengl.JoglVersion;
39import com.jogamp.opengl.test.junit.jogl.demos.GearsObject;
40import com.jogamp.opengl.util.CustomGLEventListener;
41import com.jogamp.opengl.util.PMVMatrix;
42import com.jogamp.opengl.util.TileRendererBase;
43import com.jogamp.opengl.util.glsl.ShaderCode;
44import com.jogamp.opengl.util.glsl.ShaderProgram;
45import com.jogamp.opengl.util.glsl.ShaderState;
46import com.jogamp.opengl.util.stereo.EyeParameter;
47import com.jogamp.opengl.util.stereo.ViewerPose;
48import com.jogamp.opengl.util.stereo.StereoGLEventListener;
49
50import java.nio.FloatBuffer;
51
52import com.jogamp.nativewindow.NativeWindow;
53import com.jogamp.opengl.GL;
54import com.jogamp.opengl.GL2ES2;
55import com.jogamp.opengl.GLAnimatorControl;
56import com.jogamp.opengl.GLAutoDrawable;
57import com.jogamp.opengl.GLProfile;
58import com.jogamp.opengl.GLUniformData;
59import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
60
61/**
62 * GearsES2.java <BR>
63 * @author Brian Paul (converted to Java by Ron Cemer and Sven Gothel) <P>
64 */
65public class GearsES2 implements StereoGLEventListener, TileRendererBase.TileRendererListener {
66 private final FloatBuffer lightPos = Buffers.newDirectFloatBuffer( new float[] { 5.0f, 5.0f, 10.0f } );
67
68 private ShaderState st = null;
69 private PMVMatrix pmvMatrix = null;
70 private GLUniformData pmvMatrixUniform = null;
71 private GLUniformData colorU = null;
72 private float view_rotx = 20.0f, view_roty = 30.0f;
73 private boolean flipVerticalInGLOrientation = false;
74 private final boolean customRendering = false;
75
76 private final float view_rotz = 0.0f;
77 private float panX = 0.0f, panY = 0.0f, panZ=0.0f;
78 private volatile GearsObjectES2 gear1=null, gear2=null, gear3=null;
79 private GearsES2 sharedGears = null;
80 private Object syncObjects = null;
81 private boolean useMappedBuffers = false;
82 private boolean validateBuffers = false;
83 private volatile boolean usesSharedGears = false;
84 private FloatBuffer gear1Color=GearsObject.red, gear2Color=GearsObject.green, gear3Color=GearsObject.blue;
85 private float angle = 0.0f;
86 private int swapInterval = 0;
87 // private MouseListener gearsMouse = new TraceMouseAdapter(new GearsMouseAdapter());
88 public MouseListener gearsMouse = new GearsMouseAdapter();
89 public KeyListener gearsKeys = new GearsKeyAdapter();
90 private TileRendererBase tileRendererInUse = null;
91 private boolean doRotateBeforePrinting;
92
93 private boolean doRotate = true;
94 private boolean ignoreFocus = false;
95 private float[] clearColor = null;
96 private boolean clearBuffers = true;
97 private boolean verbose = true;
98 private volatile boolean isInit = false;
99
100 private PinchToZoomGesture pinchToZoomGesture = null;
101
102
103 public GearsES2(final int swapInterval) {
104 this.swapInterval = swapInterval;
105 }
106
107 public GearsES2() {
108 this.swapInterval = 1;
109 }
110
111 @Override
113 tileRendererInUse = tr;
114 doRotateBeforePrinting = doRotate;
115 setDoRotation(false);
116 }
117 @Override
119 tileRendererInUse = null;
120 setDoRotation(doRotateBeforePrinting);
121 }
122 @Override
123 public void startTileRendering(final TileRendererBase tr) {
124 System.err.println("GearsES2.startTileRendering: "+sid()+""+tr);
125 }
126 @Override
127 public void endTileRendering(final TileRendererBase tr) {
128 System.err.println("GearsES2.endTileRendering: "+sid()+""+tr);
129 }
130
131 public void setIgnoreFocus(final boolean v) { ignoreFocus = v; }
132 public void setDoRotation(final boolean rotate) { this.doRotate = rotate; }
133 public void setClearBuffers(final boolean v) { clearBuffers = v; }
134 public GearsES2 setVerbose(final boolean v) { verbose = v; return this; }
135 public void setFlipVerticalInGLOrientation(final boolean v) { flipVerticalInGLOrientation=v; }
136
137 /** float[4] */
138 public void setClearColor(final float[] clearColor) {
139 this.clearColor = clearColor;
140 }
141
142 public void setGearsColors(final FloatBuffer gear1Color, final FloatBuffer gear2Color, final FloatBuffer gear3Color) {
143 this.gear1Color = gear1Color;
144 this.gear2Color = gear2Color;
145 this.gear3Color = gear3Color;
146 }
147
148 public void setSharedGears(final GearsES2 shared) {
149 sharedGears = shared;
150 }
151
152 public void setSyncObjects(final Object sync) {
153 syncObjects = sync;
154 }
155
156 /**
157 * @return gear1
158 */
159 public GearsObjectES2 getGear1() { return gear1; }
160
161 /**
162 * @return gear2
163 */
164 public GearsObjectES2 getGear2() { return gear2; }
165
166 /**
167 * @return gear3
168 */
169 public GearsObjectES2 getGear3() { return gear3; }
170
171 public boolean usesSharedGears() { return usesSharedGears; }
172
173 public void setUseMappedBuffers(final boolean v) { useMappedBuffers = v; }
174 public void setValidateBuffers(final boolean v) { validateBuffers = v; }
175
177 return pmvMatrix;
178 }
179
180 private static final int TIME_OUT = 2000; // 2s
181 private static final int POLL_DIVIDER = 20; // TO/20
182 private static final int TIME_SLICE = TIME_OUT / POLL_DIVIDER ;
183
184 /**
185 * @return True if this GLEventListener became initialized within TIME_OUT 2s
186 */
187 public boolean waitForInit(final boolean initialized) throws InterruptedException {
188 int wait;
189 for (wait=0; wait<POLL_DIVIDER && initialized != isInit ; wait++) {
190 Thread.sleep(TIME_SLICE);
191 }
192 return wait<POLL_DIVIDER;
193 }
194
195 private final String sid() { return "0x"+Integer.toHexString(hashCode()); }
196
197 @Override
198 public void init(final GLAutoDrawable drawable) {
199 if(null != sharedGears && !sharedGears.isInit() ) {
200 if(verbose) {
201 System.err.println(Thread.currentThread()+" GearsES2.init.0 "+sid()+": pending shared Gears .. re-init later XXXXX");
202 }
203 drawable.setGLEventListenerInitState(this, false);
204 return;
205 }
206
207 final GL2ES2 gl = drawable.getGL().getGL2ES2();
208 if(verbose) {
209 System.err.println(Thread.currentThread()+" GearsES2.init.0 "+sid()+": tileRendererInUse "+tileRendererInUse+", "+this);
210 System.err.println("GearsES2 init "+sid()+" on "+Thread.currentThread());
211 System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities());
212 System.err.println("INIT GL IS: " + gl.getClass().getName());
213 System.err.println(JoglVersion.getGLStrings(gl, null, false).toString());
214 }
215 if( !gl.hasGLSL() ) {
216 System.err.println("No GLSL available, no rendering.");
217 return;
218 }
219
220 st = new ShaderState();
221 // st.setVerbose(true);
222 final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
223 "shader/bin", "gears", true);
224 final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
225 "shader/bin", "gears", true);
226 vp0.defaultShaderCustomization(gl, true, true);
227 fp0.defaultShaderCustomization(gl, true, true);
228 final ShaderProgram sp0 = new ShaderProgram();
229 sp0.add(gl, vp0, System.err);
230 sp0.add(gl, fp0, System.err);
231 st.attachShaderProgram(gl, sp0, true);
232 // Use debug pipeline
233 // drawable.setGL(new DebugGL(drawable.getGL()));
234
236 st.attachObject("pmvMatrix", pmvMatrix);
237 pmvMatrixUniform = new GLUniformData("pmvMatrix", 4, 4, pmvMatrix.getSyncPMvMviMvit()); // P, Mv, Mvi and Mvit
238 st.ownUniform(pmvMatrixUniform);
239 st.uniform(gl, pmvMatrixUniform);
240
241 final GLUniformData lightU = new GLUniformData("lightPos", 3, lightPos);
242 st.ownUniform(lightU);
243 st.uniform(gl, lightU);
244
245 colorU = new GLUniformData("color", 4, GearsObject.red);
246 st.ownUniform(colorU);
247 st.uniform(gl, colorU);
248
249 if( null != sharedGears ) {
250 gear1 = new GearsObjectES2(sharedGears.getGear1(), st, pmvMatrix, pmvMatrixUniform, colorU);
251 gear2 = new GearsObjectES2(sharedGears.getGear2(), st, pmvMatrix, pmvMatrixUniform, colorU);
252 gear3 = new GearsObjectES2(sharedGears.getGear3(), st, pmvMatrix, pmvMatrixUniform, colorU);
253 usesSharedGears = true;
254 if(verbose) {
255 System.err.println("gear1 "+sid()+" created w/ share: "+sharedGears.getGear1()+" -> "+gear1);
256 System.err.println("gear2 "+sid()+" created w/ share: "+sharedGears.getGear2()+" -> "+gear2);
257 System.err.println("gear3 "+sid()+" created w/ share: "+sharedGears.getGear3()+" -> "+gear3);
258 }
260 syncObjects = sharedGears;
261 if(verbose) {
262 System.err.println("Shared GearsES2: Synchronized Objects due to quirk "+GLRendererQuirks.toString(GLRendererQuirks.NeedSharedObjectSync));
263 }
264 } else if( null == syncObjects ) {
265 syncObjects = new Object();
266 if(verbose) {
267 System.err.println("Shared GearsES2: Unsynchronized Objects");
268 }
269 }
270 } else {
271 gear1 = new GearsObjectES2(gl, useMappedBuffers, st, gear1Color, 1.0f, 4.0f, 1.0f, 20, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
272 if(verbose) {
273 System.err.println("gear1 "+sid()+" created: "+gear1);
274 }
275
276 gear2 = new GearsObjectES2(gl, useMappedBuffers, st, gear2Color, 0.5f, 2.0f, 2.0f, 10, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
277 if(verbose) {
278 System.err.println("gear2 "+sid()+" created: "+gear2);
279 }
280
281 gear3 = new GearsObjectES2(gl, useMappedBuffers, st, gear3Color, 1.3f, 2.0f, 0.5f, 10, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
282 if(verbose) {
283 System.err.println("gear3 "+sid()+" created: "+gear2);
284 }
285 if( null == syncObjects ) {
286 syncObjects = new Object();
287 }
288 }
289
290 final Object upstreamWidget = drawable.getUpstreamWidget();
291 if (upstreamWidget instanceof Window) {
292 final Window window = (Window) upstreamWidget;
295 window.addGestureListener(pinchToZoomListener);
296 pinchToZoomGesture = new PinchToZoomGesture(drawable.getNativeSurface(), false);
297 window.addGestureHandler(pinchToZoomGesture);
298 } else if (GLProfile.isAWTAvailable() && upstreamWidget instanceof java.awt.Component) {
299 final java.awt.Component comp = (java.awt.Component) upstreamWidget;
300 new com.jogamp.newt.event.awt.AWTMouseAdapter(gearsMouse, drawable).addTo(comp);
301 new com.jogamp.newt.event.awt.AWTKeyAdapter(gearsKeys, drawable).addTo(comp);
302 }
303
304 st.useProgram(gl, false);
305
306 gl.glFinish(); // make sure .. for shared context (impacts OSX 10.9)
307
308 isInit = true;
309 if(verbose) {
310 System.err.println(Thread.currentThread()+" GearsES2.init.X "+sid()+" FIN "+this);
311 }
312 }
313
314 public final boolean isInit() { return isInit; }
315
316 private final GestureHandler.GestureListener pinchToZoomListener = new GestureHandler.GestureListener() {
317 @Override
318 public void gestureDetected(final GestureEvent gh) {
319 final PinchToZoomGesture.ZoomEvent ze = (PinchToZoomGesture.ZoomEvent) gh;
320 final float zoom = ze.getZoom(); // * ( ze.getTrigger().getPointerCount() - 1 ); <- too much ..
321 panZ = zoom * 30f - 30f; // [0 .. 2] -> [-30f .. 30f]
322 }
323 };
324
325 @Override
326 public void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height) {
327 if( !isInit ) { return; }
328 final GL2ES2 gl = glad.getGL().getGL2ES2();
329 gl.setSwapInterval(swapInterval);
330 reshapeImpl(gl, x, y, width, height, width, height);
331 }
332
333 @Override
334 public void reshapeTile(final TileRendererBase tr,
335 final int tileX, final int tileY, final int tileWidth, final int tileHeight,
336 final int imageWidth, final int imageHeight) {
337 if( !isInit ) { return; }
338 final GL2ES2 gl = tr.getAttachedDrawable().getGL().getGL2ES2();
339 gl.setSwapInterval(0);
340 reshapeImpl(gl, tileX, tileY, tileWidth, tileHeight, imageWidth, imageHeight);
341 }
342
343 private float zNear = 5f;
344 private float zFar = 10000f;
345 private float zViewDist = 40.0f;
346
347 public void setZ(final float zNear, final float zFar, final float zViewDist) {
348 this.zNear = zNear;
349 this.zFar = zFar;
350 this.zViewDist = zViewDist;
351 }
352
353 void reshapeImpl(final GL2ES2 gl, final int tileX, final int tileY, final int tileWidth, final int tileHeight, final int imageWidth, final int imageHeight) {
355 if(verbose) {
356 System.err.println(Thread.currentThread()+" GearsES2.reshape "+sid()+" "+tileX+"/"+tileY+" "+tileWidth+"x"+tileHeight+" of "+imageWidth+"x"+imageHeight+", swapInterval "+swapInterval+", drawable 0x"+Long.toHexString(gl.getContext().getGLDrawable().getHandle())+", msaa "+msaa+", tileRendererInUse "+tileRendererInUse);
357 }
358
359 if( !gl.hasGLSL() ) {
360 return;
361 }
362
363 // compute projection parameters 'normal'
364 float left, right, bottom, top;
365 if( imageHeight > imageWidth ) {
366 final float a = (float)imageHeight / (float)imageWidth;
367 left = -1.0f;
368 right = 1.0f;
369 bottom = -a;
370 top = a;
371 } else {
372 final float a = (float)imageWidth / (float)imageHeight;
373 left = -a;
374 right = a;
375 bottom = -1.0f;
376 top = 1.0f;
377 }
378 final float w = right - left;
379 final float h = top - bottom;
380
381 // compute projection parameters 'tiled'
382 final float l = left + tileX * w / imageWidth;
383 final float r = l + tileWidth * w / imageWidth;
384 final float b = bottom + tileY * h / imageHeight;
385 final float t = b + tileHeight * h / imageHeight;
386
387 final float _w = r - l;
388 final float _h = t - b;
389 if(verbose) {
390 System.err.println(">> GearsES2 "+sid()+", angle "+angle+", [l "+left+", r "+right+", b "+bottom+", t "+top+"] "+w+"x"+h+" -> [l "+l+", r "+r+", b "+b+", t "+t+"] "+_w+"x"+_h+", v-flip "+flipVerticalInGLOrientation);
391 }
392
393 pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
394 pmvMatrix.glLoadIdentity();
395 if( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() ) {
396 pmvMatrix.glScalef(1f, -1f, 1f);
397 }
398 pmvMatrix.glFrustumf(l, r, b, t, zNear, zFar);
399
400 pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
401 pmvMatrix.glLoadIdentity();
402 pmvMatrix.glTranslatef(0.0f, 0.0f, -zViewDist);
403 st.useProgram(gl, true);
404 st.uniform(gl, pmvMatrixUniform);
405 st.useProgram(gl, false);
406 }
407 // private boolean useAndroidDebug = false;
408
409 private final Matrix4f mat4Tmp1 = new Matrix4f();
410 private final Matrix4f mat4Tmp2 = new Matrix4f();
411 private final Vec3f vec3Tmp1 = new Vec3f();
412 private final Vec3f vec3Tmp2 = new Vec3f();
413 private final Vec3f vec3Tmp3 = new Vec3f();
414
415 private static final float scalePos = 20f;
416
417 @Override
418 public void reshapeForEye(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height,
419 final EyeParameter eyeParam, final ViewerPose viewerPose) {
420 final GL2ES2 gl = drawable.getGL().getGL2ES2();
421
422 {
423 //
424 // Projection
425 //
426 final Matrix4f mat4 = new Matrix4f();
428 if( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() ) {
429 mat4Tmp1.setToScale(1f, -1f, 1f);
430 mat4Tmp2.setToPerspective(eyeParam.fovhv, zNear, zFar);
431 mat4.mul(mat4Tmp1, mat4Tmp2);
432
433 } else {
434 mat4.setToPerspective(eyeParam.fovhv, zNear, zFar);
435 }
436 pmvMatrix.glLoadMatrixf(mat4);
437
438 //
439 // Modelview
440 //
442 final Quaternion rollPitchYaw = new Quaternion();
443 // private final float eyeYaw = FloatUtil.PI; // 180 degrees in radians
444 // rollPitchYaw.rotateByAngleY(eyeYaw);
445 // final Vec3f shiftedEyePos = rollPitchYaw.rotateVector(viewerPose.position, vec3Tmp1);
446 final Vec3f shiftedEyePos = vec3Tmp1.set(viewerPose.position);
447 shiftedEyePos.scale(scalePos); // amplify viewerPose position
448 shiftedEyePos.add(eyeParam.positionOffset);
449
450 rollPitchYaw.mult(viewerPose.orientation);
451 final Vec3f up = rollPitchYaw.rotateVector(Vec3f.UNIT_Y, vec3Tmp2);
452 final Vec3f forward = rollPitchYaw.rotateVector(Vec3f.UNIT_Z_NEG, vec3Tmp3); // -> center
453 final Vec3f center = forward.add(shiftedEyePos);
454
455 final Matrix4f mLookAt = mat4Tmp2.setToLookAt(shiftedEyePos, center, up, mat4Tmp1);
456 mat4.mul( mat4Tmp1.setToTranslation( eyeParam.distNoseToPupilX,
457 eyeParam.distMiddleToPupilY,
458 eyeParam.eyeReliefZ ), mLookAt);
459 mat4.translate(0, 0, -zViewDist, mat4Tmp1);
460 pmvMatrix.glLoadMatrixf(mat4);
461 }
462 st.useProgram(gl, true);
463 st.uniform(gl, pmvMatrixUniform);
464 st.useProgram(gl, false);
465 }
466
467 @Override
468 public void dispose(final GLAutoDrawable drawable) {
469 if( !isInit ) { return; }
470 isInit = false;
471 if(verbose) {
472 System.err.println(Thread.currentThread()+" GearsES2.dispose "+sid()+": tileRendererInUse "+tileRendererInUse);
473 }
474 final Object upstreamWidget = drawable.getUpstreamWidget();
475 if (upstreamWidget instanceof Window) {
476 final Window window = (Window) upstreamWidget;
479 window.removeGestureHandler(pinchToZoomGesture);
480 pinchToZoomGesture = null;
481 window.removeGestureListener(pinchToZoomListener);
482 }
483 final GL2ES2 gl = drawable.getGL().getGL2ES2();
484 if( !gl.hasGLSL() ) {
485 return;
486 }
487 st.useProgram(gl, false);
488 gear1.destroy(gl);
489 gear1 = null;
490 gear2.destroy(gl);
491 gear2 = null;
492 gear3.destroy(gl);
493 gear3 = null;
494 pmvMatrix = null;
495 colorU = null;
496 st.destroy(gl);
497 st = null;
498 sharedGears = null;
499 syncObjects = null;
500
501 if(verbose) {
502 System.err.println(Thread.currentThread()+" GearsES2.dispose "+sid()+" FIN");
503 }
504 }
505
506 @Override
507 public void display(final GLAutoDrawable drawable) {
508 display(drawable, 0);
509 }
510
511 @Override
512 public void display(final GLAutoDrawable drawable, final int flags) {
513 if( !isInit ) { return; }
514 if(null != sharedGears && !sharedGears.isInit() ) { return; }
515 final GLAnimatorControl anim = drawable.getAnimator();
516 if( verbose && ( null == anim || !anim.isAnimating() ) ) {
517 System.err.println(Thread.currentThread()+" GearsES2.display "+sid()+" "+drawable.getSurfaceWidth()+"x"+drawable.getSurfaceHeight()+", swapInterval "+swapInterval+", drawable 0x"+Long.toHexString(drawable.getHandle()));
518 }
519
520 final boolean repeatedFrame = 0 != ( CustomGLEventListener.DISPLAY_REPEAT & flags );
521 final boolean dontClear = 0 != ( CustomGLEventListener.DISPLAY_DONTCLEAR & flags );
522
523 // Turn the gears' teeth
524 if( doRotate && !repeatedFrame ) {
525 angle += 0.5f;
526 }
527
528 // Get the GL corresponding to the drawable we are animating
529 final GL2ES2 gl = drawable.getGL().getGL2ES2();
530
531 final boolean hasFocus;
532 final Object upstreamWidget = drawable.getUpstreamWidget();
533 if(upstreamWidget instanceof NativeWindow) {
534 hasFocus = ((NativeWindow)upstreamWidget).hasFocus();
535 } else {
536 hasFocus = true;
537 }
538
539 if( clearBuffers && !dontClear ) {
540 if( null != clearColor ) {
541 gl.glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
542 } else if( null != tileRendererInUse ) {
543 gl.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
544 } else if( ignoreFocus || hasFocus ) {
545 gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
546 } else {
547 gl.glClearColor(0.2f, 0.2f, 0.2f, 0.0f);
548 }
549 // Special handling for the case where the GLJPanel is translucent
550 // and wants to be composited with other Java 2D content
551 if (GLProfile.isAWTAvailable() &&
552 (drawable instanceof com.jogamp.opengl.awt.GLJPanel) &&
553 !((com.jogamp.opengl.awt.GLJPanel) drawable).isOpaque() &&
554 ((com.jogamp.opengl.awt.GLJPanel) drawable).shouldPreserveColorBufferIfTranslucent()) {
556 } else {
558 }
559 }
560 if( !gl.hasGLSL() ) {
561 return;
562 }
563
564 setGLStates(gl, true);
565
566 st.useProgram(gl, true);
567 pmvMatrix.glPushMatrix();
568 pmvMatrix.glTranslatef(panX, panY, panZ);
569 pmvMatrix.glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
570 pmvMatrix.glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
571 pmvMatrix.glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
572
573 synchronized ( syncObjects ) {
574 gear1.draw(gl, -3.0f, -2.0f, 1f * angle - 0f);
575 gear2.draw(gl, 3.1f, -2.0f, -2f * angle - 9.0f);
576 gear3.draw(gl, -3.1f, 4.2f, -2f * angle - 25.0f);
577 }
578 pmvMatrix.glPopMatrix();
579 st.useProgram(gl, false);
580
581 setGLStates(gl, false);
582 }
583
584 public void setGLStates(final GL2ES2 gl, final boolean enable) {
585 // Culling only possible if we do not flip the projection matrix
586 final boolean useCullFace = ! ( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() || customRendering );
587 if( enable ) {
589 if( useCullFace ) {
591 }
592 } else {
594 if( useCullFace ) {
596 }
597 }
598 }
599
600 @Override
601 public String toString() {
602 return "GearsES2[obj "+sid()+" isInit "+isInit+", usesShared "+usesSharedGears+", 1 "+gear1+", 2 "+gear2+", 3 "+gear3+", sharedGears "+sharedGears+"]";
603 }
604
605 class GearsKeyAdapter extends KeyAdapter {
606 @Override
607 public void keyPressed(final KeyEvent e) {
608 final int kc = e.getKeyCode();
609 if(KeyEvent.VK_LEFT == kc) {
610 view_roty -= 1;
611 } else if(KeyEvent.VK_RIGHT == kc) {
612 view_roty += 1;
613 } else if(KeyEvent.VK_UP == kc) {
614 view_rotx -= 1;
615 } else if(KeyEvent.VK_DOWN == kc) {
616 view_rotx += 1;
617 }
618 }
619 }
620
621 class GearsMouseAdapter implements MouseListener{
622 private int prevMouseX, prevMouseY;
623
624 @Override
625 public void mouseClicked(final MouseEvent e) {
626 }
627
628 @Override
629 public void mouseEntered(final MouseEvent e) {
630 }
631
632 @Override
633 public void mouseExited(final MouseEvent e) {
634 }
635
636 @Override
637 public void mouseWheelMoved(final MouseEvent e) {
638 final float[] rot = e.getRotation();
639 if( e.isControlDown() ) {
640 // alternative zoom
641 final float incr = e.isShiftDown() ? rot[0] : rot[1] * 0.5f ;
642 panZ += incr;
643 System.err.println("panZ.2: incr "+incr+", dblZoom "+e.isShiftDown()+" -> "+panZ);
644 } else {
645 // panning
646 panX -= rot[0]; // positive -> left
647 panY += rot[1]; // positive -> up
648 }
649 }
650
651 @Override
652 public void mousePressed(final MouseEvent e) {
653 if( e.getPointerCount()==1 ) {
654 prevMouseX = e.getX();
655 prevMouseY = e.getY();
656 } else if( e.getPointerCount() == 4 ) {
657 final Object src = e.getSource();
658 if( e.getPressure(0, true) > 0.7f && src instanceof Window) { // show Keyboard
659 ((Window) src).setKeyboardVisible(true);
660 }
661 }
662 }
663
664 @Override
665 public void mouseReleased(final MouseEvent e) {
666 }
667
668 @Override
669 public void mouseMoved(final MouseEvent e) {
670 if( e.isConfined() ) {
671 navigate(e);
672 } else {
673 // track prev. position so we don't have 'jumps'
674 // in case we move to confined navigation.
675 prevMouseX = e.getX();
676 prevMouseY = e.getY();
677 }
678 }
679
680 @Override
681 public void mouseDragged(final MouseEvent e) {
682 navigate(e);
683 }
684
685 private void navigate(final MouseEvent e) {
686 final int x = e.getX();
687 final int y = e.getY();
688
689 int width, height;
690 final Object source = e.getSource();
691 Window window = null;
692 if(source instanceof Window) {
693 window = (Window) source;
694 width=window.getSurfaceWidth();
695 height=window.getSurfaceHeight();
696 } else if (source instanceof GLAutoDrawable) {
697 final GLAutoDrawable glad = (GLAutoDrawable) source;
698 width = glad.getSurfaceWidth();
699 height = glad.getSurfaceHeight();
700 } else if (GLProfile.isAWTAvailable() && source instanceof java.awt.Component) {
701 final java.awt.Component comp = (java.awt.Component) source;
702 width=comp.getWidth(); // FIXME HiDPI: May need to convert window units -> pixel units!
703 height=comp.getHeight();
704 } else {
705 throw new RuntimeException("Event source neither Window nor Component: "+source);
706 }
707 final float thetaY = 360.0f * ( (float)(x-prevMouseX)/(float)width);
708 final float thetaX = 360.0f * ( (float)(prevMouseY-y)/(float)height);
709 view_rotx += thetaX;
710 view_roty += thetaY;
711 prevMouseX = x;
712 prevMouseY = y;
713 // System.err.println("rotXY.1: "+view_rotx+"/"+view_roty+", source "+e);
714 }
715 }
716}
Basic 4x4 float matrix implementation using fields for intensive use-cases (host operations).
Definition: Matrix4f.java:89
final Matrix4f mul(final Matrix4f b)
Multiply matrix: [this] = [this] x [b].
Definition: Matrix4f.java:726
final Matrix4f translate(final float x, final float y, final float z, final Matrix4f tmp)
Translate this matrix, i.e.
Definition: Matrix4f.java:1558
Matrix4f setToPerspective(final float fovy_rad, final float aspect, final float zNear, final float zFar)
Set this matrix to perspective frustum projection.
Definition: Matrix4f.java:1303
Matrix4f setToLookAt(final Vec3f eye, final Vec3f center, final Vec3f up, final Matrix4f tmp)
Set this matrix to the look-at matrix based on given parameters.
Definition: Matrix4f.java:1432
Quaternion implementation supporting Gimbal-Lock free rotations.
Definition: Quaternion.java:45
final Vec3f rotateVector(final Vec3f vecIn, final Vec3f vecOut)
final Quaternion mult(final Quaternion q)
Multiply this quaternion by the param quaternion.
3D Vector based upon three float components.
Definition: Vec3f.java:37
Vec3f scale(final float s)
this = this * s, returns this.
Definition: Vec3f.java:218
static final Vec3f UNIT_Z_NEG
Definition: Vec3f.java:44
static final Vec3f UNIT_Y
Definition: Vec3f.java:41
Vec3f set(final Vec3f o)
this = o, returns this.
Definition: Vec3f.java:79
Vec3f add(final float dx, final float dy, final float dz)
this = this + { dx, dy, dz }, returns this.
Definition: Vec3f.java:239
PMVMatrix4f implements the basic computer graphics Matrix4f pack using projection (P),...
static final int INVERSE_TRANSPOSED_MODELVIEW
Bit value for inverse transposed modelview matrix (Mvit), updated via update().
static final int INVERSE_MODELVIEW
Bit value for inverse modelview matrix (Mvi), updated via update().
final SyncMatrices4f getSyncPMvMviMvit()
Returns SyncMatrices4f of 4 matrices within one FloatBuffer: P, Mv, Mvi and Mvit if requested.
static final short VK_LEFT
Constant for the cursor- or numerical-pad left arrow key.
Definition: KeyEvent.java:811
final short getKeyCode()
Returns the virtual key code using a fixed mapping to the US keyboard layout.
Definition: KeyEvent.java:195
A GestureHandler.GestureEvent denominating zoom.
abstract GLDrawable getGLDrawable()
Returns the write-drawable this context uses for framebuffer operations.
final boolean hasRendererQuirk(final int quirk)
Returns true if the quirk exist in getRendererQuirks(), otherwise false.
Definition: GLContext.java:304
Specifies the the OpenGL profile.
Definition: GLProfile.java:77
GLRendererQuirks contains information of known bugs of various GL renderer.
static final int NeedSharedObjectSync
Need GL objects (VBO, ..) to be synchronized when utilized concurrently from multiple threads via a s...
final StringBuilder toString(StringBuilder sb)
GLSL uniform data wrapper encapsulating data to be uploaded to the GPU as a uniform.
static StringBuilder getGLStrings(final GL gl, final StringBuilder sb)
void removeTileRendererNotify(final TileRendererBase tr)
The owning GLAutoDrawable is detached from the given TileRendererBase instance.
Definition: GearsES2.java:118
void addTileRendererNotify(final TileRendererBase tr)
The owning GLAutoDrawable is attached to the given TileRendererBase instance.
Definition: GearsES2.java:112
void init(final GLAutoDrawable drawable)
Called by the drawable immediately after the OpenGL context is initialized.
Definition: GearsES2.java:198
void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height)
Called by the drawable during the first repaint after the component has been resized.
Definition: GearsES2.java:326
void setGearsColors(final FloatBuffer gear1Color, final FloatBuffer gear2Color, final FloatBuffer gear3Color)
Definition: GearsES2.java:142
void display(final GLAutoDrawable drawable, final int flags)
Extended display method, allowing to pass a display flag, e.g.
Definition: GearsES2.java:512
void startTileRendering(final TileRendererBase tr)
Called by the TileRendererBase during tile-rendering after TileRendererBase#beginTile(GL) and before ...
Definition: GearsES2.java:123
void setGLStates(final GL2ES2 gl, final boolean enable)
Definition: GearsES2.java:584
void endTileRendering(final TileRendererBase tr)
Called by the TileRenderer during tile-rendering after TileRendererBase#endTile(GL) and GLAutoDrawabl...
Definition: GearsES2.java:127
void dispose(final GLAutoDrawable drawable)
Notifies the listener to perform the release of all OpenGL resources per GLContext,...
Definition: GearsES2.java:468
void display(final GLAutoDrawable drawable)
Called by the drawable to initiate OpenGL rendering by the client.
Definition: GearsES2.java:507
boolean waitForInit(final boolean initialized)
Definition: GearsES2.java:187
void reshapeTile(final TileRendererBase tr, final int tileX, final int tileY, final int tileWidth, final int tileHeight, final int imageWidth, final int imageHeight)
Called by the TileRendererBase during tile-rendering via an attached GLAutoDrawable's GLAutoDrawable#...
Definition: GearsES2.java:334
void reshapeForEye(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height, final EyeParameter eyeParam, final ViewerPose viewerPose)
Stereo capable specialization of reshape(GLAutoDrawable, int, int, int, int) for one StereoDeviceRend...
Definition: GearsES2.java:418
void setZ(final float zNear, final float zFar, final float zViewDist)
Definition: GearsES2.java:347
void setClearColor(final float[] clearColor)
float[4]
Definition: GearsES2.java:138
PMVMatrix implements a subset of the fixed function pipeline GLMatrixFunc using PMVMatrix4f.
Definition: PMVMatrix.java:62
final void glTranslatef(final float x, final float y, final float z)
Translate the current matrix.
Definition: PMVMatrix.java:379
final void glScalef(final float x, final float y, final float z)
Scale the current matrix.
Definition: PMVMatrix.java:396
final void glMatrixMode(final int matrixName)
Sets the current matrix mode.
Definition: PMVMatrix.java:218
final void glPushMatrix()
Push the current matrix to it's stack, while preserving it's values.
Definition: PMVMatrix.java:458
final void glFrustumf(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar)
Multiply the current matrix with the frustum matrix.
Definition: PMVMatrix.java:481
final void glRotatef(final float ang_deg, final float x, final float y, final float z)
Rotate the current matrix.
Definition: PMVMatrix.java:413
final void glPopMatrix()
Pop the current matrix from it's stack.
Definition: PMVMatrix.java:447
final void glLoadIdentity()
Load the current matrix with the identity matrix.
Definition: PMVMatrix.java:325
final void glLoadMatrixf(final float[] values, final int offset)
Load the current matrix w/ the provided one.
Definition: PMVMatrix.java:271
A fairly direct port of Brian Paul's tile rendering library, found at http://www.mesa3d....
final GLAutoDrawable getAttachedDrawable()
Returns a previously attached GLAutoDrawable, null if none is attached.
Convenient shader code class to use and instantiate vertex or fragment programs.
Definition: ShaderCode.java:75
final int defaultShaderCustomization(final GL2ES2 gl, final boolean preludeVersion, final boolean addDefaultPrecision)
Default customization of this shader source code.
static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, final String[] sourceFiles, final boolean mutableStringBuilder)
Creates a complete ShaderCode object while reading all shader source of sourceFiles,...
synchronized void add(final ShaderCode shaderCode)
Adds a new shader to this program.
ShaderState allows to sharing data between shader programs, while updating the attribute and uniform ...
synchronized void useProgram(final GL2ES2 gl, final boolean on)
Turns the shader program on or off.
synchronized boolean attachShaderProgram(final GL2ES2 gl, final ShaderProgram prog, final boolean enable)
Attach or switch a shader program.
final Object attachObject(final String name, final Object obj)
Attach user object for the given name to this ShaderState.
synchronized void destroy(final GL2ES2 gl)
Calls release(gl, true, true, true).
boolean uniform(final GL2ES2 gl, final GLUniformData data)
Set the uniform data, if it's location is valid, i.e.
void ownUniform(final GLUniformData uniform)
Bind the GLUniform lifecycle to this ShaderState.
Constant single eye parameter of the viewer, relative to its ViewerPose.
final float distNoseToPupilX
IPD related horizontal distance from nose to pupil in meter.
final FovHVHalves fovhv
Field of view in both directions, may not be centered, either FovHVHalves#inTangents or radians.
final float distMiddleToPupilY
Vertical distance from middle-line to pupil in meter.
final Vec3f positionOffset
eye position vector used to define eye height in meter relative to actor.
final float eyeReliefZ
Z-axis eye relief in meter.
position and orientation of viewer.
Definition: ViewerPose.java:36
final Quaternion orientation
Orientation of viewer.
Definition: ViewerPose.java:50
final Vec3f position
position of viewer in meter.
Definition: ViewerPose.java:47
Extend the NativeSurface interface with windowing information such as window-handle,...
Specifying NEWT's Window functionality:
Definition: Window.java:115
void addGestureListener(GestureHandler.GestureListener gl)
Appends the given GestureHandler.GestureListener to the end of the list.
void addKeyListener(KeyListener l)
Appends the given com.jogamp.newt.event.KeyListener to the end of the list.
void removeGestureHandler(GestureHandler gh)
Removes the given GestureHandler from the list.
void removeKeyListener(KeyListener l)
void addMouseListener(MouseListener l)
Appends the given MouseListener to the end of the list.
void removeGestureListener(GestureHandler.GestureListener gl)
Removes the given GestureHandler.GestureListener from the list.
void addGestureHandler(GestureHandler gh)
Appends the given GestureHandler to the end of the list.
void removeMouseListener(MouseListener l)
Removes the given MouseListener from the list.
Generic gesture handler interface designed to allow pass-through filtering of InputEvents.
Listener for KeyEvents.
static final int GL_VERTEX_SHADER
GL_ES_VERSION_2_0, GL_VERSION_2_0, GL_EXT_vertex_shader, GL_ARB_vertex_shader Alias for: GL_VERTEX_SH...
Definition: GL2ES2.java:39
static final int GL_FRAGMENT_SHADER
GL_ES_VERSION_2_0, GL_VERSION_2_0, GL_ATI_fragment_shader, GL_ARB_fragment_shader Alias for: GL_FRAGM...
Definition: GL2ES2.java:541
An animator control interface, which implementation may drive a com.jogamp.opengl....
boolean isAnimating()
Indicates whether this animator is started and is not paused.
A higher-level abstraction than GLDrawable which supplies an event based mechanism (GLEventListener) ...
GLAnimatorControl getAnimator()
GL getGL()
Returns the GL pipeline object this GLAutoDrawable uses.
void setGLEventListenerInitState(GLEventListener listener, boolean initialized)
Sets the given listener's initialized state.
Object getUpstreamWidget()
Method may return the upstream UI toolkit object holding this GLAutoDrawable instance,...
boolean hasGLSL()
Indicates whether this GL object supports GLSL.
GL2ES2 getGL2ES2()
Casts this object to the GL2ES2 interface.
void setSwapInterval(int interval)
Set the swap interval of the current context and attached onscreen GLDrawable.
GLContext getContext()
Returns the GLContext associated which this GL object.
boolean getSampleBuffers()
Returns whether sample buffers for full-scene antialiasing (FSAA) should be allocated for this drawab...
GLCapabilitiesImmutable getChosenGLCapabilities()
Fetches the GLCapabilitiesImmutable corresponding to the chosen OpenGL capabilities (pixel format / v...
int getSurfaceWidth()
Returns the width of this GLDrawable's surface client area in pixel units.
long getHandle()
Returns the GL drawable handle, guaranteed to be valid after realization and while it's surface is be...
boolean isGLOriented()
Returns true if the drawable is rendered in OpenGL's coordinate system, origin at bottom left.
NativeSurface getNativeSurface()
Returns the associated NativeSurface of this NativeSurfaceHolder.
int getSurfaceHeight()
Returns the height of this GLDrawable's surface client area in pixel units.
void glDisable(int cap)
Entry point to C language function: void {@native glDisable}(GLenum cap) Part of GL_ES_VERSION_2_0...
static final int GL_COLOR_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_COLOR_BUFFER_BIT" wit...
Definition: GL.java:390
void glClearColor(float red, float green, float blue, float alpha)
Entry point to C language function: void {@native glClearColor}(GLfloat red, GLfloat green,...
void glEnable(int cap)
Entry point to C language function: void {@native glEnable}(GLenum cap) Part of GL_ES_VERSION_2_0,...
static final int GL_DEPTH_TEST
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_TEST" with expr...
Definition: GL.java:43
void glClear(int mask)
Entry point to C language function: void {@native glClear}(GLbitfield mask) Part of GL_ES_VERSION_...
void glFinish()
Entry point to C language function: void {@native glFinish}() Part of GL_ES_VERSION_2_0,...
static final int GL_DEPTH_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_BUFFER_BIT" wit...
Definition: GL.java:738
static final int GL_CULL_FACE
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_CULL_FACE" with expre...
Definition: GL.java:720
Subset of OpenGL fixed function pipeline's matrix operations.
static final int GL_PROJECTION
Matrix mode projection.
static final int GL_MODELVIEW
Matrix mode modelview.
Extended GLEventListener and CustomGLEventListener interface supporting stereoscopic client rendering...