Sfoglia il codice sorgente

jme3-vr: whitespace

Stephen Gold 3 anni fa
parent
commit
8bd99bfcce
38 ha cambiato i file con 3197 aggiunte e 3405 eliminazioni
  1. 173 183
      jme3-vr/src/main/java/com/jme3/app/VRAppState.java
  2. 188 202
      jme3-vr/src/main/java/com/jme3/app/VRApplication.java
  3. 43 47
      jme3-vr/src/main/java/com/jme3/app/VRConstants.java
  4. 270 284
      jme3-vr/src/main/java/com/jme3/app/VREnvironment.java
  5. 10 10
      jme3-vr/src/main/java/com/jme3/input/lwjgl/GlfwMouseInputVR.java
  6. 87 92
      jme3-vr/src/main/java/com/jme3/input/vr/AbstractVRMouseManager.java
  7. 53 63
      jme3-vr/src/main/java/com/jme3/input/vr/AbstractVRViewManager.java
  8. 21 22
      jme3-vr/src/main/java/com/jme3/input/vr/HmdType.java
  9. 31 33
      jme3-vr/src/main/java/com/jme3/input/vr/VRAPI.java
  10. 35 37
      jme3-vr/src/main/java/com/jme3/input/vr/VRInputAPI.java
  11. 120 121
      jme3-vr/src/main/java/com/jme3/input/vr/VRInputType.java
  12. 14 16
      jme3-vr/src/main/java/com/jme3/input/vr/VRMouseManager.java
  13. 36 37
      jme3-vr/src/main/java/com/jme3/input/vr/VRTrackedController.java
  14. 66 73
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVR.java
  15. 6 9
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRBounds.java
  16. 4 4
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRInput.java
  17. 73 75
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRMouseManager.java
  18. 72 76
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRTrackedController.java
  19. 2 2
      jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRViewManager.java
  20. 72 74
      jme3-vr/src/main/java/com/jme3/input/vr/oculus/OculusMouseManager.java
  21. 102 110
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVR.java
  22. 8 11
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRBounds.java
  23. 193 211
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRInput.java
  24. 72 75
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRMouseManager.java
  25. 72 76
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRTrackedController.java
  26. 311 339
      jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRViewManager.java
  27. 32 37
      jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVR.java
  28. 44 50
      jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRInput.java
  29. 73 75
      jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRMouseManager.java
  30. 407 425
      jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRViewManager.java
  31. 32 34
      jme3-vr/src/main/java/com/jme3/shadow/AbstractShadowRendererVR.java
  32. 14 15
      jme3-vr/src/main/java/com/jme3/shadow/InstancedDirectionalShadowFilter.java
  33. 5 5
      jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglContextVR.java
  34. 7 10
      jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglDisplayVR.java
  35. 3 6
      jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBufferVR.java
  36. 6 15
      jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglWindowVR.java
  37. 6 6
      jme3-vr/src/main/java/com/jme3/util/VRGUIPositioningMode.java
  38. 434 445
      jme3-vr/src/main/java/com/jme3/util/VRGuiManager.java

+ 173 - 183
jme3-vr/src/main/java/com/jme3/app/VRAppState.java

@@ -60,9 +60,9 @@ import java.util.logging.Level;
 import java.util.logging.Logger;
 
 /**
- * A JMonkey app state dedicated to Virtual Reality. 
+ * A JMonkey app state dedicated to Virtual Reality.
  * An application that want to use VR devices (HTC vive, ...) has to use this app state.<br>
- * As this app state and the main {@link Application application} have to share {@link AppSettings application settings}, 
+ * As this app state and the main {@link Application application} have to share {@link AppSettings application settings},
  * the common way to use this app state is:<br>
  * <ul>
  * <li>To create {@link AppSettings application settings} and set the VR related settings (see {@link VRConstants}).
@@ -74,68 +74,64 @@ import java.util.logging.Logger;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class VRAppState extends AbstractAppState {
-
     private static final Logger logger = Logger.getLogger(VRAppState.class.getName());
-    
+
     /**
      * Is the application has not to start within VR mode (default is <code>false</code>).
      */
     public boolean DISABLE_VR = false;
-    
-
 
     private float fFar  = 1000f;
     private float fNear = 0.1f;
     private int xWin    = 1920;
     private int yWin    = 1080;
-    
+
     private float resMult = 1f;
- 
+
     /*
      where is the headset pointing, after all rotations are combined?
      depends on observer rotation, if any
      */
     private Quaternion tempq = new Quaternion();
-    
+
     private Application application      = null;
     private AppStateManager stateManager = null;
     private AppSettings settings         = null;
-    
+
     private VREnvironment environment    = null;
-    
+
     /**
      * Create a new default VR app state that relies on the given {@link VREnvironment VR environment}.
      * @param environment the {@link VREnvironment VR environment} that this app state is using.
      */
     public VRAppState(VREnvironment environment) {
-      super();
+        super();
+
+        this.environment = environment;
+
+        this.setSettings(environment.getSettings());
+    }
 
-      this.environment = environment; 
-      
-      this.setSettings(environment.getSettings());
-     }
-    
     /**
      * Create a new VR app state with given settings. The app state relies on the given {@link VREnvironment VR environment}.
      * @param settings the settings to use.
      * @param environment the {@link VREnvironment VR environment} that this app state is using.
      */
     public VRAppState(AppSettings settings, VREnvironment environment){
-      this(environment);
-      this.settings = settings;
-      processSettings(settings);
+        this(environment);
+        this.settings = settings;
+        processSettings(settings);
     }
 
-    
     /**
      * Simple update of the app state, this method should contain any spatial updates.
      * This method is called by the {@link #update(float) update()} method and should not be called manually.
      * @param tpf the application time.
      */
     public void simpleUpdate(float tpf) {
-    	return;
+        return;
     }
-    
+
     /**
      * Rendering callback of the app state. This method is called by the {@link #update(float) update()} method and should not be called manually.
      * @param renderManager the {@link RenderManager render manager}.
@@ -153,7 +149,7 @@ public class VRAppState extends AbstractAppState {
         fNear = near;
         fFar = far;
     }
-    
+
     /**
      * Set the mirror window size in pixel.
      * @param width the width of the mirror window in pixel.
@@ -163,7 +159,7 @@ public class VRAppState extends AbstractAppState {
         xWin = width;
         yWin = height;
     }
-    
+
     /**
      * Set the resolution multiplier.
      * @param val the resolution multiplier.
@@ -171,11 +167,10 @@ public class VRAppState extends AbstractAppState {
     public void setResolutionMultiplier(float val) {
         resMult = val;
         if( environment.getVRViewManager() != null ){
-        	environment.getVRViewManager().setResolutionMultiplier(resMult);
+            environment.getVRViewManager().setResolutionMultiplier(resMult);
         }
     }
-   
-	
+
     /**
      * Move filters from the main scene into the eye's.
      * This removes filters from the main scene.
@@ -183,7 +178,7 @@ public class VRAppState extends AbstractAppState {
     public void moveScreenProcessingToVR() {
       environment.getVRViewManager().moveScreenProcessingToEyes();
     }
-    
+
     /**
      * Get the observer final rotation within the scene.
      * @return the observer final rotation within the scene.
@@ -194,10 +189,10 @@ public class VRAppState extends AbstractAppState {
             if( environment.getObserver() == null ) {
                 return environment.getCamera().getRotation();
             } else {
-            	return ((Spatial)environment.getObserver()).getWorldRotation();
+                return ((Spatial)environment.getObserver()).getWorldRotation();
             }
-        }  
-        
+        }
+
         if( environment.getObserver() == null ) {
             tempq.set(environment.getDummyCamera().getRotation());
         } else {
@@ -205,7 +200,7 @@ public class VRAppState extends AbstractAppState {
         }
         return tempq.multLocal(environment.getVRHardware().getOrientation());
     }
-    
+
     /**
      * Get the observer final position within the scene.
      * @return the observer position.
@@ -216,20 +211,20 @@ public class VRAppState extends AbstractAppState {
             if( environment.getObserver() == null ) {
                 return environment.getCamera().getLocation();
             } else{
-            	return ((Spatial)environment.getObserver()).getWorldTranslation();            
+                return ((Spatial)environment.getObserver()).getWorldTranslation();
             }
         }
-        
+
         Vector3f pos = environment.getVRHardware().getPosition();
         if( environment.getObserver() == null ) {
-        	environment.getDummyCamera().getRotation().mult(pos, pos);
+            environment.getDummyCamera().getRotation().mult(pos, pos);
             return pos.addLocal(environment.getDummyCamera().getLocation());
         } else {
-        	((Spatial)environment.getObserver()).getWorldRotation().mult(pos, pos);
+            ((Spatial)environment.getObserver()).getWorldRotation().mult(pos, pos);
             return pos.addLocal(((Spatial)environment.getObserver()).getWorldTranslation());
         }
     }
-    
+
     /**
      * Get the VR headset left viewport.
      * @return the VR headset left viewport.
@@ -237,12 +232,12 @@ public class VRAppState extends AbstractAppState {
      */
     public ViewPort getLeftViewPort() {
         if( environment.getVRViewManager() == null ){
-        	return application.getViewPort();
+            return application.getViewPort();
         }
-        
+
         return environment.getVRViewManager().getLeftViewPort();
     }
-    
+
     /**
      * Get the VR headset right viewport.
      * @return the VR headset right viewport.
@@ -250,11 +245,11 @@ public class VRAppState extends AbstractAppState {
      */
     public ViewPort getRightViewPort() {
         if( environment.getVRViewManager() == null ){
-        	return application.getViewPort();
+            return application.getViewPort();
         }
         return environment.getVRViewManager().getRightViewPort();
     }
-    
+
     /**
      * Set the background color for both left and right view ports.
      * @param clr the background color.
@@ -263,42 +258,41 @@ public class VRAppState extends AbstractAppState {
         if( environment.getVRViewManager() == null ) {
             application.getViewPort().setBackgroundColor(clr);
         } else if( environment.getVRViewManager().getLeftViewPort() != null ) {
-        	
-        	environment.getVRViewManager().getLeftViewPort().setBackgroundColor(clr);
-            
-        	if( environment.getVRViewManager().getRightViewPort() != null ){
-            	environment.getVRViewManager().getRightViewPort().setBackgroundColor(clr);
+            environment.getVRViewManager().getLeftViewPort().setBackgroundColor(clr);
+
+            if( environment.getVRViewManager().getRightViewPort() != null ){
+                environment.getVRViewManager().getRightViewPort().setBackgroundColor(clr);
             }
         }
     }
-    
+
     /**
      * Get the {@link Application} to which this app state is attached.
      * @return the {@link Application} to which this app state is attached.
      * @see #getStateManager()
      */
     public Application getApplication(){
-    	return application;
+        return application;
     }
-    
+
     /**
      * Get the {@link AppStateManager state manager} to which this app state is attached.
      * @return the {@link AppStateManager state manager} to which this app state is attached.
      * @see #getApplication()
      */
     public AppStateManager getStateManager(){
-    	return stateManager;
+        return stateManager;
     }
-    
+
     /**
      * Get the scene observer. If no observer has been set, this method returns the application camera.
-     * @return the scene observer. 
+     * @return the scene observer.
      * @see #setObserver(Spatial)
      */
     public Object getObserver() {
         return environment.getObserver();
     }
-    
+
     /**
      * Set the scene observer. The VR headset will be linked to it. If no observer is set, the VR headset is linked to the application camera.
      * @param observer the scene observer.
@@ -306,7 +300,7 @@ public class VRAppState extends AbstractAppState {
     public void setObserver(Spatial observer) {
        environment.setObserver(observer);
     }
-    
+
     /**
      * Check if the rendering is instanced (see <a href="https://en.wikipedia.org/wiki/Geometry_instancing">Geometry instancing</a>).
      * @return <code>true</code> if the rendering is instanced and <code>false</code> otherwise.
@@ -314,84 +308,84 @@ public class VRAppState extends AbstractAppState {
     public boolean isInstanceRendering() {
         return environment.isInstanceRendering();
     }
-    
+
     /**
-     * Return the {@link VREnvironment VR environment} on which this app state relies. 
-     * @return the {@link VREnvironment VR environment} on which this app state relies. 
+     * Return the {@link VREnvironment VR environment} on which this app state relies.
+     * @return the {@link VREnvironment VR environment} on which this app state relies.
      */
     public VREnvironment getVREnvironment(){
-    	return environment;
-    }
-    
-	/**
-	 * Get the VR underlying hardware.
-	 * @return the VR underlying hardware.
-	 */
-	public VRAPI getVRHardware() {
-	    return getVREnvironment().getVRHardware();
-	}
-	
-	/**
-	 * Get the VR dedicated input.
-	 * @return the VR dedicated input.
-	 */
-	public VRInputAPI getVRinput() {
-	    if( getVREnvironment().getVRHardware() == null ){
-	    	return null;
-	    }
-	    
-	    return getVREnvironment().getVRHardware().getVRinput();
-	}
-	
-	/**
-	 * Get the VR view manager.
-	 * @return the VR view manager.
-	 */
-	public VRViewManager getVRViewManager() {
-	    return getVREnvironment().getVRViewManager();
-	}
-	
-	/**
-	 * Get the GUI manager attached to this app state.
-	 * @return the GUI manager attached to this app state.
-	 */
-	public VRGuiManager getVRGUIManager(){
-		return getVREnvironment().getVRGUIManager();
-	}
-	
-	/**
-	 * Get the VR mouse manager attached to this app state.
-	 * @return the VR mouse manager attached to this application.
-	 */
-	public VRMouseManager getVRMouseManager(){
-		return getVREnvironment().getVRMouseManager();
-	}
-    
-	/**
-	 * Get the {@link AppSettings settings} attached to this app state.
-	 * @return the {@link AppSettings settings} attached to this app state.
-	 * @see #setSettings(AppSettings)
-	 */
-	public AppSettings getSettings(){
-		return settings;
-	}
-	
-	/**
-	 * Set the {@link AppSettings settings} attached to this app state.
-	 * @param settings the {@link AppSettings settings} attached to this app state.
-	 * @see #getSettings()
-	 */
-	public void setSettings(AppSettings settings){
-		this.settings = settings;
-		processSettings(settings);
-	}
-	
+        return environment;
+    }
+
+    /**
+     * Get the VR underlying hardware.
+     * @return the VR underlying hardware.
+     */
+    public VRAPI getVRHardware() {
+        return getVREnvironment().getVRHardware();
+    }
+
+    /**
+     * Get the VR dedicated input.
+     * @return the VR dedicated input.
+     */
+    public VRInputAPI getVRinput() {
+        if( getVREnvironment().getVRHardware() == null ){
+            return null;
+        }
+
+        return getVREnvironment().getVRHardware().getVRinput();
+    }
+
+    /**
+     * Get the VR view manager.
+     * @return the VR view manager.
+     */
+    public VRViewManager getVRViewManager() {
+        return getVREnvironment().getVRViewManager();
+    }
+
+    /**
+     * Get the GUI manager attached to this app state.
+     * @return the GUI manager attached to this app state.
+     */
+    public VRGuiManager getVRGUIManager(){
+        return getVREnvironment().getVRGUIManager();
+    }
+
+    /**
+     * Get the VR mouse manager attached to this app state.
+     * @return the VR mouse manager attached to this application.
+     */
+    public VRMouseManager getVRMouseManager(){
+        return getVREnvironment().getVRMouseManager();
+    }
+
+    /**
+     * Get the {@link AppSettings settings} attached to this app state.
+     * @return the {@link AppSettings settings} attached to this app state.
+     * @see #setSettings(AppSettings)
+     */
+    public AppSettings getSettings(){
+        return settings;
+    }
+
+    /**
+     * Set the {@link AppSettings settings} attached to this app state.
+     * @param settings the {@link AppSettings settings} attached to this app state.
+     * @see #getSettings()
+     */
+    public void setSettings(AppSettings settings){
+        this.settings = settings;
+        processSettings(settings);
+    }
+
     @Override
-    public void update(float tpf) {    
-        
+    public void update(float tpf) {
+
         // update VR pose & cameras
         if( environment.getVRViewManager() != null ) {
-        	environment.getVRViewManager().update(tpf);    
+            environment.getVRViewManager().update(tpf);
         } else if( environment.getObserver() != null ) {
             environment.getCamera().setFrame(((Spatial)environment.getObserver()).getWorldTranslation(), ((Spatial)environment.getObserver()).getWorldRotation());
         }
@@ -401,9 +395,9 @@ public class VRAppState extends AbstractAppState {
             // it will get updated automatically in the view manager update otherwise
             // TODO isn't this done by SimpleApplication?
             for (Spatial spatial : application.getGuiViewPort().getScenes()) {
-            	//spatial.updateLogicalState(tpf);
-            	spatial.updateGeometricState();
-            }    
+                //spatial.updateLogicalState(tpf);
+                spatial.updateGeometricState();
+            }
         }
 
         // use the analog control on the first tracked controller to push around the mouse
@@ -413,86 +407,84 @@ public class VRAppState extends AbstractAppState {
     @Override
     public void render(RenderManager rm) {
       super.render(rm);
-      
+
       // update compositor
       if( environment.getVRViewManager() != null ) {
         environment.getVRViewManager().render();
       }
     }
-    
+
     @Override
     public void postRender() {
         super.postRender();
-        
+
         // update compositor
         if( environment.getVRViewManager() != null ) {
-        	environment.getVRViewManager().postRender();
+            environment.getVRViewManager().postRender();
         }
     }
 
     @Override
     public void initialize(AppStateManager stateManager, Application app) {
         super.initialize(stateManager, app);
-        
+
         this.application  = app;
         this.stateManager = stateManager;
-        
+
         // disable annoying warnings about GUI stuff being updated, which is normal behavior
         // for late GUI placement for VR purposes
-        Logger.getLogger("com.jme3").setLevel(Level.SEVERE);     
-        
+        Logger.getLogger("com.jme3").setLevel(Level.SEVERE);
+
         app.getCamera().setFrustumFar(fFar);
         app.getCamera().setFrustumNear(fNear);
 
         if( environment.isInVR() ) {
-        	
-        	logger.config("VR mode enabled.");
-        	
+            logger.config("VR mode enabled.");
+
             if( environment.getVRHardware() != null ) {
-            	environment.getVRHardware().initVRCompositor(environment.compositorAllowed());
+                environment.getVRHardware().initVRCompositor(environment.compositorAllowed());
             } else {
-            	logger.warning("No VR system found.");
+                logger.warning("No VR system found.");
             }
-            
-            
+
             environment.getVRViewManager().setResolutionMultiplier(resMult);
             //inputManager.addMapping(RESET_HMD, new KeyTrigger(KeyInput.KEY_F9));
             //setLostFocusBehavior(LostFocusBehavior.Disabled);
         } else {
-        	logger.config("VR mode disabled.");
+            logger.config("VR mode disabled.");
             //viewPort.attachScene(rootNode);
             //guiViewPort.attachScene(guiNode);
         }
-        
+
         if( environment.getVRViewManager() != null ) {
-        	environment.getVRViewManager().initialize();
+            environment.getVRViewManager().initialize();
         }
     }
-    
+
     @Override
     public void stateAttached(AppStateManager stateManager) {
         super.stateAttached(stateManager); //To change body of generated methods, choose Tools | Templates.
-        
+
         if (settings == null) {
             settings = new AppSettings(true);
             logger.config("Using default settings.");
         } else {
-        	logger.config("Using given settings.");
+            logger.config("Using given settings.");
         }
-   
+
         // Attach VR environment to the application
         if (!environment.isInitialized()){
-        	environment.initialize();
+            environment.initialize();
         }
-        
+
         if (environment.isInitialized()){
-        	environment.atttach(this, stateManager.getApplication());
+            environment.atttach(this, stateManager.getApplication());
         } else {
-        	logger.severe("Cannot attach VR environment to the VR app state as its not initialized.");
+            logger.severe("Cannot attach VR environment to the VR app state as its not initialized.");
         }
 
         GraphicsDevice defDev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
-                                    
+
         if( environment.isInVR() && !environment.compositorAllowed() ) {
             // "easy extended" mode
             // setup experimental JFrame on external device
@@ -510,7 +502,7 @@ public class VRAppState extends AbstractAppState {
             // did we get the VR device?
             if( VRdev != null ) {
                 // set properties for VR acceleration
-                try {   
+                try {
                     java.awt.DisplayMode useDM = null;
                     int max = 0;
                     for(java.awt.DisplayMode dm : VRdev.getDisplayModes()) {
@@ -520,7 +512,7 @@ public class VRAppState extends AbstractAppState {
                             useDM = dm;
                         }
                     }
-                    
+
                     // create a window for the VR device
                     settings.setWidth(useDM.getWidth());
                     settings.setHeight(useDM.getHeight());
@@ -530,32 +522,31 @@ public class VRAppState extends AbstractAppState {
                     settings.setVSync(true); // allow vsync on this display
                     stateManager.getApplication().setSettings(settings);
                     logger.config("Updated underlying application settings.");
-                    
+
                     //VRdev.setFullScreenWindow(VRwindow);
                     // make sure we are in the right display mode
                     if( VRdev.getDisplayMode().equals(useDM) == false ) {
                         VRdev.setDisplayMode(useDM);
                     }
-                    
+
                     return;
-                } catch(Exception e) { 
+                } catch(Exception e) {
                     logger.log(Level.SEVERE, e.getMessage(), e);
                 }
             } else {
-            	logger.config("Cannot access to external screen.");
+                logger.config("Cannot access to external screen.");
             }
         } else {
-        	if (!environment.isInVR()){
-        	  logger.config("Cannot switch to VR mode (VR disabled by user).");
-        	} else if (!environment.compositorAllowed()){
-        	  logger.warning("Cannot switch to VR mode (VR not supported).");
-        	}
+            if (!environment.isInVR()){
+              logger.config("Cannot switch to VR mode (VR disabled by user).");
+            } else if (!environment.compositorAllowed()){
+              logger.warning("Cannot switch to VR mode (VR not supported).");
+            }
         }
-        
+
         if( !environment.isInVR() ) {
-        	
-        	//FIXME: Handling GLFW workaround on MacOS
-        	boolean macOs = false;
+            //FIXME: Handling GLFW workaround on MacOS
+            boolean macOs = false;
             if (macOs) {
                 // GLFW workaround on macs
                 settings.setFrequency(defDev.getDisplayMode().getRefreshRate());
@@ -591,7 +582,7 @@ public class VRAppState extends AbstractAppState {
             settings.setSamples(1);
             settings.setWidth(xWin);
             settings.setHeight(yWin);
-            settings.setBitsPerPixel(32);     
+            settings.setBitsPerPixel(32);
             settings.setFrameRate(0);
             settings.setFrequency(environment.getVRHardware().getDisplayFrequency());
             settings.setFullscreen(false);
@@ -602,34 +593,33 @@ public class VRAppState extends AbstractAppState {
         // Updating application settings
         stateManager.getApplication().setSettings(settings);
         logger.config("Updated underlying application settings.");
-        
     }
 
     @Override
     public void cleanup() {
         if( environment.getVRHardware() != null ) {
-        	environment.getVRHardware().destroy();
-        }        
-        
+            environment.getVRHardware().destroy();
+        }
+
         this.application  = null;
         this.stateManager = null;
     }
-    
+
     @Override
     public void stateDetached(AppStateManager stateManager) {
       super.stateDetached(stateManager);
     }
-    
+
     /**
      * Process the attached settings and apply changes to this app state.
      * @param settings the app settings to process.
      */
     protected void processSettings(AppSettings settings){
-    	if (settings != null){
+        if (settings != null){
 
             if (settings.get(VRConstants.SETTING_DISABLE_VR) != null){
                 DISABLE_VR = settings.getBoolean(VRConstants.SETTING_DISABLE_VR);
-    		}
-    	}
+            }
+        }
     }
 }

File diff suppressed because it is too large
+ 188 - 202
jme3-vr/src/main/java/com/jme3/app/VRApplication.java


+ 43 - 47
jme3-vr/src/main/java/com/jme3/app/VRConstants.java

@@ -1,7 +1,6 @@
 package com.jme3.app;
 
 import java.util.HashMap;
-
 import com.jme3.system.AppSettings;
 
 /**
@@ -10,107 +9,105 @@ import com.jme3.system.AppSettings;
  * @since 3.1.0
  */
 public class VRConstants {
-	
-	/**
-	 * An AppSettings parameter that set if the VR compositor has to be used.
-	 * <p>
-	 * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_USE_COMPOSITOR, value)</code>
-	 */
+    /**
+     * An AppSettings parameter that set if the VR compositor has to be used.
+     * <p>
+     * <b>Type: </b><code>boolean</code><br>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_USE_COMPOSITOR, value)</code>
+     */
     public static final String SETTING_USE_COMPOSITOR = "VRUseCompositor";
-    
+
     /**
-     * An AppSettings parameter that set if the rendering has to use two eyes, 
+     * An AppSettings parameter that set if the rendering has to use two eyes,
      * regardless of VR API detection (turning this setting on without a VR system should lead to errors).
      * <p>
-	 * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_VR_FORCE, value)</code>
-
+     * <b>Type: </b><code>boolean</code><br>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_VR_FORCE, value)</code>
      */
     public static final String SETTING_VR_FORCE = "VRForce";
-    
+
     /**
      * An AppSettings parameter that set to invert the eyes of the HMD.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_FLIP_EYES, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_FLIP_EYES, value)</code>
      */
     public static final String SETTING_FLIP_EYES = "VRFlipEyes";
-    
+
     /**
      * An AppSettings parameter that set if the GUI has to be displayed even if it is behind objects.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_GUI_OVERDRAW, value)</code>
-     * 
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_GUI_OVERDRAW, value)</code>
+     *
      */
     public static final String SETTING_GUI_OVERDRAW = "VRGUIOverdraw";
-    
+
     /**
      * An AppSettings parameter that set if the GUI surface has to be curved.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_GUI_CURVED_SURFACE, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_GUI_CURVED_SURFACE, value)</code>
      */
     public static final String SETTING_GUI_CURVED_SURFACE = "VRGUICurvedSurface";
-  
+
     /**
-     * An AppSettings parameter that set if a mirror rendering has to be displayed on the screen. 
+     * An AppSettings parameter that set if a mirror rendering has to be displayed on the screen.
      * Runs faster when set to <code>false</code>.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_ENABLE_MIRROR_WINDOW, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_ENABLE_MIRROR_WINDOW, value)</code>
      */
     public static final String SETTING_ENABLE_MIRROR_WINDOW = "VREnableMirrorWindow";
-    
+
     /**
-     * An AppSettings parameter that set if the VR rendering has to be disabled, 
+     * An AppSettings parameter that set if the VR rendering has to be disabled,
      * regardless VR API and devices are presents.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DISABLE_VR, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DISABLE_VR, value)</code>
      */
     public static final String SETTING_DISABLE_VR = "VRDisable";
-    
-    
+
+
     /**
      * An AppSettings parameter that set if the VR user is seated.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_SEATED_EXPERIENCE, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_SEATED_EXPERIENCE, value)</code>
      */
     public static final String SETTING_SEATED_EXPERIENCE = "VRSeatedExperience";
-    
+
     /**
      * An AppSettings parameter that set if the GUI has to be ignored.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_NO_GUI, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_NO_GUI, value)</code>
      */
     public static final String SETTING_NO_GUI = "VRNoGUI";
-    
+
     /**
-     * An AppSettings parameter that set if instance rendering has to be used. 
+     * An AppSettings parameter that set if instance rendering has to be used.
      * This setting requires some vertex shader changes (see Common/MatDefs/VR/Unshaded.j3md).
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_INSTANCE_RENDERING, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_INSTANCE_RENDERING, value)</code>
      */
     public static final String SETTING_INSTANCE_RENDERING = "VRInstanceRendering";
-    
+
     /**
      * An AppSettings parameter that set if Multi Sample Anti Aliasing has to be enabled.
      * <b>Type: </b><code>boolean</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DISABLE_MSAA, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DISABLE_MSAA, value)</code>
      */
     public static final String SETTING_DISABLE_MSAA = "VRDisableMSAA";
-    
+
     /**
      * An AppSettings parameter that set the default field of view (FOV) value.
      * <b>Type: </b><code>float</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DEFAULT_FOV, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DEFAULT_FOV, value)</code>
      */
     public static final String SETTING_DEFAULT_FOV = "VRDefaultFOV";
-    
+
     /**
      * An AppSettings parameter that set the default aspect ratio.
      * <b>Type: </b><code>float</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DEFAULT_ASPECT_RATIO, value)</code>
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_DEFAULT_ASPECT_RATIO, value)</code>
      */
     public static final String SETTING_DEFAULT_ASPECT_RATIO = "VRDefaultAspectRatio";
-    
+
     /**
      * An AppSettings parameter that specifies the underlying VR API. Possible values are:<br>
      * <ul>
@@ -120,11 +117,10 @@ public class VRConstants {
      * <li>{@link VRConstants#SETTING_VRAPI_OCULUSVR_VALUE SETTING_VRAPI_OCULUSVR_VALUE}: Use Oculus Rift binding binding.
      * </ul>
      * <b>Type: </b><code>int</code><br>
-	 * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_VRAPI, value)</code>
-
+     * <b>Usage: </b><code>{@link AppSettings appSettings}.{@link HashMap#put(Object, Object) put}(VRConstants.SETTING_VRAPI, value)</code>
      */
     public static final String SETTING_VRAPI = "VRAPI";
-    
+
     /**
      * The identifier of the OpenVR system.
      * @see #SETTING_VRAPI_OSVR_VALUE
@@ -132,7 +128,7 @@ public class VRConstants {
      * @see #SETTING_VRAPI_OCULUSVR_VALUE
      */
     public static final int SETTING_VRAPI_OPENVR_VALUE       = 1;
-    
+
     /**
      * The identifier of the OSVR system.
      * @see #SETTING_VRAPI_OPENVR_VALUE
@@ -140,7 +136,7 @@ public class VRConstants {
      * @see #SETTING_VRAPI_OCULUSVR_VALUE
      */
     public static final int SETTING_VRAPI_OSVR_VALUE         = 2;
-    
+
     /**
      * The identifier of the OpenVR from LWJGL system.
      * @see #SETTING_VRAPI_OPENVR_VALUE
@@ -148,7 +144,7 @@ public class VRConstants {
      * @see #SETTING_VRAPI_OCULUSVR_VALUE
      */
     public static final int SETTING_VRAPI_OPENVR_LWJGL_VALUE = 3;
-    
+
     /**
      * The identifier of the Oculus Rift system.
      * @see #SETTING_VRAPI_OPENVR_VALUE

+ 270 - 284
jme3-vr/src/main/java/com/jme3/app/VREnvironment.java

@@ -28,128 +28,125 @@ import com.jme3.system.jopenvr.JOpenVRLibrary;
 import com.jme3.util.VRGuiManager;
 
 /**
- * 
+ *
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  *
  */
 public class VREnvironment {
-	
-	private static final Logger logger = Logger.getLogger(VREnvironment.class.getName());
-	
+    private static final Logger logger = Logger.getLogger(VREnvironment.class.getName());
+
     private VRAPI hardware              = null;
     private VRGuiManager guiManager     = null;
     private VRMouseManager mouseManager = null;
     private VRViewManager viewManager = null;
-    
+
     private VRBounds bounds             = null;
-    
+
     /**
      * The underlying system VR API. By default set to {@link VRConstants#SETTING_VRAPI_OPENVR_VALUE}.
      */
     public int vrBinding = VRConstants.SETTING_VRAPI_OPENVR_VALUE;
-    
+
     private boolean seated        = false;
-    
+
     private Spatial observer      = null;
-    
+
     private boolean forceVR       = false;
-    
+
     private boolean vrSupportedOS = false;
-    
+
     private boolean nogui = false;
-    
+
     private boolean compositorOS;
-    
+
     private boolean useCompositor = true;
-    
+
     private boolean instanceRendering = false;
-    
+
     private boolean disableSwapBuffers = true;
-    
-	private float defaultFOV           = 108f;
-	
+
+    private float defaultFOV           = 108f;
+
     private float defaultAspect        = 1f;
-    
+
     private AppSettings settings = null;
-    
+
     private Application application = null;
-    
+
     private Camera dummyCam = null;
-    
+
     private AppState app = null;
-    
+
     private boolean initialized = false;
-    
-    
+
     public VREnvironment(AppSettings settings){
-    	
-    	this.settings = settings;
+        this.settings = settings;
 
         bounds       = null;
-        
+
         processSettings();
     }
-    
-	/**
-	 * Get the VR underlying hardware.
-	 * @return the VR underlying hardware.
-	 */
-	public VRAPI getVRHardware() {
-	    return hardware;
-	}
-	
-	/**
-	 * Set the VR bounds.
-	 * @see #getVRBounds()
-	 */
-	public void setVRBounds(VRBounds bounds){
-		this.bounds = bounds;
-	}
-	
-	/**
-	 * Get the VR bounds.
-	 * @return the VR bounds.
-	 * @see #setVRBounds(VRBounds)
-	 */
-	public VRBounds getVRBounds(){
-		return bounds;
-	}
-	
-	/**
-	 * Get the VR dedicated input.
-	 * @return the VR dedicated input.
-	 */
-	public VRInputAPI getVRinput() {
-	    if( hardware == null ){
-	    	return null;
-	    }
-	    
-	    return hardware.getVRinput();
-	}
-	
-	/**
-	 * Get the VR view manager.
-	 * @return the VR view manager.
-	 */
-	public VRViewManager getVRViewManager() {
-	    return viewManager;
-	}
-	
-	/**
-	 * Get the GUI manager attached to this environment.
-	 * @return the GUI manager attached to this environment.
-	 */
-	public VRGuiManager getVRGUIManager(){
-		return guiManager;
-	}
-	
-	/**
-	 * Get the VR mouse manager attached to this environment.
-	 * @return the VR mouse manager attached to this environment.
-	 */
-	public VRMouseManager getVRMouseManager(){
-		return mouseManager;
-	}
+
+    /**
+     * Get the VR underlying hardware.
+     * @return the VR underlying hardware.
+     */
+    public VRAPI getVRHardware() {
+        return hardware;
+    }
+
+    /**
+     * Set the VR bounds.
+     * @see #getVRBounds()
+     */
+    public void setVRBounds(VRBounds bounds){
+        this.bounds = bounds;
+    }
+
+    /**
+     * Get the VR bounds.
+     * @return the VR bounds.
+     * @see #setVRBounds(VRBounds)
+     */
+    public VRBounds getVRBounds(){
+        return bounds;
+    }
+
+    /**
+     * Get the VR dedicated input.
+     * @return the VR dedicated input.
+     */
+    public VRInputAPI getVRinput() {
+        if( hardware == null ){
+            return null;
+        }
+
+        return hardware.getVRinput();
+    }
+
+    /**
+     * Get the VR view manager.
+     * @return the VR view manager.
+     */
+    public VRViewManager getVRViewManager() {
+        return viewManager;
+    }
+
+    /**
+     * Get the GUI manager attached to this environment.
+     * @return the GUI manager attached to this environment.
+     */
+    public VRGuiManager getVRGUIManager(){
+        return guiManager;
+    }
+
+    /**
+     * Get the VR mouse manager attached to this environment.
+     * @return the VR mouse manager attached to this environment.
+     */
+    public VRMouseManager getVRMouseManager(){
+        return mouseManager;
+    }
 
     /**
      * Can be used to change seated experience during runtime.
@@ -160,21 +157,21 @@ public class VREnvironment {
         seated = isSeated;
         if( hardware instanceof OpenVR ) {
             if( hardware.getCompositor() == null ) {
-            	return;
+                return;
             }
-            
+
             if( seated ) {
                 ((OpenVR)hardware).getCompositor().SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseSeated);
             } else {
-                ((OpenVR)hardware).getCompositor().SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseStanding);                
-            }        
+                ((OpenVR)hardware).getCompositor().SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseStanding);
+            }
         } else if (hardware instanceof LWJGLOpenVR) {
-        	if( hardware.isInitialized() ) {
-            	((LWJGLOpenVR)hardware).setTrackingSpace(seated);
+            if( hardware.isInitialized() ) {
+                ((LWJGLOpenVR)hardware).setTrackingSpace(seated);
             }
         }
     }
-    
+
     /**
      * Check if the application is configured as a seated experience.
      * @return <code>true</code> if the application is configured as a seated experience and <code>false</code> otherwise.
@@ -183,7 +180,7 @@ public class VREnvironment {
     public boolean isSeatedExperience() {
         return seated;
     }
-    
+
     /**
      * Set the VR headset height from the ground.
      * @param amount the VR headset height from the ground.
@@ -191,10 +188,10 @@ public class VREnvironment {
      */
     public void setVRHeightAdjustment(float amount) {
         if( viewManager != null ){
-        	viewManager.setHeightAdjustment(amount);
+            viewManager.setHeightAdjustment(amount);
         }
     }
-    
+
     /**
      * Get the VR headset height from the ground.
      * @return the VR headset height from the ground.
@@ -202,28 +199,27 @@ public class VREnvironment {
      */
     public float getVRHeightAdjustment() {
         if( viewManager != null ){
-        	return viewManager.getHeightAdjustment();
+            return viewManager.getHeightAdjustment();
         }
         return 0f;
     }
-    
+
     /**
      * Get the scene observer. If no observer has been set, this method return the application {@link #getCamera() camera}.
-     * @return the scene observer. 
+     * @return the scene observer.
      * @see #setObserver(Spatial)
      */
     public Object getObserver() {
         if( observer == null ) {
-        	
-        	if (application != null){
+            if (application != null){
               return application.getCamera();
-        	} else {
-        		throw new IllegalStateException("VR environment is not attached to any application.");
-        	}
+            } else {
+                throw new IllegalStateException("VR environment is not attached to any application.");
+            }
         }
         return observer;
     }
-    
+
     /**
      * Set the scene observer. The VR headset will be linked to it. If no observer is set, the VR headset is linked to the application {@link #getCamera() camera}.
      * @param observer the scene observer.
@@ -231,62 +227,62 @@ public class VREnvironment {
     public void setObserver(Spatial observer) {
        this.observer = observer;
     }
-    
+
     /**
      * Get the default Field Of View (FOV) value.
      * @return the default Field Of View (FOV) value.
      * @see #setDefaultFOV(float)
      */
     public float getDefaultFOV() {
-		return defaultFOV;
-	}
+        return defaultFOV;
+    }
 
     /**
      * Set the default Field Of View (FOV) value.
      * @param defaultFOV the default Field Of View (FOV) value.
      * @see #getDefaultFOV()
      */
-	public void setDefaultFOV(float defaultFOV) {
-		this.defaultFOV = defaultFOV;
-	}
-
-	/**
-	 * Get the default aspect ratio.
-	 * @return the default aspect ratio.
-	 * @see #setDefaultAspect(float)
-	 */
-	public float getDefaultAspect() {
-		return defaultAspect;
-	}
-
-	/**
-	 * Set the default aspect ratio.
-	 * @param defaultAspect the default aspect ratio.
-	 * @see #getDefaultAspect()
-	 */
-	public void setDefaultAspect(float defaultAspect) {
-		this.defaultAspect = defaultAspect;
-	}
-    
-	/**
-	 * Get the {@link AppSettings settings} attached to this environment.
-	 * @return the {@link AppSettings settings} attached to this environment.
-	 * @see #setSettings(AppSettings)
-	 */
-	public AppSettings getSettings(){
-		return settings;
-	}
-	
-	/**
-	 * Set the {@link AppSettings settings} attached to this environment.
-	 * @param settings the {@link AppSettings settings} attached to this environment.
-	 * @see #getSettings()
-	 */
-	public void setSettings(AppSettings settings){
-		this.settings = settings;
-		processSettings();
-	}
-    
+    public void setDefaultFOV(float defaultFOV) {
+        this.defaultFOV = defaultFOV;
+    }
+
+    /**
+     * Get the default aspect ratio.
+     * @return the default aspect ratio.
+     * @see #setDefaultAspect(float)
+     */
+    public float getDefaultAspect() {
+        return defaultAspect;
+    }
+
+    /**
+     * Set the default aspect ratio.
+     * @param defaultAspect the default aspect ratio.
+     * @see #getDefaultAspect()
+     */
+    public void setDefaultAspect(float defaultAspect) {
+        this.defaultAspect = defaultAspect;
+    }
+
+    /**
+     * Get the {@link AppSettings settings} attached to this environment.
+     * @return the {@link AppSettings settings} attached to this environment.
+     * @see #setSettings(AppSettings)
+     */
+    public AppSettings getSettings(){
+        return settings;
+    }
+
+    /**
+     * Set the {@link AppSettings settings} attached to this environment.
+     * @param settings the {@link AppSettings settings} attached to this environment.
+     * @see #getSettings()
+     */
+    public void setSettings(AppSettings settings){
+        this.settings = settings;
+        processSettings();
+    }
+
     /**
      * Get if the system currently support VR.
      * @return <code>true</code> if the system currently support VR and <code>false</Code> otherwise.
@@ -294,7 +290,7 @@ public class VREnvironment {
     public boolean isVRSupported() {
         return vrSupportedOS;
     }
-	
+
     /**
      * Check if the VR mode is enabled.
      * @return <code>true</code> if the VR mode is enabled and <code>false</code> otherwise.
@@ -310,11 +306,11 @@ public class VREnvironment {
     public boolean isInstanceRendering() {
         return instanceRendering;
     }
-    
+
     public boolean isSwapBuffers(){
-    	return disableSwapBuffers;
+        return disableSwapBuffers;
     }
-    
+
     /**
      * Check if the application has a GUI overlay attached.
      * @return <code>true</code> if the application has a GUI overlay attached and <code>false</code> otherwise.
@@ -322,15 +318,15 @@ public class VREnvironment {
     public boolean hasTraditionalGUIOverlay() {
         return !nogui;
     }
-    
+
     /**
      * Check if the VR environment is initialized. A call to the {@link #initialize() initialize()} method should set this value to <code>true</code>
      * @return <code>true</code> if the VR environment is initialized and <code>false</code> otherwise.
      */
     public boolean isInitialized(){
-    	return initialized;
+        return initialized;
     }
-    
+
     /**
      * Is the VR compositor is active.
      * @return <code>true</code> if the VR compositor is active and <code>false</code> otherwise.
@@ -344,22 +340,22 @@ public class VREnvironment {
      */
     public void resetSeatedPose(){
         if( vrSupportedOS == false || isSeatedExperience() == false ){
-        	return;
+            return;
         }
         getVRHardware().reset();
     }
-    
+
     public AppState getAppState(){
-    	return app;
+        return app;
     }
-    
+
     public Application getApplication(){
-    	return application;
+        return application;
     }
-    
+
     /**
-     * Get the {@link Camera camera} used for rendering. 
-     * If the VR mode is {@link #isInVR() active}, this method return a dummy camera, otherwise, 
+     * Get the {@link Camera camera} used for rendering.
+     * If the VR mode is {@link #isInVR() active}, this method return a dummy camera, otherwise,
      * this method return the camera of the attached application.
      * @return the camera attached used for rendering.
      */
@@ -367,69 +363,64 @@ public class VREnvironment {
         if( isInVR() && getVRViewManager() != null && getVRViewManager().getLeftCamera() != null ) {
             return getDummyCamera();
         }
-        
+
         return application.getCamera();
     }
-    
+
     public Camera getDummyCamera(){
-    	
-    	if (dummyCam == null){
-    		
-    		if (application != null){
-    			
-    			if (application.getCamera() != null){
-    				dummyCam = application.getCamera().clone();
-    			} else {
-    				
-    				if ((settings != null) && (settings.getWidth() != 0) && (settings.getHeight() != 0)){
-    		        	dummyCam = new Camera(settings.getWidth(), settings.getHeight());
-    		        } else {
-    		        	dummyCam = new Camera(0, 0);
-    		        }
-    			}
-    		} else {
-    			throw new IllegalStateException("VR environment is not attached to any application.");
-    		}
-    	}
-    	return dummyCam;
-    }
-    
+        if (dummyCam == null){
+            if (application != null){
+                if (application.getCamera() != null){
+                    dummyCam = application.getCamera().clone();
+                } else {
+                    if ((settings != null) && (settings.getWidth() != 0) && (settings.getHeight() != 0)){
+                        dummyCam = new Camera(settings.getWidth(), settings.getHeight());
+                    } else {
+                        dummyCam = new Camera(0, 0);
+                    }
+                }
+            } else {
+                throw new IllegalStateException("VR environment is not attached to any application.");
+            }
+        }
+        return dummyCam;
+    }
+
     /**
-     * Attach the VR environment to the given app state and application. 
-     * This method should be called within the {@link AppState#stateAttached(com.jme3.app.state.AppStateManager) stateAttached(com.jme3.app.state.AppStateManager)} method 
+     * Attach the VR environment to the given app state and application.
+     * This method should be called within the {@link AppState#stateAttached(com.jme3.app.state.AppStateManager) stateAttached(com.jme3.app.state.AppStateManager)} method
      * from the app state.
      * @param appState the app state to attach.
      * @param application the application to attach.
      */
-    public void atttach(AppState appState, Application application){    	
-    	this.application = application;
-    	this.app         = appState;
-    	
-    	// Instantiate view manager
-    	if (vrBinding == VRConstants.SETTING_VRAPI_OPENVR_VALUE){
-    		viewManager = new OpenVRViewManager(this);
-    	} else if (vrBinding == VRConstants.SETTING_VRAPI_OSVR_VALUE){
-    		viewManager = new OSVRViewManager(this);
-    	} else if (vrBinding == VRConstants.SETTING_VRAPI_OCULUSVR_VALUE) {
-    		viewManager = new OculusViewManager(this);
-    	} else if (vrBinding == VRConstants.SETTING_VRAPI_OPENVR_LWJGL_VALUE) {
-    		viewManager = new LWJGLOpenVRViewManager(this);
-    	} else {
-    		logger.severe("Cannot instantiate view manager, unknown VRAPI type: "+vrBinding);
-    	}
-    }
-    
+    public void atttach(AppState appState, Application application){
+        this.application = application;
+        this.app         = appState;
+
+        // Instantiate view manager
+        if (vrBinding == VRConstants.SETTING_VRAPI_OPENVR_VALUE){
+            viewManager = new OpenVRViewManager(this);
+        } else if (vrBinding == VRConstants.SETTING_VRAPI_OSVR_VALUE){
+            viewManager = new OSVRViewManager(this);
+        } else if (vrBinding == VRConstants.SETTING_VRAPI_OCULUSVR_VALUE) {
+            viewManager = new OculusViewManager(this);
+        } else if (vrBinding == VRConstants.SETTING_VRAPI_OPENVR_LWJGL_VALUE) {
+            viewManager = new LWJGLOpenVRViewManager(this);
+        } else {
+            logger.severe("Cannot instantiate view manager, unknown VRAPI type: "+vrBinding);
+        }
+    }
+
     /**
-     * Initialize this VR environment. This method enable the system bindings and configure all the VR system modules. 
+     * Initialize this VR environment. This method enable the system bindings and configure all the VR system modules.
      * A call to this method has to be made before any use of VR capabilities.
      * @return <code>true</code> if the VR environment is successfully initialized and <code>false</code> otherwise.
      */
     public boolean initialize(){
-    	
-    	logger.config("Initializing VR environment.");
-    	
-    	initialized = false;
-    	
+        logger.config("Initializing VR environment.");
+
+        initialized = false;
+
         // we are going to use OpenVR now, not the Oculus Rift
         // OpenVR does support the Rift
         String OS     = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
@@ -437,119 +428,114 @@ public class VREnvironment {
         compositorOS  = OS.contains("indows") || OS.contains("nux");
 
         if (OS.contains("nux") && vrBinding != VRConstants.SETTING_VRAPI_OPENVR_LWJGL_VALUE){
-        	logger.severe("Only LWJGL VR backend is currently (partially) supported on Linux.");
-        	vrSupportedOS = false;
+            logger.severe("Only LWJGL VR backend is currently (partially) supported on Linux.");
+            vrSupportedOS = false;
         }
 
         if( vrSupportedOS) {
-        	if( vrBinding == VRConstants.SETTING_VRAPI_OSVR_VALUE ) {
-        		
+            if( vrBinding == VRConstants.SETTING_VRAPI_OSVR_VALUE ) {
                 guiManager   = new VRGuiManager(this);
                 mouseManager = new OpenVRMouseManager(this);
-        		
+
                 hardware = new OSVR(this);
                 initialized = true;
                 logger.config("Creating OSVR wrapper [SUCCESS]");
             } else if( vrBinding == VRConstants.SETTING_VRAPI_OPENVR_VALUE ) {
-            	
                 guiManager   = new VRGuiManager(this);
                 mouseManager = new OpenVRMouseManager(this);
 
-            	hardware = new OpenVR(this);
-            	initialized = true;
+                hardware = new OpenVR(this);
+                initialized = true;
                 logger.config("Creating OpenVR wrapper [SUCCESS]");
             } else if (vrBinding == VRConstants.SETTING_VRAPI_OCULUSVR_VALUE) {
-            	
                 guiManager   = new VRGuiManager(this);
                 mouseManager = new OculusMouseManager(this);
-            	
+
                 hardware = new OculusVR(this);
-            	initialized = true;
-            	logger.config("Creating Oculus Rift wrapper [SUCCESS]");
+                initialized = true;
+                logger.config("Creating Oculus Rift wrapper [SUCCESS]");
             } else if (vrBinding == VRConstants.SETTING_VRAPI_OPENVR_LWJGL_VALUE) {
-            	
-            	guiManager   = new VRGuiManager(this);
+                guiManager   = new VRGuiManager(this);
                 mouseManager = new LWJGLOpenVRMouseManager(this);
 
-            	hardware = new LWJGLOpenVR(this);
-            	initialized = true;
+                hardware = new LWJGLOpenVR(this);
+                initialized = true;
                 logger.config("Creating OpenVR/LWJGL wrapper [SUCCESS]");
             } else {
-            	logger.config("Cannot create VR binding: "+vrBinding+" [FAILED]");
-            	logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
+                logger.config("Cannot create VR binding: "+vrBinding+" [FAILED]");
+                logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
             }
-        	
+
             if( hardware.initialize() ) {
-            	initialized &= true;
-            	logger.config("VR native wrapper initialized [SUCCESS]");
+                initialized &= true;
+                logger.config("VR native wrapper initialized [SUCCESS]");
             } else {
-            	initialized &= false;
-            	logger.warning("VR native wrapper initialized [FAILED]");
-            	logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
+                initialized &= false;
+                logger.warning("VR native wrapper initialized [FAILED]");
+                logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
             }
         } else {
-        	logger.log(Level.SEVERE, "System does not support VR capabilities.");
-        	logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
+            logger.log(Level.SEVERE, "System does not support VR capabilities.");
+            logger.log(Level.SEVERE, "Cannot initialize VR environment [FAILED]");
         }
-    	
-    	return initialized;
+
+        return initialized;
     }
-    
+
     private void processSettings(){
-    	if (settings != null){
-    		
-    		if (settings.get(VRConstants.SETTING_USE_COMPOSITOR) != null){
-    			useCompositor = settings.getBoolean(VRConstants.SETTING_USE_COMPOSITOR);
+        if (settings != null){
+            if (settings.get(VRConstants.SETTING_USE_COMPOSITOR) != null){
+                useCompositor = settings.getBoolean(VRConstants.SETTING_USE_COMPOSITOR);
                 if( useCompositor == false ){
-                	disableSwapBuffers = false;
+                    disableSwapBuffers = false;
                 }
-    		}
-    		
+            }
+
             if (settings.get(VRConstants.SETTING_ENABLE_MIRROR_WINDOW) != null){
                 if( useCompositor == false ) {
                     disableSwapBuffers = false;
                 } else {
-                	disableSwapBuffers = !settings.getBoolean(VRConstants.SETTING_ENABLE_MIRROR_WINDOW);
+                    disableSwapBuffers = !settings.getBoolean(VRConstants.SETTING_ENABLE_MIRROR_WINDOW);
                 }
-    		}
-    		
+            }
+
             if (settings.get(VRConstants.SETTING_GUI_OVERDRAW) != null){
-            	getVRGUIManager().setGuiOverdraw(settings.getBoolean(VRConstants.SETTING_GUI_OVERDRAW));
-    		}
-    	    
+                getVRGUIManager().setGuiOverdraw(settings.getBoolean(VRConstants.SETTING_GUI_OVERDRAW));
+            }
+
             if (settings.get(VRConstants.SETTING_GUI_CURVED_SURFACE) != null){
-            	getVRGUIManager().setCurvedSurface(settings.getBoolean(VRConstants.SETTING_GUI_CURVED_SURFACE));
-    		}
-    		
-    		if (settings.get(VRConstants.SETTING_NO_GUI) != null){
-            	nogui = settings.getBoolean(VRConstants.SETTING_NO_GUI);
-    		}
-    		
+                getVRGUIManager().setCurvedSurface(settings.getBoolean(VRConstants.SETTING_GUI_CURVED_SURFACE));
+            }
+
+            if (settings.get(VRConstants.SETTING_NO_GUI) != null){
+                nogui = settings.getBoolean(VRConstants.SETTING_NO_GUI);
+            }
+
             if (settings.get(VRConstants.SETTING_VRAPI) != null){
-            	vrBinding = settings.getInteger(VRConstants.SETTING_VRAPI);
-    		}
-            
+                vrBinding = settings.getInteger(VRConstants.SETTING_VRAPI);
+            }
+
             if (settings.get(VRConstants.SETTING_SEATED_EXPERIENCE) != null){
-            	seated = settings.getBoolean(VRConstants.SETTING_SEATED_EXPERIENCE);
-    		}
-            
+                seated = settings.getBoolean(VRConstants.SETTING_SEATED_EXPERIENCE);
+            }
+
             if (settings.get(VRConstants.SETTING_INSTANCE_RENDERING) != null){
-            	instanceRendering = settings.getBoolean(VRConstants.SETTING_INSTANCE_RENDERING);
-    		}
+                instanceRendering = settings.getBoolean(VRConstants.SETTING_INSTANCE_RENDERING);
+            }
 
             if (settings.get(VRConstants.SETTING_DEFAULT_FOV) != null){
-            	defaultFOV = settings.getFloat(VRConstants.SETTING_DEFAULT_FOV);
-    		}
-            
+                defaultFOV = settings.getFloat(VRConstants.SETTING_DEFAULT_FOV);
+            }
+
             if (settings.get(VRConstants.SETTING_DEFAULT_ASPECT_RATIO) != null){
-            	defaultAspect = settings.getFloat(VRConstants.SETTING_DEFAULT_ASPECT_RATIO);
-    		}
-            
+                defaultAspect = settings.getFloat(VRConstants.SETTING_DEFAULT_ASPECT_RATIO);
+            }
+
             if (settings.get(VRConstants.SETTING_FLIP_EYES) != null){
                 if( getVRHardware() != null ){
-                	getVRHardware().setFlipEyes(settings.getBoolean(VRConstants.SETTING_FLIP_EYES));
-                } 
-    		}
-    	}
+                    getVRHardware().setFlipEyes(settings.getBoolean(VRConstants.SETTING_FLIP_EYES));
+                }
+            }
+        }
     }
 }

+ 10 - 10
jme3-vr/src/main/java/com/jme3/input/lwjgl/GlfwMouseInputVR.java

@@ -168,10 +168,10 @@ public class GlfwMouseInputVR implements MouseInput {
         if (!context.isRenderable()) {
             return;
         }
-        
-        glfwSetCursorPos(context.getWindowHandle(), x, y);	
+
+        glfwSetCursorPos(context.getWindowHandle(), x, y);
     }
-    
+
     /**
      * Hide the active cursor within the display.
      */
@@ -181,10 +181,10 @@ public class GlfwMouseInputVR implements MouseInput {
         }
 
         if (cursorVisible) {
-            glfwSetInputMode(context.getWindowHandle(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);            
+            glfwSetInputMode(context.getWindowHandle(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
         }
     }
-    
+
     /**
      * Get the last delta in x (pixel).
      * @return the last delta in x (pixel).
@@ -193,7 +193,7 @@ public class GlfwMouseInputVR implements MouseInput {
     public int getLastDeltaX() {
         return xDelta;
     }
-    
+
     /**
      * Get the last delta in y (pixel).
      * @return the last delta in y (pixel).
@@ -202,7 +202,7 @@ public class GlfwMouseInputVR implements MouseInput {
     public int getLastDeltaY() {
         return yDelta;
     }
-    
+
     /**
      * Clear the last x and y deltas.
      * @see #getLastDeltaX()
@@ -212,7 +212,7 @@ public class GlfwMouseInputVR implements MouseInput {
         xDelta = 0;
         yDelta = 0;
     }
-    
+
     /**
      * Check if the input is initialized.
      * @return <code>true</code> if the input is initialized and <code>false</code> otherwise.
@@ -243,11 +243,11 @@ public class GlfwMouseInputVR implements MouseInput {
         if (!context.isRenderable()) {
             return;
         }
-        
+
         cursorPosCallback.free();
         scrollCallback.free();
         mouseButtonCallback.free();
-        
+
         for (long glfwCursor : jmeToGlfwCursorMap.values()) {
             glfwDestroyCursor(glfwCursor);
         }

+ 87 - 92
jme3-vr/src/main/java/com/jme3/input/vr/AbstractVRMouseManager.java

@@ -21,50 +21,48 @@ import com.jme3.ui.Picture;
  *
  */
 public abstract class AbstractVRMouseManager implements VRMouseManager {
+    private static final Logger logger = Logger.getLogger(AbstractVRMouseManager.class.getName());
 
-	private static final Logger logger = Logger.getLogger(AbstractVRMouseManager.class.getName());
+    private VREnvironment environment = null;
 
-	private VREnvironment environment = null;
-	
     private boolean vrMouseEnabled = true;
     private boolean mouseAttached = false;
     private Picture mouseImage;
     private int recentCenterCount = 0;
-    
+
     protected final Vector2f cursorPos = new Vector2f();
-    
+
     private float ySize, sensitivity = 8f, acceleration = 2f;
 
     private boolean thumbstickMode;
     private float moveScale = 1f;
- 
+
     /**
      * Create a new AbstractVRMouseManager attached to the given {@link VREnvironment VR environment}.
      * @param environment the {@link VREnvironment VR environment} that this manager is attached to.
      */
     public AbstractVRMouseManager(VREnvironment environment) {
-    	this.environment = environment;
+        this.environment = environment;
     }
-    
+
     @Override
     public void initialize() {
-    	
-    	logger.config("Initializing VR mouse manager.");
-    	
+        logger.config("Initializing VR mouse manager.");
+
         // load default mouseimage
         mouseImage = new Picture("mouse");
         setImage("Common/Util/mouse.png");
         // hide default cursor by making it invisible
-        
+
         MouseInput mi = environment.getApplication().getContext().getMouseInput();
-        if( mi instanceof GlfwMouseInputVR ){       	
-        	((GlfwMouseInputVR)mi).hideActiveCursor();
+        if( mi instanceof GlfwMouseInputVR ){
+            ((GlfwMouseInputVR)mi).hideActiveCursor();
         }
         centerMouse();
-        
+
         logger.config("Initialized VR mouse manager [SUCCESS]");
     }
-    
+
     @Override
     public VREnvironment getVREnvironment() {
       return environment;
@@ -74,129 +72,126 @@ public abstract class AbstractVRMouseManager implements VRMouseManager {
     public void setVRMouseEnabled(boolean enabled) {
         vrMouseEnabled = enabled;
     }
-    
+
     @Override
     public void setThumbstickMode(boolean set) {
         thumbstickMode = set;
     }
-    
+
     @Override
     public boolean isThumbstickMode() {
         return thumbstickMode;
     }
-    
+
     @Override
     public void setSpeed(float sensitivity, float acceleration) {
         this.sensitivity = sensitivity;
         this.acceleration = acceleration;
     }
-    
+
     @Override
     public float getSpeedSensitivity() {
         return sensitivity;
     }
-    
+
     @Override
     public float getSpeedAcceleration() {
         return acceleration;
     }
-    
+
     @Override
     public float getMouseMoveScale() {
-    	return moveScale;
+        return moveScale;
     }
-    
+
     @Override
     public void setMouseMoveScale(float set) {
         moveScale = set;
     }
-    
+
     @Override
     public void setImage(String texture) {
-    	
-    	if (environment != null){
-    		
-    		if (environment.getApplication() != null){
-    			if( environment.isInVR() == false ){
-    	        	Texture tex = environment.getApplication().getAssetManager().loadTexture(texture);
-    	            mouseImage.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, true);
-    	            ySize = tex.getImage().getHeight();
-    	            mouseImage.setHeight(ySize);
-    	            mouseImage.setWidth(tex.getImage().getWidth());
-    	            mouseImage.getMaterial().getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
-    	            mouseImage.getMaterial().getAdditionalRenderState().setDepthWrite(false);
-    	        } else {
-    	        	Texture tex = environment.getApplication().getAssetManager().loadTexture(texture);
-    	            mouseImage.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, true);
-    	            ySize = tex.getImage().getHeight();
-    	            mouseImage.setHeight(ySize);
-    	            mouseImage.setWidth(tex.getImage().getWidth());
-    	            mouseImage.getMaterial().getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
-    	            mouseImage.getMaterial().getAdditionalRenderState().setDepthWrite(false);
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    		
-    	} else {
+        if (environment != null){
+
+            if (environment.getApplication() != null){
+                if( environment.isInVR() == false ){
+                    Texture tex = environment.getApplication().getAssetManager().loadTexture(texture);
+                    mouseImage.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, true);
+                    ySize = tex.getImage().getHeight();
+                    mouseImage.setHeight(ySize);
+                    mouseImage.setWidth(tex.getImage().getWidth());
+                    mouseImage.getMaterial().getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
+                    mouseImage.getMaterial().getAdditionalRenderState().setDepthWrite(false);
+                } else {
+                    Texture tex = environment.getApplication().getAssetManager().loadTexture(texture);
+                    mouseImage.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, true);
+                    ySize = tex.getImage().getHeight();
+                    mouseImage.setHeight(ySize);
+                    mouseImage.setWidth(tex.getImage().getWidth());
+                    mouseImage.getMaterial().getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
+                    mouseImage.getMaterial().getAdditionalRenderState().setDepthWrite(false);
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+
+        } else {
           throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	} 
+        }
     }
 
-	
+
     @Override
     public Vector2f getCursorPosition() {
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    			 if( environment.isInVR() ) {
-    		            return cursorPos;
-    		        }
-    		        
-    		        return environment.getApplication().getInputManager().getCursorPosition();
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+
+        if (environment != null){
+            if (environment.getApplication() != null){
+                 if( environment.isInVR() ) {
+                        return cursorPos;
+                    }
+
+                    return environment.getApplication().getInputManager().getCursorPosition();
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     @Override
     public void centerMouse() {
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    	        // set mouse in center of the screen if newly added
-    	        Vector2f size = environment.getVRGUIManager().getCanvasSize();
-    	        MouseInput mi = environment.getApplication().getContext().getMouseInput();
-    	        AppSettings as = environment.getApplication().getContext().getSettings();
-    	        if( mi instanceof GlfwMouseInputVR ) ((GlfwMouseInputVR)mi).setCursorPosition((int)(as.getWidth() / 2f), (int)(as.getHeight() / 2f));
-    	        if( environment.isInVR() ) {
-    	            cursorPos.x = size.x / 2f;
-    	            cursorPos.y = size.y / 2f;
-    	            recentCenterCount = 2;
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (environment != null){
+            if (environment.getApplication() != null){
+                // set mouse in center of the screen if newly added
+                Vector2f size = environment.getVRGUIManager().getCanvasSize();
+                MouseInput mi = environment.getApplication().getContext().getMouseInput();
+                AppSettings as = environment.getApplication().getContext().getSettings();
+                if( mi instanceof GlfwMouseInputVR ) ((GlfwMouseInputVR)mi).setCursorPosition((int)(as.getWidth() / 2f), (int)(as.getHeight() / 2f));
+                if( environment.isInVR() ) {
+                    cursorPos.x = size.x / 2f;
+                    cursorPos.y = size.y / 2f;
+                    recentCenterCount = 2;
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
-    	
+        }
     }
-    
+
     @Override
     public void update(float tpf) {
         // if we are showing the cursor, add our picture as it
         if( vrMouseEnabled && environment.getApplication().getInputManager().isCursorVisible() ) {
             if(!mouseAttached) {
                 mouseAttached = true;
-            	environment.getApplication().getGuiViewPort().attachScene(mouseImage);         
+                environment.getApplication().getGuiViewPort().attachScene(mouseImage);
                 centerMouse();
                 // the "real" mouse pointer should stay hidden
                 if (environment.getApplication().getContext() instanceof LwjglWindow){
-                	GLFW.glfwSetInputMode(((LwjglWindow)environment.getApplication().getContext()).getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED);
+                    GLFW.glfwSetInputMode(((LwjglWindow)environment.getApplication().getContext()).getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED);
                 }
             }
             // handle mouse movements, which may be in addition to (or exclusive from) tracked movement
@@ -216,9 +211,9 @@ public abstract class AbstractVRMouseManager implements VRMouseManager {
             // ok, update the cursor graphic position
             Vector2f currentPos = getCursorPosition();
             mouseImage.setLocalTranslation(currentPos.x, currentPos.y - ySize, environment.getVRGUIManager().getGuiDistance() + 1f);
-		    
+
             mouseImage.updateGeometricState();
-            
+
         } else if(mouseAttached) {
             mouseAttached = false;
             environment.getApplication().getGuiViewPort().detachScene(mouseImage);
@@ -227,5 +222,5 @@ public abstract class AbstractVRMouseManager implements VRMouseManager {
             boolean cursorVisible = environment.getApplication().getInputManager().isCursorVisible();
             environment.getApplication().getContext().getMouseInput().setCursorVisible(cursorVisible);
         }
-    }  
+    }
 }

+ 53 - 63
jme3-vr/src/main/java/com/jme3/input/vr/AbstractVRViewManager.java

@@ -16,161 +16,154 @@ import com.jme3.shadow.VRDirectionalLightShadowRenderer;
 import com.jme3.texture.Texture2D;
 
 /**
- * A VR view manager. This class holds methods that enable to submit 3D views to the VR compositor. 
+ * A VR view manager. This class holds methods that enable to submit 3D views to the VR compositor.
  * System-dependent classes should extend this one.
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public abstract class AbstractVRViewManager implements VRViewManager {
-
-	
-	//private static final Logger logger = Logger.getLogger(AbstractVRViewManager.class.getName());
+    //private static final Logger logger = Logger.getLogger(AbstractVRViewManager.class.getName());
 
     protected  VREnvironment environment = null;
-    
+
     protected Camera leftCamera;
     protected ViewPort leftViewPort;
     protected FilterPostProcessor leftPostProcessor;
     protected Texture2D leftEyeTexture;
     protected Texture2D leftEyeDepth;
-    
+
     protected Camera rightCamera;
     protected ViewPort rightViewPort;
     protected FilterPostProcessor rightPostProcessor;
     protected Texture2D rightEyeTexture;
     protected Texture2D rightEyeDepth;
-	
-    protected ViewPort mirrorViewPort; 
 
-	private float resMult = 1f;
-    
+    protected ViewPort mirrorViewPort;
+
+    private float resMult = 1f;
+
     private float heightAdjustment;
-    
+
     @Override
     public Camera getLeftCamera() {
         return leftCamera;
     }
-    
+
     @Override
     public Camera getRightCamera() {
         return rightCamera;
     }
-    
+
     @Override
     public ViewPort getLeftViewPort() {
         return leftViewPort;
     }
-    
+
     @Override
     public ViewPort getRightViewPort() {
         return rightViewPort;
     }
-    
+
     /**
      * Get the {@link ViewPort view port} attached to the mirror display.
      * @return the view port attached to the mirror display.
      */
     @Override
     public ViewPort getMirrorViewPort() {
-		return mirrorViewPort;
-	}
+        return mirrorViewPort;
+    }
+
 
-    
     @Override
     public Texture2D getLeftTexture(){
       return leftEyeTexture;
     }
-    
+
     @Override
     public Texture2D getRightTexture(){
       return rightEyeTexture;
     }
-    
+
     @Override
     public Texture2D getLeftDepth(){
       return leftEyeDepth;
     }
-    
+
     @Override
     public Texture2D getRightDepth(){
       return rightEyeDepth;
     }
-    
+
     @Override
     public FilterPostProcessor getLeftPostProcessor(){
       return leftPostProcessor;
     }
-    
+
     @Override
     public FilterPostProcessor getRightPostProcessor(){
       return rightPostProcessor;
     }
-    
+
     @Override
     public float getResolutionMuliplier() {
         return resMult;
     }
-    
+
     @Override
     public void setResolutionMultiplier(float resMult) {
         this.resMult = resMult;
     }
-    
+
     @Override
     public float getHeightAdjustment() {
         return heightAdjustment;
     }
-    
+
     @Override
     public void setHeightAdjustment(float amount) {
         heightAdjustment = amount;
     }
-    
+
     @Override
     public VREnvironment getVREnvironment(){
-    	return environment;
+        return environment;
     }
-    
+
     /**
      * Handles moving filters from the main view to each eye
      */
     @Override
     public void moveScreenProcessingToEyes() {
-    	
-    	if (environment != null){
+        if (environment != null){
             if( getRightViewPort() == null ){
-            	return;
+                return;
             }
-            
+
             if (environment.getApplication() != null){
                 syncScreenProcessing(environment.getApplication().getViewPort());
                 environment.getApplication().getViewPort().clearProcessors();
             } else {
-            	throw new IllegalStateException("The VR environment is not attached to any application.");
+                throw new IllegalStateException("The VR environment is not attached to any application.");
             }
-            
-
-    	} else {
-    		throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
-    	
 
+        } else {
+            throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
+        }
     }
-    
+
     /**
      * Sets the two views to use the list of {@link SceneProcessor processors}.
      * @param sourceViewport the {@link ViewPort viewport} that contains the processors to use.
      */
     public void syncScreenProcessing(ViewPort sourceViewport) {
-    	
-    	if (environment != null){
-    		if(  getRightViewPort() == null ){
-    			return;
-    		}
-    		
-    		if (environment.getApplication() != null){
-    			// set up post-processing filters
+        if (environment != null){
+            if(  getRightViewPort() == null ){
+                return;
+            }
+
+            if (environment.getApplication() != null){
+                // set up post-processing filters
                 if( getRightPostProcessor() == null ) {
-                    rightPostProcessor = new FilterPostProcessor(environment.getApplication().getAssetManager());               
+                    rightPostProcessor = new FilterPostProcessor(environment.getApplication().getAssetManager());
                     leftPostProcessor =  new FilterPostProcessor(environment.getApplication().getAssetManager());
                 }
                 // clear out all filters & processors, to start from scratch
@@ -192,11 +185,11 @@ public abstract class AbstractVRViewManager implements VRViewManager {
                                 // just remove this filter, we will add it at the end manually
                                 ((FilterPostProcessor)sceneProcessor).removeFilter(f);
                             } else {
-                            	getLeftPostProcessor().addFilter(f);
+                                getLeftPostProcessor().addFilter(f);
                                 // clone to the right
                                 Filter f2;
                                 if(f instanceof FogFilter){
-                                    f2 = FilterUtil.cloneFogFilter((FogFilter)f); 
+                                    f2 = FilterUtil.cloneFogFilter((FogFilter)f);
                                 } else if (f instanceof CartoonSSAO ) {
                                     f2 = new CartoonSSAO((CartoonSSAO)f);
                                 } else if (f instanceof SSAOFilter){
@@ -205,7 +198,7 @@ public abstract class AbstractVRViewManager implements VRViewManager {
                                     f2 = FilterUtil.cloneDirectionalLightShadowFilter(environment.getApplication().getAssetManager(), (DirectionalLightShadowFilter)f);
                                 } else {
                                     f2 = f; // dof, bloom, light scattering etc.
-                                }                    
+                                }
                                 getRightPostProcessor().addFilter(f2);
                             }
                         }
@@ -222,15 +215,12 @@ public abstract class AbstractVRViewManager implements VRViewManager {
                 // make sure each has a translucent filter renderer
                 getLeftPostProcessor().addFilter(new TranslucentBucketFilter());
                 getRightPostProcessor().addFilter(new TranslucentBucketFilter());
-    		} else {
-            	throw new IllegalStateException("The VR environment is not attached to any application.");
+            } else {
+                throw new IllegalStateException("The VR environment is not attached to any application.");
             }
-    		
-            
-    	} else {
-    		throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
-    	
-        
+
+        } else {
+            throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
+        }
     }
 }

+ 21 - 22
jme3-vr/src/main/java/com/jme3/input/vr/HmdType.java

@@ -6,10 +6,9 @@ package com.jme3.input.vr;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public enum HmdType {
-	
-	/**
-	 * <a href="https://www.vive.com/fr/">HTC vive</a> Head Mounted Device (HMD).
-	 */
+    /**
+     * <a href="https://www.vive.com/fr/">HTC vive</a> Head Mounted Device (HMD).
+     */
     HTC_VIVE,
 
     /**
@@ -20,48 +19,48 @@ public enum HmdType {
     /**
      * <a href="https://www3.oculus.com/en-us/rift/">Oculus Rift</a> Head Mounted Device (HMD).
      */
-    OCULUS_RIFT, 
-    
+    OCULUS_RIFT,
+
     /**
      * <a href="http://www.osvr.org/">OSVR</a> generic Head Mounted Device (HMD).
      */
-    OSVR, 
-    
+    OSVR,
+
     /**
      * <a href="https://www.getfove.com/">FOVE</a> Head Mounted Device (HMD).
      */
-    FOVE, 
-    
+    FOVE,
+
     /**
      * <a href="http://www.starvr.com/">STARVR</a> Head Mounted Device (HMD).
      */
-    STARVR, 
-    
+    STARVR,
+
     /**
      * <a href="http://gamefacelabs.com/">GameFace</a> Head Mounted Device (HMD).
      */
-    GAMEFACE, 
-    
+    GAMEFACE,
+
     /**
      * <a href="https://www.playstation.com/en-us/explore/playstation-vr/">PlayStation VR</a> (formerly Morpheus) Head Mounted Device (HMD).
      */
-    MORPHEUS, 
-    
+    MORPHEUS,
+
     /**
      * <a href="http://www.samsung.com/fr/galaxynote4/gear-vr/">Samsung GearVR</a> Head Mounted Device (HMD).
      */
-    GEARVR, 
-    
+    GEARVR,
+
     /**
      * a null Head Mounted Device (HMD).
      */
-    NULL, 
-    
+    NULL,
+
     /**
      * a none Head Mounted Device (HMD).
      */
-    NONE, 
-    
+    NONE,
+
     /**
      * a not referenced Head Mounted Device (HMD).
      */

+ 31 - 33
jme3-vr/src/main/java/com/jme3/input/vr/VRAPI.java

@@ -12,50 +12,49 @@ import com.jme3.renderer.Camera;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public interface VRAPI {
-    
-	/**
-	 * Initialize this object from a VR system. All the native bindings to underlying VR system should be done within this method.
-	 * @return <code>true</code> if the initialization is a success and <code>false</code> otherwise.
-	 */
+    /**
+     * Initialize this object from a VR system. All the native bindings to underlying VR system should be done within this method.
+     * @return <code>true</code> if the initialization is a success and <code>false</code> otherwise.
+     */
     public boolean initialize();
-    
+
     /**
      * Initialize the VR compositor that will be used for rendering.
      * @param allowed <code>true</code> if the use of VR compositor is allowed and <code>false</code> otherwise.
      * @return <code>true</code> if the initialization is a success and <code>false</code> otherwise.
      */
     public boolean initVRCompositor(boolean allowed);
-       
+
     /**
      * Get the object that wraps natively the VR system.
      * @return the object that wraps natively the VR system.
      */
     public Object getVRSystem();
-    
+
     /**
      * Get the object that wraps natively the VR compositor.
      * @return the object that wraps natively the VR system.
      */
     public Object getCompositor();
-    
+
     /**
      * Get the name of the underlying VR system.
      * @return the name of the underlying VR system.
      */
     public String getName();
-    
+
     /**
      * Get the input provided by the underlying VR system.
      * @return the input provided by the underlying VR system.
      */
     public VRInputAPI getVRinput();
-    
+
     /**
      * Flip the left and right eye.
      * @param set <code>true</code> if the eyes has to be flipped and <code>false</code> otherwise.
      */
     public void setFlipEyes(boolean set);
-    
+
     /**
      * Set if latency information has to be logged.
      * @param set <code>true</code> if latency information has to be logged and <code>false</code> otherwise.
@@ -67,7 +66,7 @@ public interface VRAPI {
      * @return the Head Mounted DEvice (HMD) display frequency.
      */
     public int getDisplayFrequency();
-    
+
     /**
      * Close the link with underlying VR system and free all attached resources.
      */
@@ -91,7 +90,7 @@ public interface VRAPI {
      * @param store the size of a Head Mounted Device (HMD) rendering area in pixels (modified).
      */
     public void getRenderSize(Vector2f store);
-    
+
     //public float getFOV(int dir);
 
     /**
@@ -99,7 +98,7 @@ public interface VRAPI {
      * @return the Head Mounted Device (HMD) interpupilar distance in meters.
      */
     public float getInterpupillaryDistance();
-    
+
     /**
      * Get the Head Mounted Device (HMD) orientation.
      * @return the Head Mounted Device (HMD) orientation.
@@ -111,14 +110,14 @@ public interface VRAPI {
      * @return the Head Mounted Device (HMD) orientation.
      */
     public Vector3f getPosition();
-    
+
     /**
      * Get the Head Mounted Device (HMD) position and orientation.
      * @param storePos the Head Mounted Device (HMD) position (modified).
      * @param storeRot the Head Mounted Device (HMD) rotation (modified).
      */
     public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot);
-    
+
     /**
      * Update Head Mounted Device (HMD) pose internal storage. This method should be called before other calls to HMD position/orientation access.
      */
@@ -130,56 +129,55 @@ public interface VRAPI {
      * @return the Head Mounted Device (HMD) left eye projection matrix.
      */
     public Matrix4f getHMDMatrixProjectionLeftEye(Camera cam);
-        
+
     /**
      * Get the Head Mounted Device (HMD) right eye projection matrix.
      * @param cam the camera attached to the right eye.
      * @return the Head Mounted Device (HMD) right eye projection matrix.
      */
     public Matrix4f getHMDMatrixProjectionRightEye(Camera cam);
-    
+
     /**
      * Get the Head Mounted Device (HMD) left eye pose (position of the eye from the head) as a {@link Vector3f vector}.
      * @return the Head Mounted Device (HMD) left eye pose as a {@link Vector3f vector}.
      */
     public Vector3f getHMDVectorPoseLeftEye();
-    
+
     /**
      * Get the Head Mounted Device (HMD) right eye pose (position of the eye from the head) as a {@link Vector3f vector}.
      * @return the Head Mounted Device (HMD) right eye pose as a {@link Vector3f vector}.
      */
     public Vector3f getHMDVectorPoseRightEye();
-    
+
     /**
-     * Returns the transform between the view space and left eye space. 
-     * Eye space is the per-eye flavor of view space that provides stereo disparity. 
-     * Instead of Model * View * Projection the model is Model * View * Eye * Projection. 
+     * Returns the transform between the view space and left eye space.
+     * Eye space is the per-eye flavor of view space that provides stereo disparity.
+     * Instead of Model * View * Projection the model is Model * View * Eye * Projection.
      * Normally View and Eye will be multiplied together and treated as View.
      * This matrix incorporates the user's interpupillary distance (IPD).
-     * @return the transform between the view space and eye space. 
+     * @return the transform between the view space and eye space.
      */
     public Matrix4f getHMDMatrixPoseLeftEye();
-    
+
     /**
-     * Returns the transform between the view space and right eye space. 
-     * Eye space is the per-eye flavor of view space that provides stereo disparity. 
-     * Instead of Model * View * Projection the model is Model * View * Eye * Projection. 
+     * Returns the transform between the view space and right eye space.
+     * Eye space is the per-eye flavor of view space that provides stereo disparity.
+     * Instead of Model * View * Projection the model is Model * View * Eye * Projection.
      * Normally View and Eye will be multiplied together and treated as View.
      * This matrix incorporates the user's interpupillary distance (IPD).
-     * @return the transform between the view space and eye space. 
+     * @return the transform between the view space and eye space.
      */
     public Matrix4f getHMDMatrixPoseRightEye();
-    
+
     /**
      * Get the Head Mounted Device (HMD) type.
      * @return the Head Mounted Device (HMD) type.
      */
     public HmdType getType();
-    
+
     /**
      * Get the seated to absolute position.
      * @return the seated to absolute position.
      */
     public Vector3f getSeatedToAbsolutePosition();
-    
 }

+ 35 - 37
jme3-vr/src/main/java/com/jme3/input/vr/VRInputAPI.java

@@ -10,15 +10,14 @@ import com.jme3.math.Vector3f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public interface VRInputAPI {
-
-	/**
-	 * Check if the given button is down (more generally if the given input type is activated).
-	 * @param controllerIndex the index of the controller to check.
-	 * @param checkButton the button / input to check.
-	 * @return <code>true</code> if the button / input is down / activated and <code>false</code> otherwise.
-	 */
+    /**
+     * Check if the given button is down (more generally if the given input type is activated).
+     * @param controllerIndex the index of the controller to check.
+     * @param checkButton the button / input to check.
+     * @return <code>true</code> if the button / input is down / activated and <code>false</code> otherwise.
+     */
     public boolean isButtonDown(int controllerIndex, VRInputType checkButton);
-    
+
     /**
      * Check if the given button / input from the given controller has been just pressed / activated.
      * @param controllerIndex the index of the controller.
@@ -26,13 +25,13 @@ public interface VRInputAPI {
      * @return <code>true</code> if the given button / input from the given controller has been just pressed / activated and <code>false</code> otherwise.
      */
     public boolean wasButtonPressedSinceLastCall(int controllerIndex, VRInputType checkButton);
-    
+
     /**
      * Reset the current activation of the inputs. After a call to this method, all input activation is considered as new activation.
      * @see #wasButtonPressedSinceLastCall(int, VRInputType)
      */
     public void resetInputSinceLastCall();
-    
+
     /**
      * Get the controller axis delta from the last value.
      * @param controllerIndex the index of the controller.
@@ -40,7 +39,7 @@ public interface VRInputAPI {
      * @return the controller axis delta from the last call.
      */
     public Vector2f getAxisDeltaSinceLastCall(int controllerIndex, VRInputType forAxis);
-    
+
     /**
      * Get the controller velocity on all axes.
      * @param controllerIndex the index of the controller.
@@ -48,7 +47,7 @@ public interface VRInputAPI {
      * @see #getAngularVelocity(int)
      */
     public Vector3f getVelocity(int controllerIndex);
-    
+
     /**
      * Get the controller angular velocity on all axes.
      * @param controllerIndex the index of the controller.
@@ -56,9 +55,9 @@ public interface VRInputAPI {
      * @see #getVelocity(int)
      */
     public Vector3f getAngularVelocity(int controllerIndex);
-    
+
     /**
-     * Get the axis value for the given input on the given controller. 
+     * Get the axis value for the given input on the given controller.
      * This value is the {@link #getAxisRaw(int, VRInputType) raw value} multiplied by the  {@link #getAxisMultiplier() axis multiplier}.
      * @param controllerIndex the index of the controller.
      * @param forAxis the axis.
@@ -67,9 +66,9 @@ public interface VRInputAPI {
      * @see #getAxisMultiplier()
      */
     public Vector2f getAxis(int controllerIndex, VRInputType forAxis);
-    
+
     /**
-     * Get the axis value for the given input on the given controller. 
+     * Get the axis value for the given input on the given controller.
      * @param controllerIndex the index of the controller.
      * @param forAxis the axis.
      * @return the axis value for the given input on the given controller.
@@ -82,14 +81,14 @@ public interface VRInputAPI {
      * @return <code>true</code> if the initialization is successful and <code>false</code> otherwise.
      */
     public boolean init();
-    
+
     /**
      * Get the number of tracked controllers (for example, hand controllers) attached to the VR system.
      * @return the number of controllers attached to the VR system.
      * @see #getTrackedController(int)
      */
     public int getTrackedControllerCount();
-    
+
     /**
      * Get a tracked controller (for example, a hand controller) that is attached to the VR system.
      * @param index the index of the controller.
@@ -97,62 +96,62 @@ public interface VRInputAPI {
      * @see #getTrackedControllerCount()
      */
     public VRTrackedController getTrackedController(int index);
-    
+
     /**
-     * Update the connected controllers. 
+     * Update the connected controllers.
      * This method should be used just after the initialization of the input.
      */
     public void updateConnectedControllers();
-    
+
     /**
      * Update the controller states.
      * This method should be called before accessing any controller data.
      */
     public void updateControllerStates();
-    
+
     /**
      * Get the native wrapping of a controller state.
      * @param index the index of the controller.
      * @return the native wrapping of a controller state.
      */
     public Object getRawControllerState(int index);
-    
+
     /**
      * Swap the two hands (exchange the hands controller 1 and 2 indices).
      */
     public void swapHands();
-    
+
     /**
-     * Get the controller axis multiplier. 
+     * Get the controller axis multiplier.
      * The controller axis raw data (trackpad, trigger, ...) value is multiplied by the one given in parameter.
-     * @return the controller axis multiplier. 
+     * @return the controller axis multiplier.
      * @see #setAxisMultiplier(float)
      */
     public float getAxisMultiplier();
-    
+
     /**
-     * Set the controller axis multiplier. 
+     * Set the controller axis multiplier.
      * The controller axis raw data (trackpad, trigger, ...) value is multiplied by the one given in parameter.
-     * @param set the controller axis multiplier. 
+     * @param set the controller axis multiplier.
      * @see #getAxisMultiplier()
      */
     public void setAxisMultiplier(float set);
-    
+
     //public Matrix4f getPoseForInputDevice(int index);
-    
+
     /**
      * Check if the VR system has the focus and if it's not used by other process.
      * @return <code>true</code> if the VR system has the focus and <code>false</code> otherwise.
      */
     public boolean isInputFocused();
-    
+
     /**
      * Check if the input device is actually tracked (i-e if we can obtain a pose from the input).
      * @param index the index of the controller.
      * @return <code>true</code> if the input device is actually tracked and <code>false</code> otherwise.
      */
     public boolean isInputDeviceTracking(int index);
-    
+
     /**
      * Get the orientation of the input.
      * @param index the index of the controller.
@@ -166,7 +165,7 @@ public interface VRInputAPI {
      * @return the position of the input.
      */
     public Vector3f getPosition(int index);
-    
+
     /**
      * Get where is the controller pointing, after all rotations are combined.
      * This position should include observer rotation from the VR application.
@@ -174,7 +173,7 @@ public interface VRInputAPI {
      * @return the rotation of the input after all positional tracking is complete.
      */
     public Quaternion getFinalObserverRotation(int index);
-    
+
     /**
      * Get the position of the input after all positional tracking is complete.
      * This position should include observer position from the VR application.
@@ -182,12 +181,11 @@ public interface VRInputAPI {
      * @return the position of the input after all positional tracking is complete.
      */
     public Vector3f getFinalObserverPosition(int index);
-    
+
     /**
      * Trigger a haptic pulse on the selected controller for the duration given in parameters (in seconds).
      * @param controllerIndex the index of the controller.
      * @param seconds the duration of the pulse in seconds.
      */
     public void triggerHapticPulse(int controllerIndex, float seconds);
-    
 }

+ 120 - 121
jme3-vr/src/main/java/com/jme3/input/vr/VRInputType.java

@@ -7,132 +7,131 @@ package com.jme3.input.vr;
  *
  */
 public enum VRInputType {
-	
-	/**
-	 * an HTC vive trigger axis (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
-	 */
-    ViveTriggerAxis(0), 
-    
-	/**
-	 * an HTC vive trackpad axis (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
-	 */
-    ViveTrackpadAxis(1), 
-    
-	/**
-	 * an HTC vive grip button (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
-	 */
-    ViveGripButton(2), 
-    
-	/**
-	 * an HTC vive menu button (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
-	 */
+    /**
+     * an HTC vive trigger axis (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
+     */
+    ViveTriggerAxis(0),
+
+    /**
+     * an HTC vive trackpad axis (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
+     */
+    ViveTrackpadAxis(1),
+
+    /**
+     * an HTC vive grip button (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
+     */
+    ViveGripButton(2),
+
+    /**
+     * an HTC vive menu button (about <a href="https://www.vive.com/us/support/category_howto/720435.html">Vive controller</a>).
+     */
     ViveMenuButton(3),
 
-	/**
-	 * The thumbstick on the Oculus Touch controllers.
-	 * 
-	 * Unlike the Vive controllers where the touchpad is commonly used
-	 * as a virtual DPad, you should avoid using the thumbstick for purposes
-	 * that do not require analog input.
-	 */
-	OculusThumbstickAxis(0),
-
-	/**
-	 * The trigger button on the Oculus Touch controllers.
-	 * 
-	 * This is the button under the user's index finger, and should not be used to
-	 * pick up objects. See the 
-	 * <a href="https://developer.oculus.com/documentation/pcsdk/latest/concepts/dg-input-touch-overview/"
-	 * >Oculus Developer</a> documentation.
-	 */
-	OculusTriggerAxis(0),
-
-	/**
-	 * The 'grab' button on the Oculus Touch controllers.
-	 * 
-	 * This button should only (unless you have a compelling reason otherwise) be used to pick up objects.
-	 */
-	OculusGripAxis(0),
-
-	/**
-	 * The upper buttons on the Oculus Touch controllers - B on the right controller, and Y on the left.
-	 */
-	OculusTopButton(org.lwjgl.ovr.OVR.ovrButton_B | org.lwjgl.ovr.OVR.ovrButton_Y),
-
-	/**
-	 * The lower (not counting menu) buttons on the Oculus Touch
-	 * controllers - A on the right controller, and X on the left.
-	 */
-	OculusBottomButton(org.lwjgl.ovr.OVR.ovrButton_A | org.lwjgl.ovr.OVR.ovrButton_X),
-
-	/**
-	 * The 'click' button on the Oculus Touch thumbsticks.
-	 */
-	OculusThumbstickButton(org.lwjgl.ovr.OVR.ovrButton_LThumb | org.lwjgl.ovr.OVR.ovrButton_RThumb),
-
-	/**
-	 * The game-usable menu button, under and to the left of the 'X' button on the left controller.
-	 * 
-	 * Most games use this to pause - it preferably should be used for at least that purpose, and is
-	 * uncomfortable to rest your thumb on (in games where you suddenly have to pause/open a menu).
-	 */
-	OculusMenuButton(org.lwjgl.ovr.OVR.ovrButton_Enter),
-
-	/**
-	 * The capacitive touch sensors on the top buttons (Y and B) of the Oculus Touch.
-	 */
-	OculusTopTouch(org.lwjgl.ovr.OVR.ovrTouch_B | org.lwjgl.ovr.OVR.ovrTouch_Y),
-
-	/**
-	 * The capacitive touch sensors on the lower buttons (X and A) of the Oculus Touch.
-	 */
-	OculusBottomTouch(org.lwjgl.ovr.OVR.ovrTouch_A | org.lwjgl.ovr.OVR.ovrTouch_X),
-
-	/**
-	 * The capacitive touch sensors on the thumbsticks of the Oculus Touch.
-	 */
-	OculusThumbstickTouch(org.lwjgl.ovr.OVR.ovrTouch_LThumb | org.lwjgl.ovr.OVR.ovrTouch_RThumb),
-
-	/**
-	 * The capacitive touch sensors on the thumbrests of the Oculus Touch - this is a textured pad
+    /**
+     * The thumbstick on the Oculus Touch controllers.
+     *
+     * Unlike the Vive controllers where the touchpad is commonly used
+     * as a virtual DPad, you should avoid using the thumbstick for purposes
+     * that do not require analog input.
+     */
+    OculusThumbstickAxis(0),
+
+    /**
+     * The trigger button on the Oculus Touch controllers.
+     *
+     * This is the button under the user's index finger, and should not be used to
+     * pick up objects. See the
+     * <a href="https://developer.oculus.com/documentation/pcsdk/latest/concepts/dg-input-touch-overview/"
+     * >Oculus Developer</a> documentation.
+     */
+    OculusTriggerAxis(0),
+
+    /**
+     * The 'grab' button on the Oculus Touch controllers.
+     *
+     * This button should only (unless you have a compelling reason otherwise) be used to pick up objects.
+     */
+    OculusGripAxis(0),
+
+    /**
+     * The upper buttons on the Oculus Touch controllers - B on the right controller, and Y on the left.
+     */
+    OculusTopButton(org.lwjgl.ovr.OVR.ovrButton_B | org.lwjgl.ovr.OVR.ovrButton_Y),
+
+    /**
+     * The lower (not counting menu) buttons on the Oculus Touch
+     * controllers - A on the right controller, and X on the left.
+     */
+    OculusBottomButton(org.lwjgl.ovr.OVR.ovrButton_A | org.lwjgl.ovr.OVR.ovrButton_X),
+
+    /**
+     * The 'click' button on the Oculus Touch thumbsticks.
+     */
+    OculusThumbstickButton(org.lwjgl.ovr.OVR.ovrButton_LThumb | org.lwjgl.ovr.OVR.ovrButton_RThumb),
+
+    /**
+     * The game-usable menu button, under and to the left of the 'X' button on the left controller.
+     *
+     * Most games use this to pause - it preferably should be used for at least that purpose, and is
+     * uncomfortable to rest your thumb on (in games where you suddenly have to pause/open a menu).
+     */
+    OculusMenuButton(org.lwjgl.ovr.OVR.ovrButton_Enter),
+
+    /**
+     * The capacitive touch sensors on the top buttons (Y and B) of the Oculus Touch.
+     */
+    OculusTopTouch(org.lwjgl.ovr.OVR.ovrTouch_B | org.lwjgl.ovr.OVR.ovrTouch_Y),
+
+    /**
+     * The capacitive touch sensors on the lower buttons (X and A) of the Oculus Touch.
+     */
+    OculusBottomTouch(org.lwjgl.ovr.OVR.ovrTouch_A | org.lwjgl.ovr.OVR.ovrTouch_X),
+
+    /**
+     * The capacitive touch sensors on the thumbsticks of the Oculus Touch.
+     */
+    OculusThumbstickTouch(org.lwjgl.ovr.OVR.ovrTouch_LThumb | org.lwjgl.ovr.OVR.ovrTouch_RThumb),
+
+    /**
+     * The capacitive touch sensors on the thumbrests of the Oculus Touch - this is a textured pad
      * on the Oculus Touch controller next to the ABXY buttons for users to reset their thumbs on.
-	 * 
-	 * While it probably goes without saying, only use this for gesture support and do not bind game
-	 * elements to it.
-	 */
-	OculusThumbrestTouch(org.lwjgl.ovr.OVR.ovrTouch_LThumbRest | org.lwjgl.ovr.OVR.ovrTouch_RThumbRest),
-
-	/**
-	 * The state of a software calculation based on the capacitive touch sensor values that determine if
-	 * the user has lifted their thumb off the controller, and can be used for gesture support.
-	 * 
-	 * This should be used instead of calculating this yourself based on the touch results of all the other
-	 * parts of the controller.
-	 */
-	OculusThumbUp(org.lwjgl.ovr.OVR.ovrTouch_LThumbUp | org.lwjgl.ovr.OVR.ovrTouch_RThumbUp),
-
-	/**
-	 * Is the user resting their finger on the trigger of an Oculus Touch controller?
-	 */
-	OculusIndexTouch(org.lwjgl.ovr.OVR.ovrTouch_LIndexPointing | org.lwjgl.ovr.OVR.ovrTouch_RIndexPointing),
-
-	/**
-	 * Is the user pointing their finger forwards, as if to press a button?
-	 * 
-	 * This is internally calculated from proximity and filtering is applied - it should be used rather
-	 * than !OculusIndexTouch, as it will probably lead to better results.
-	 */
-	OculusIndexPointing(org.lwjgl.ovr.OVR.ovrTouch_LIndexPointing | org.lwjgl.ovr.OVR.ovrTouch_RIndexPointing);
-    
+     *
+     * While it probably goes without saying, only use this for gesture support and do not bind game
+     * elements to it.
+     */
+    OculusThumbrestTouch(org.lwjgl.ovr.OVR.ovrTouch_LThumbRest | org.lwjgl.ovr.OVR.ovrTouch_RThumbRest),
+
+    /**
+     * The state of a software calculation based on the capacitive touch sensor values that determine if
+     * the user has lifted their thumb off the controller, and can be used for gesture support.
+     *
+     * This should be used instead of calculating this yourself based on the touch results of all the other
+     * parts of the controller.
+     */
+    OculusThumbUp(org.lwjgl.ovr.OVR.ovrTouch_LThumbUp | org.lwjgl.ovr.OVR.ovrTouch_RThumbUp),
+
+    /**
+     * Is the user resting their finger on the trigger of an Oculus Touch controller?
+     */
+    OculusIndexTouch(org.lwjgl.ovr.OVR.ovrTouch_LIndexPointing | org.lwjgl.ovr.OVR.ovrTouch_RIndexPointing),
+
+    /**
+     * Is the user pointing their finger forwards, as if to press a button?
+     *
+     * This is internally calculated from proximity and filtering is applied - it should be used rather
+     * than !OculusIndexTouch, as it will probably lead to better results.
+     */
+    OculusIndexPointing(org.lwjgl.ovr.OVR.ovrTouch_LIndexPointing | org.lwjgl.ovr.OVR.ovrTouch_RIndexPointing);
+
     /**
      * The value that codes the input type.
      */
-	private final int value;
-    
-	/**
-	 * Construct a new input type with the given code.
-	 * @param value the code of the input type.
-	 */
+    private final int value;
+
+    /**
+     * Construct a new input type with the given code.
+     * @param value the code of the input type.
+     */
     private VRInputType(int value) {
         this.value = value;
     }
@@ -143,5 +142,5 @@ public enum VRInputType {
      */
     public int getValue() {
         return value;
-    }        
+    }
 }

+ 14 - 16
jme3-vr/src/main/java/com/jme3/input/vr/VRMouseManager.java

@@ -9,13 +9,11 @@ import com.jme3.math.Vector2f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public interface VRMouseManager {
-
-	
   /**
    * Initialize the VR mouse manager.
    */
   public void initialize();
-  
+
   /**
    * Get the {@link VREnvironment VR Environment} to which this manager is attached.
    * @return the {@link VREnvironment VR Environment} to which this manager is attached.
@@ -27,19 +25,19 @@ public interface VRMouseManager {
    * @param enabled <code>true</code> if the mouse cursor should be displayed in VR and <code>false</code> otherwise.
    */
   public void setVRMouseEnabled(boolean enabled);
-  
+
   /**
    * Set if the VR device controller is used within thumb stick mode.
    * @param set <code>true</code> if the VR device controller is used within thumb stick mode and <code>false</code> otherwise.
    */
   public void setThumbstickMode(boolean set);
-  
+
   /**
    * Get if the VR device controller is used within thumb stick mode.
    * @return <code>true</code> if the VR device controller is used within thumb stick mode and <code>false</code> otherwise.
    */
   public boolean isThumbstickMode();
-  
+
   /**
    * Set the speed of the mouse.
    * @param sensitivity the sensitivity of the mouse.
@@ -48,41 +46,41 @@ public interface VRMouseManager {
    * @see #getSpeedSensitivity()
    */
   public void setSpeed(float sensitivity, float acceleration);
-  
+
   /**
    * Get the sensitivity of the mouse.
    * @return the sensitivity of the mouse.
    * @see #setSpeed(float, float)
    */
   public float getSpeedSensitivity();
-  
+
   /**
    * Get the acceleration of the mouse.
    * @return the acceleration of the mouse.
    * @see #setSpeed(float, float)
    */
   public float getSpeedAcceleration();
-  
+
   /**
    * Get the move scale.
    * return the move scale.
    * @see #setMouseMoveScale(float)
    */
   public float getMouseMoveScale();
-  
+
   /**
    * Set the mouse move scale.
    * @param set the mouse move scale.
    * @see #getMouseMoveScale()
    */
   public void setMouseMoveScale(float set);
-  
+
   /**
    * Set the image to use as mouse cursor. The given string describe an asset that the underlying application asset manager has to load.
    * @param texture the image to use as mouse cursor.
    */
   public void setImage(String texture);
-  
+
   /**
    * Update analog controller as it was a mouse controller.
    * @param inputIndex the index of the controller attached to the VR system.
@@ -92,20 +90,20 @@ public interface VRMouseManager {
    * @param tpf the time per frame.
    */
   public void updateAnalogAsMouse(int inputIndex, AnalogListener mouseListener, String mouseXName, String mouseYName, float tpf);
-  
+
   /**
    * Get the actual cursor position.
    * @return the actual cursor position.
    */
   public Vector2f getCursorPosition();
-  
+
   /**
    * Center the mouse on the display.
    */
   public void centerMouse();
-  
+
   /**
-   * Update the mouse manager. This method should not be called manually. 
+   * Update the mouse manager. This method should not be called manually.
    * The standard behavior for this method is to be called from the {@link VRViewManager#update(float) update method} of the attached {@link VRViewManager VR view manager}.
    * @param tpf the time per frame.
    */

+ 36 - 37
jme3-vr/src/main/java/com/jme3/input/vr/VRTrackedController.java

@@ -9,41 +9,40 @@ import com.jme3.math.Vector3f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public interface VRTrackedController {
-  
-	/**
-	 * Get the controller name.
-	 * @return the controller name.
-	 */
-	public String getControllerName();
-	
-	/**
-	 * Get the controller manufacturer.
-	 * @return the controller manufacturer.
-	 */
-	public String getControllerManufacturer();
-	
-	/**
-	 * Get the position of the tracked device. This value is the translation component of the device {@link #getPose() pose}.
-	 * @return the position of the tracked device.
-	 * @see #getOrientation()
-	 * @see #getPose()
-	 */
-	public Vector3f getPosition();
-	
-	/**
-	 * Get the orientation of the tracked device. This value is the rotation component of the device {@link #getPose() pose}.
-	 * @return the orientation of the tracked device.
-	 * @see #getPosition()
-	 * @see #getPose()
-	 */
-	public Quaternion getOrientation();
-	
-	/**
-	 * Get the pose of the tracked device. 
-	 * The pose is a 4x4 matrix than combine the {@link #getPosition() position} and the {@link #getOrientation() orientation} of the device.
-	 * @return the pose of the tracked device.
-	 * @see #getPosition()
-	 * @see #getOrientation()
-	 */
-	public Matrix4f getPose();
+    /**
+     * Get the controller name.
+     * @return the controller name.
+     */
+    public String getControllerName();
+
+    /**
+     * Get the controller manufacturer.
+     * @return the controller manufacturer.
+     */
+    public String getControllerManufacturer();
+
+    /**
+     * Get the position of the tracked device. This value is the translation component of the device {@link #getPose() pose}.
+     * @return the position of the tracked device.
+     * @see #getOrientation()
+     * @see #getPose()
+     */
+    public Vector3f getPosition();
+
+    /**
+     * Get the orientation of the tracked device. This value is the rotation component of the device {@link #getPose() pose}.
+     * @return the orientation of the tracked device.
+     * @see #getPosition()
+     * @see #getPose()
+     */
+    public Quaternion getOrientation();
+
+    /**
+     * Get the pose of the tracked device.
+     * The pose is a 4x4 matrix than combine the {@link #getPosition() position} and the {@link #getOrientation() orientation} of the device.
+     * @return the pose of the tracked device.
+     * @see #getPosition()
+     * @see #getOrientation()
+     */
+    public Matrix4f getPose();
 }

+ 66 - 73
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVR.java

@@ -18,27 +18,26 @@ import org.lwjgl.BufferUtils;
 import org.lwjgl.openvr.*;
 
 /**
- * A class that wraps an <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system. 
+ * A class that wraps an <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system.
  * @author reden - phr00t
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  * @author Rickard Edén
  */
 public class LWJGLOpenVR implements VRAPI {
-    
     private static final Logger logger = Logger.getLogger(LWJGLOpenVR.class.getName());
-	
+
     private static boolean initSuccess = false;
     private static boolean flipEyes    = false;
-    
+
     private IntBuffer hmdDisplayFrequency;
     private TrackedDevicePose.Buffer trackedDevicePose;
     protected TrackedDevicePose[] hmdTrackedDevicePoses;
-    
+
     protected IntBuffer hmdErrorStore = BufferUtils.createIntBuffer(1);
-    
+
     private final Quaternion rotStore = new Quaternion();
     private final Vector3f posStore = new Vector3f();
-    
+
     protected Matrix4f[] poseMatrices;
 
     private final Matrix4f hmdPose = Matrix4f.IDENTITY.clone();
@@ -46,15 +45,13 @@ public class LWJGLOpenVR implements VRAPI {
     private Matrix4f hmdProjectionRightEye;
     private Matrix4f hmdPoseLeftEye;
     private Matrix4f hmdPoseRightEye;
-    
+
     private Vector3f hmdPoseLeftEyeVec, hmdPoseRightEyeVec, hmdSeatToStand;
-    
+
     private LWJGLOpenVRInput VRinput;
-    
-    
+
     private VREnvironment environment = null;
-    
-    
+
     /**
      * Convert specific OpenVR {@link org.lwjgl.openvr.HmdMatrix34 HmdMatrix34} into JME {@link Matrix4f Matrix4f}
      * @param hmdMatrix the input matrix
@@ -62,13 +59,13 @@ public class LWJGLOpenVR implements VRAPI {
      * @return the converted matrix
      */
     public static Matrix4f convertSteamVRMatrix3ToMatrix4f(org.lwjgl.openvr.HmdMatrix34 hmdMatrix, Matrix4f mat){
-        mat.set(hmdMatrix.m(0), hmdMatrix.m(1), hmdMatrix.m(2), hmdMatrix.m(3), 
-                hmdMatrix.m(4), hmdMatrix.m(5), hmdMatrix.m(6), hmdMatrix.m(7), 
-                hmdMatrix.m(8), hmdMatrix.m(9), hmdMatrix.m(10), hmdMatrix.m(11), 
+        mat.set(hmdMatrix.m(0), hmdMatrix.m(1), hmdMatrix.m(2), hmdMatrix.m(3),
+                hmdMatrix.m(4), hmdMatrix.m(5), hmdMatrix.m(6), hmdMatrix.m(7),
+                hmdMatrix.m(8), hmdMatrix.m(9), hmdMatrix.m(10), hmdMatrix.m(11),
                 0f, 0f, 0f, 1f);
         return mat;
     }
-    
+
     /**
      * Convert specific OpenVR {@link org.lwjgl.openvr.HmdMatrix34 HmdMatrix34_t} into JME {@link Matrix4f Matrix4f}
      * @param hmdMatrix the input matrix
@@ -76,47 +73,47 @@ public class LWJGLOpenVR implements VRAPI {
      * @return the converted matrix
      */
     public static Matrix4f convertSteamVRMatrix4ToMatrix4f(org.lwjgl.openvr.HmdMatrix44 hmdMatrix, Matrix4f mat){
-        mat.set(hmdMatrix.m(0), hmdMatrix.m(1), hmdMatrix.m(2), hmdMatrix.m(3), 
+        mat.set(hmdMatrix.m(0), hmdMatrix.m(1), hmdMatrix.m(2), hmdMatrix.m(3),
                 hmdMatrix.m(4), hmdMatrix.m(5), hmdMatrix.m(6), hmdMatrix.m(7),
-                hmdMatrix.m(8), hmdMatrix.m(9), hmdMatrix.m(10), hmdMatrix.m(11), 
+                hmdMatrix.m(8), hmdMatrix.m(9), hmdMatrix.m(10), hmdMatrix.m(11),
                 hmdMatrix.m(12), hmdMatrix.m(13), hmdMatrix.m(14), hmdMatrix.m(15));
         return mat;
     }
-    
+
     /**
-     * Create a new <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system 
+     * Create a new <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system
      * attached to the given {@link VREnvironment VR environment}.
      * @param environment the VR environment to which this API is attached.
      */
     public LWJGLOpenVR(VREnvironment environment){
       this.environment = environment;
     }
-    
+
     @Override
     public LWJGLOpenVRInput getVRinput() {
         return VRinput;
     }
-    
+
     @Override
     public Object getVRSystem() {
         throw new UnsupportedOperationException("Not yet implemented!");
     }
-    
+
     @Override
     public Object getCompositor() {
         throw new UnsupportedOperationException("Not yet implemented!");
     }
-    
+
     @Override
     public String getName() {
         return "OpenVR/LWJGL";
     }
-    
+
     @Override
     public void setFlipEyes(boolean set) {
         flipEyes = set;
     }
-    
+
     @Override
     public void printLatencyInfoToConsole(boolean set) {
         // not implemented
@@ -127,16 +124,15 @@ public class LWJGLOpenVR implements VRAPI {
         if( hmdDisplayFrequency == null ) return 0;
         return hmdDisplayFrequency.get(0);
     }
-    
+
     @Override
     public boolean initialize() {
-    	
-    	logger.config("Initializing OpenVR system...");
-    	
+        logger.config("Initializing OpenVR system...");
+
         // Init the native linking to the OpenVR library.
-        
+
         int result = VR.VR_InitInternal(hmdErrorStore, VR.EVRApplicationType_VRApplication_Scene);
-        
+
         if(hmdErrorStore.get(0) != VR.EVRInitError_VRInitError_None) {
             logger.severe("OpenVR Initialize Result: " + VR.VR_GetVRInitErrorAsEnglishDescription(hmdErrorStore.get(0)));
             logger.severe("Initializing OpenVR system [FAILED]");
@@ -151,7 +147,7 @@ public class LWJGLOpenVR implements VRAPI {
 
             hmdDisplayFrequency = BufferUtils.createIntBuffer(1);
             hmdDisplayFrequency.put(VR.ETrackedDeviceProperty_Prop_DisplayFrequency_Float);
-            
+
             trackedDevicePose = TrackedDevicePose.create(VR.k_unMaxTrackedDeviceCount);
             hmdTrackedDevicePoses = new TrackedDevicePose[VR.k_unMaxTrackedDeviceCount];
             poseMatrices = new Matrix4f[VR.k_unMaxTrackedDeviceCount];
@@ -165,7 +161,7 @@ public class LWJGLOpenVR implements VRAPI {
             VRinput = new LWJGLOpenVRInput(environment);
             VRinput.init();
             VRinput.updateConnectedControllers();
-            
+
             // init bounds & chaperone info
             LWJGLOpenVRBounds bounds = new LWJGLOpenVRBounds();
 //            bounds.init(this);
@@ -176,7 +172,7 @@ public class LWJGLOpenVR implements VRAPI {
             return true;
         }
     }
-    
+
     @Override
     public boolean initVRCompositor(boolean allowed) {
         hmdErrorStore.put(0, VR.EVRInitError_VRInitError_None); // clear the error store
@@ -202,22 +198,21 @@ public class LWJGLOpenVR implements VRAPI {
      * @return token for camera
      */
     public long initCamera(boolean allowed) {
-      hmdErrorStore.put(0, VR.EVRInitError_VRInitError_None); // clear the error store
-      if( allowed) {
-          
-        long result = VR.VR_GetGenericInterface(VR.IVRTrackedCamera_Version, hmdErrorStore);
-    	  if (result > 0){
-    	    if(hmdErrorStore.get(0) == VR.EVRInitError_VRInitError_None ){
-    	        logger.config("OpenVR Camera initialized");
-    	    }
-            return result;
-    	  } else {
+        hmdErrorStore.put(0, VR.EVRInitError_VRInitError_None); // clear the error store
+        if( allowed) {
+            long result = VR.VR_GetGenericInterface(VR.IVRTrackedCamera_Version, hmdErrorStore);
+            if (result > 0){
+                if(hmdErrorStore.get(0) == VR.EVRInitError_VRInitError_None ){
+                    logger.config("OpenVR Camera initialized");
+                }
+                return result;
+            } else {
               logger.severe("Failed to initialize camera");
-          }
-       }
-      return 0;
+            }
+        }
+        return 0;
     }
-    
+
     @Override
     public void destroy() {
         VR.VR_ShutdownInternal();
@@ -244,12 +239,12 @@ public class LWJGLOpenVR implements VRAPI {
         store.x = w.get(0);
         store.y = h.get(0);
     }
-    
+
     @Override
     public float getInterpupillaryDistance() {
         throw new UnsupportedOperationException("Not yet implemented!");
     }
-    
+
     @Override
     public Quaternion getOrientation() {
         VRUtil.convertMatrix4toQuat(hmdPose, rotStore);
@@ -264,29 +259,29 @@ public class LWJGLOpenVR implements VRAPI {
         posStore.z = -posStore.z;
         return posStore;
     }
-    
+
     @Override
     public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot) {
         hmdPose.toTranslationVector(storePos);
         storePos.x = -storePos.x;
         storePos.z = -storePos.z;
         storeRot.set(getOrientation());
-    }    
-    
+    }
+
     @Override
     public void updatePose(){
         int result = VRCompositor.nVRCompositor_WaitGetPoses(trackedDevicePose.address(), trackedDevicePose.remaining(), 0, 0);
         // NPE when calling without a gamePoseArray. Issue filed with lwjgl #418
 //        int result = VRCompositor.VRCompositor_WaitGetPoses(trackedDevicePose, null);
         environment.getVRinput().updateControllerStates();
-                
+
         // read pose data from native
         for (int nDevice = 0; nDevice < VR.k_unMaxTrackedDeviceCount; ++nDevice ){
             if( hmdTrackedDevicePoses[nDevice].bPoseIsValid() ){
                 convertSteamVRMatrix3ToMatrix4f(hmdTrackedDevicePoses[nDevice].mDeviceToAbsoluteTracking(), poseMatrices[nDevice]);
-            }            
+            }
         }
-        
+
         if ( hmdTrackedDevicePoses[VR.k_unTrackedDeviceIndex_Hmd].bPoseIsValid()){
             hmdPose.set(poseMatrices[VR.k_unTrackedDeviceIndex_Hmd]);
         } else {
@@ -306,7 +301,7 @@ public class LWJGLOpenVR implements VRAPI {
             return hmdProjectionLeftEye;
         }
     }
-        
+
     @Override
     public Matrix4f getHMDMatrixProjectionRightEye(Camera cam){
         if( hmdProjectionRightEye != null ) {
@@ -319,7 +314,7 @@ public class LWJGLOpenVR implements VRAPI {
             return hmdProjectionRightEye;
         }
     }
-    
+
     @Override
     public Vector3f getHMDVectorPoseLeftEye() {
         if( hmdPoseLeftEyeVec == null ) {
@@ -332,7 +327,7 @@ public class LWJGLOpenVR implements VRAPI {
         }
         return hmdPoseLeftEyeVec;
     }
-    
+
     @Override
     public Vector3f getHMDVectorPoseRightEye() {
         if( hmdPoseRightEyeVec == null ) {
@@ -345,13 +340,13 @@ public class LWJGLOpenVR implements VRAPI {
         }
         return hmdPoseRightEyeVec;
     }
-    
+
     @Override
     public Vector3f getSeatedToAbsolutePosition() {
         if( environment.isSeatedExperience() == false ) return Vector3f.ZERO;
         if( hmdSeatToStand == null ) {
             hmdSeatToStand = new Vector3f();
-            
+
             HmdMatrix34 mat = HmdMatrix34.create();
             VRSystem.VRSystem_GetSeatedZeroPoseToStandingAbsoluteTrackingPose(mat);
             Matrix4f tempmat = new Matrix4f();
@@ -360,7 +355,7 @@ public class LWJGLOpenVR implements VRAPI {
         }
         return hmdSeatToStand;
     }
-    
+
     @Override
     public Matrix4f getHMDMatrixPoseLeftEye(){
         if( hmdPoseLeftEye != null ) {
@@ -372,8 +367,7 @@ public class LWJGLOpenVR implements VRAPI {
             return convertSteamVRMatrix3ToMatrix4f(mat, hmdPoseLeftEye);
         }
     }
-    
-    
+
     @Override
     public Matrix4f getHMDMatrixPoseRightEye(){
         if( hmdPoseRightEye != null ) {
@@ -385,7 +379,7 @@ public class LWJGLOpenVR implements VRAPI {
             return convertSteamVRMatrix3ToMatrix4f(mat, hmdPoseRightEye);
         }
     }
-    
+
     @Override
     public HmdType getType() {
             String completeName = "";
@@ -421,21 +415,20 @@ public class LWJGLOpenVR implements VRAPI {
                 } else if( completeName.contains("null") ) {
                     return HmdType.NULL;
                 }
-            } 
+            }
         return HmdType.OTHER;
     }
-    
+
     public void setTrackingSpace(boolean isSeated){
-        if( isSeated) {    
+        if( isSeated) {
             VRCompositor.VRCompositor_SetTrackingSpace(VR.ETrackingUniverseOrigin_TrackingUniverseSeated);
         } else {
             VRCompositor.VRCompositor_SetTrackingSpace(VR.ETrackingUniverseOrigin_TrackingUniverseStanding);
         }
     }
-    
-    
+
+
     public Matrix4f[] getPoseMatrices() {
         return poseMatrices;
     }
-    
 }

+ 6 - 9
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRBounds.java

@@ -15,20 +15,18 @@ import java.util.logging.Logger;
  * @author Rickard Edén
  */
 public class LWJGLOpenVRBounds implements VRBounds {
+    private static Logger logger = Logger.getLogger(LWJGLOpenVRBounds.class.getName());
 
-	private static Logger logger = Logger.getLogger(LWJGLOpenVRBounds.class.getName());
-	
     private Vector2f playSize;
     private boolean setup = false;
-    
+
     /**
      * Initialize the VR bounds.
      * @return <code>true</code> if the initialization is a success and <code>false</code> otherwise.
      */
     public boolean init(VRAPI api) {
-    	
-    	logger.config("Initialize VR bounds...");
-    	
+        logger.config("Initialize VR bounds...");
+
         if( !setup ) {
 //            vrChaperone = new VR_IVRChaperone_FnTable(JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRChaperone_Version, api.hmdErrorStore).getPointer());
             FloatBuffer fbX = BufferUtils.createFloatBuffer(1);
@@ -40,14 +38,13 @@ public class LWJGLOpenVRBounds implements VRBounds {
             logger.config("Initialize VR bounds [SUCCESS]");
             return true; // init success
         }
-        
+
         logger.config("Initialize VR bounds already done.");
         return true; // already initialized
     }
-    
+
     @Override
     public Vector2f getPlaySize() {
         return playSize;
     }
-    
 }

+ 4 - 4
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRInput.java

@@ -296,13 +296,13 @@ public class LWJGLOpenVRInput implements VRInputAPI {
 
     @Override
     public boolean isInputFocused() {
-    	if (environment != null){
+        if (environment != null){
             // not a 100% match, but the closest i can find in lwjgl. Doc seems to confirm this too.
             return VRSystem.VRSystem_IsInputAvailable();
             //return ((VR_IVRSystem_FnTable)environment.getVRHardware().getVRSystem()).IsInputFocusCapturedByAnotherProcess.apply() == 0;
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}      
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
 
     @Override

+ 73 - 75
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRMouseManager.java

@@ -12,95 +12,93 @@ import com.jme3.math.Vector2f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class LWJGLOpenVRMouseManager extends AbstractVRMouseManager {
+    private final int AVERAGE_AMNT = 4;
 
-	private final int AVERAGE_AMNT = 4;
-	
     private int avgCounter;
-	
+
     private final float[] lastXmv = new float[AVERAGE_AMNT];
-    
+
     private final float[] lastYmv = new float[AVERAGE_AMNT];
-    
+
     /**
      * Create a new VR mouse manager within the given {@link VREnvironment VR environment}.
      * @param environment the VR environment of the mouse manager.
      */
     public LWJGLOpenVRMouseManager(VREnvironment environment){
-    	super(environment);
+        super(environment);
     }
-    
-    
+
+
     @Override
     public void updateAnalogAsMouse(int inputIndex, AnalogListener mouseListener, String mouseXName, String mouseYName, float tpf) {
-        
-    	if (getVREnvironment() != null){
-    		if (getVREnvironment().getApplication() != null){
-    			// got a tracked controller to use as the "mouse"
-    	        if( getVREnvironment().isInVR() == false || 
-    	        	getVREnvironment().getVRinput() == null ||
-    	        	getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
-    	        	return;
-    	        }
-    	        
-    	        Vector2f tpDelta;
-    	        // TODO option to use Touch joysticks
-    	        if( isThumbstickMode() ) {
-    	            tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
-    	        } else {
-    	            tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);            
-    	        }
-    	        
-    	        float xAmount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        float yAmount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        
-    	        if( tpDelta.x < 0f ){
-    	        	xAmount = -xAmount;
-    	        }
-    	        
-    	        if( tpDelta.y < 0f ){
-    	        	yAmount = -yAmount;
-    	        }
-    	        
-    	        xAmount *= getMouseMoveScale();
-    	        yAmount *= getMouseMoveScale();
-    	        
-    	        if( mouseListener != null ) {
-    	            if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, xAmount * 0.2f, tpf);
-    	            if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, yAmount * 0.2f, tpf);
-    	        }
-    	        
-    	        if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
-    	            int index = (avgCounter+1) % AVERAGE_AMNT;
-    	            lastXmv[index] = xAmount * 133f;
-    	            lastYmv[index] = yAmount * 133f;
-    	            cursorPos.x -= avg(lastXmv);
-    	            cursorPos.y -= avg(lastYmv);
-    	            Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
-    	            
-    	            if( cursorPos.x > maxsize.x ){
-    	            	cursorPos.x = maxsize.x;
-    	            }
-    	            
-    	            if( cursorPos.x < 0f ){
-    	            	cursorPos.x = 0f;
-    	            }
-    	            
-    	            if( cursorPos.y > maxsize.y ){
-    	            	cursorPos.y = maxsize.y;
-    	            }
-    	            
-    	            if( cursorPos.y < 0f ){
-    	            	cursorPos.y = 0f;
-    	            }
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (getVREnvironment() != null){
+            if (getVREnvironment().getApplication() != null){
+                // got a tracked controller to use as the "mouse"
+                if( getVREnvironment().isInVR() == false ||
+                    getVREnvironment().getVRinput() == null ||
+                    getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
+                    return;
+                }
+
+                Vector2f tpDelta;
+                // TODO option to use Touch joysticks
+                if( isThumbstickMode() ) {
+                    tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
+                } else {
+                    tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);
+                }
+
+                float xAmount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
+                float yAmount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
+
+                if( tpDelta.x < 0f ){
+                    xAmount = -xAmount;
+                }
+
+                if( tpDelta.y < 0f ){
+                    yAmount = -yAmount;
+                }
+
+                xAmount *= getMouseMoveScale();
+                yAmount *= getMouseMoveScale();
+
+                if( mouseListener != null ) {
+                    if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, xAmount * 0.2f, tpf);
+                    if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, yAmount * 0.2f, tpf);
+                }
+
+                if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
+                    int index = (avgCounter+1) % AVERAGE_AMNT;
+                    lastXmv[index] = xAmount * 133f;
+                    lastYmv[index] = yAmount * 133f;
+                    cursorPos.x -= avg(lastXmv);
+                    cursorPos.y -= avg(lastYmv);
+                    Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
+
+                    if( cursorPos.x > maxsize.x ){
+                        cursorPos.x = maxsize.x;
+                    }
+
+                    if( cursorPos.x < 0f ){
+                        cursorPos.x = 0f;
+                    }
+
+                    if( cursorPos.y > maxsize.y ){
+                        cursorPos.y = maxsize.y;
+                    }
+
+                    if( cursorPos.y < 0f ){
+                        cursorPos.y = 0f;
+                    }
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     private float avg(float[] arr) {
         float amt = 0f;
         for(float f : arr) amt += f;

+ 72 - 76
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRTrackedController.java

@@ -13,88 +13,84 @@ import com.jme3.math.Vector3f;
  * @author Rickard Edén
  */
 public class LWJGLOpenVRTrackedController implements VRTrackedController{
+    /**
+     * The index of the controller within the underlying VR API.
+     */
+    private int controllerIndex = -1;
+
+    /**
+     * The underlying VRAPI.
+     */
+    private VRInputAPI hardware     = null;
 
-	/**
-	 * The index of the controller within the underlying VR API.
-	 */
-	private int controllerIndex = -1;
-	
-	/**
-	 * The underlying VRAPI.
-	 */
-	private VRInputAPI hardware     = null;
-	
-	/**
-	 * The name of the controller.
-	 */
-	private String name;
-	
-	private VREnvironment environment;
-	
     /**
-	 * Wrap a new VR tracked controller on an OpenVR system.
-	 * @param controllerIndex the index of the controller within the underlying VR system.
-	 * @param hardware the underlying VR system.
-	 * @param name the name of the controller.
-	 * @param manufacturer the manufacturer of the controller.
-	 * @param environment the VR environment.
-	 */
+     * The name of the controller.
+     */
+    private String name;
+
+    private VREnvironment environment;
+
+    /**
+     * Wrap a new VR tracked controller on an OpenVR system.
+     * @param controllerIndex the index of the controller within the underlying VR system.
+     * @param hardware the underlying VR system.
+     * @param name the name of the controller.
+     * @param manufacturer the manufacturer of the controller.
+     * @param environment the VR environment.
+     */
     public LWJGLOpenVRTrackedController(int controllerIndex, VRInputAPI hardware, String name, String manufacturer, VREnvironment environment){
-    	this.controllerIndex = controllerIndex;
-    	this.hardware        = hardware;
-    	
-    	this.name            = name;
-    	this.manufacturer    = manufacturer;
-    	
-    	this.environment     = environment;
+        this.controllerIndex = controllerIndex;
+        this.hardware        = hardware;
+
+        this.name            = name;
+        this.manufacturer    = manufacturer;
+
+        this.environment     = environment;
+    }
+
+    /**
+     * The manufacturer of the controller.
+     */
+    private String manufacturer;
+
+    @Override
+    public Vector3f getPosition() {
+        if (hardware != null){
+            return hardware.getPosition(controllerIndex);
+        } else {
+            throw new IllegalStateException("No underlying VR API.");
+        }
     }
-	
-	/**
-	 * The manufacturer of the controller.
-	 */
-	private String manufacturer;
-	
-	@Override
-	public Vector3f getPosition() {
-		if (hardware != null){
-			return hardware.getPosition(controllerIndex);
-		} else {
-			throw new IllegalStateException("No underlying VR API.");
-		}
-	}
 
-	@Override
-	public Quaternion getOrientation() {
+    @Override
+    public Quaternion getOrientation() {
         if (hardware != null){
-			return hardware.getOrientation(controllerIndex);
-		} else {
-			throw new IllegalStateException("No underlying VR API.");
-		}
-	}
+            return hardware.getOrientation(controllerIndex);
+        } else {
+            throw new IllegalStateException("No underlying VR API.");
+        }
+    }
 
-	@Override
-	public Matrix4f getPose(){
-		
-		if (environment != null){
-			 if (hardware != null){
-					return ((LWJGLOpenVR)environment.getVRHardware()).getPoseMatrices()[controllerIndex];
-				} else {
-					throw new IllegalStateException("No underlying VR API.");
-				}
-		} else {
-			throw new IllegalStateException("VR tracked device is not attached to any environment.");
-		}
-		
-		
-	}
-	
-	@Override
-	public String getControllerName() {
-		return name;
-	}
+    @Override
+    public Matrix4f getPose(){
+        if (environment != null){
+             if (hardware != null){
+                    return ((LWJGLOpenVR)environment.getVRHardware()).getPoseMatrices()[controllerIndex];
+                } else {
+                    throw new IllegalStateException("No underlying VR API.");
+                }
+        } else {
+            throw new IllegalStateException("VR tracked device is not attached to any environment.");
+        }
+    }
+
+    @Override
+    public String getControllerName() {
+        return name;
+    }
 
-	@Override
-	public String getControllerManufacturer() {
-		return manufacturer;
-	}
+    @Override
+    public String getControllerManufacturer() {
+        return manufacturer;
+    }
 }

+ 2 - 2
jme3-vr/src/main/java/com/jme3/input/vr/lwjgl_openvr/LWJGLOpenVRViewManager.java

@@ -208,8 +208,8 @@ public class LWJGLOpenVRViewManager extends AbstractVRViewManager {
 
                 if (errr != 0) {
                     logger.severe("Submit to right compositor error: " + " (" + Integer.toString(errl) + ")");
-//                    	logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(rightTextureType.eColorSpace));
-//                    	logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(rightTextureType.eType));
+//                    logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(rightTextureType.eColorSpace));
+//                    logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(rightTextureType.eType));
                     logger.severe("  Texture handle: " + rightTextureType.handle());
 
                     logger.severe("  Right eye texture " + rightEyeTexture.getName() + " (" + rightEyeTexture.getImage().getId() + ")");

+ 72 - 74
jme3-vr/src/main/java/com/jme3/input/vr/oculus/OculusMouseManager.java

@@ -12,94 +12,92 @@ import com.jme3.math.Vector2f;
  *
  */
 public class OculusMouseManager extends AbstractVRMouseManager {
+    private final int AVERAGE_AMNT = 4;
 
-	private final int AVERAGE_AMNT = 4;
-	
     private int avgCounter;
-	
+
     private final float[] lastXmv = new float[AVERAGE_AMNT];
-    
+
     private final float[] lastYmv = new float[AVERAGE_AMNT];
-    
+
     /**
      * Create a new VR mouse manager within the given {@link VREnvironment VR environment}.
      * @param environment the VR environment of the mouse manager.
      */
     public OculusMouseManager(VREnvironment environment){
-    	super(environment);
+        super(environment);
     }
-    
+
     @Override
     public void updateAnalogAsMouse(int inputIndex, AnalogListener mouseListener, String mouseXName, String mouseYName, float tpf) {
-        
-    	if (getVREnvironment() != null){
-    		if (getVREnvironment().getApplication() != null){
-    			// got a tracked controller to use as the "mouse"
-    	        if( getVREnvironment().isInVR() == false || 
-    	        	getVREnvironment().getVRinput() == null ||
-    	        	getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
-    	        	return;
-    	        }
-    	        
-    	        Vector2f tpDelta;
-    	        // TODO option to use Touch joysticks
-    	        if( isThumbstickMode() ) {
-    	            tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.OculusThumbstickAxis);
-    	        } else {
-    	            tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.OculusThumbstickAxis);            
-    	        }
-    	        
-    	        float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        
-    	        if( tpDelta.x < 0f ){
-    	        	Xamount = -Xamount;
-    	        }
-    	        
-    	        if( tpDelta.y < 0f ){
-    	        	Yamount = -Yamount;
-    	        }
-    	        
-    	        Xamount *= getMouseMoveScale(); 
-    	        Yamount *= getMouseMoveScale();
-    	        
-    	        if( mouseListener != null ) {
-    	            if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
-    	            if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);            
-    	        }
-    	        
-    	        if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
-    	            int index = (avgCounter+1) % AVERAGE_AMNT;
-    	            lastXmv[index] = Xamount * 133f;
-    	            lastYmv[index] = Yamount * 133f;
-    	            cursorPos.x -= avg(lastXmv);
-    	            cursorPos.y -= avg(lastYmv);
-    	            Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
-    	            
-    	            if( cursorPos.x > maxsize.x ){
-    	            	cursorPos.x = maxsize.x;
-    	            }
-    	            
-    	            if( cursorPos.x < 0f ){
-    	            	cursorPos.x = 0f;
-    	            }
-    	            
-    	            if( cursorPos.y > maxsize.y ){
-    	            	cursorPos.y = maxsize.y;
-    	            }
-    	            
-    	            if( cursorPos.y < 0f ){
-    	            	cursorPos.y = 0f;
-    	            }
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (getVREnvironment() != null){
+            if (getVREnvironment().getApplication() != null){
+                // got a tracked controller to use as the "mouse"
+                if( getVREnvironment().isInVR() == false ||
+                    getVREnvironment().getVRinput() == null ||
+                    getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
+                    return;
+                }
+
+                Vector2f tpDelta;
+                // TODO option to use Touch joysticks
+                if( isThumbstickMode() ) {
+                    tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.OculusThumbstickAxis);
+                } else {
+                    tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.OculusThumbstickAxis);
+                }
+
+                float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
+                float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
+
+                if( tpDelta.x < 0f ){
+                    Xamount = -Xamount;
+                }
+
+                if( tpDelta.y < 0f ){
+                    Yamount = -Yamount;
+                }
+
+                Xamount *= getMouseMoveScale();
+                Yamount *= getMouseMoveScale();
+
+                if( mouseListener != null ) {
+                    if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
+                    if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);
+                }
+
+                if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
+                    int index = (avgCounter+1) % AVERAGE_AMNT;
+                    lastXmv[index] = Xamount * 133f;
+                    lastYmv[index] = Yamount * 133f;
+                    cursorPos.x -= avg(lastXmv);
+                    cursorPos.y -= avg(lastYmv);
+                    Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
+
+                    if( cursorPos.x > maxsize.x ){
+                        cursorPos.x = maxsize.x;
+                    }
+
+                    if( cursorPos.x < 0f ){
+                        cursorPos.x = 0f;
+                    }
+
+                    if( cursorPos.y > maxsize.y ){
+                        cursorPos.y = maxsize.y;
+                    }
+
+                    if( cursorPos.y < 0f ){
+                        cursorPos.y = 0f;
+                    }
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     private float avg(float[] arr) {
         float amt = 0f;
         for(float f : arr) amt += f;

+ 102 - 110
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVR.java

@@ -30,58 +30,56 @@ import java.util.logging.Level;
 import java.util.logging.Logger;
 
 /**
- * A class that wraps an <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system. 
+ * A class that wraps an <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system.
  * @author reden - phr00t - https://github.com/phr00t
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OpenVR implements VRAPI {
-    
-	private static final Logger logger = Logger.getLogger(OpenVR.class.getName());
-	
+    private static final Logger logger = Logger.getLogger(OpenVR.class.getName());
+
     private static VR_IVRCompositor_FnTable compositorFunctions;
     private static VR_IVRSystem_FnTable vrsystemFunctions;
     private static VR_IVRTrackedCamera_FnTable cameraFunctions;
-    
+
     private static boolean initSuccess = false;
     private static boolean flipEyes    = false;
-    
+
     private IntBuffer hmdDisplayFrequency;
     private TrackedDevicePose_t.ByReference hmdTrackedDevicePoseReference;
     protected TrackedDevicePose_t[] hmdTrackedDevicePoses;
-    
+
     protected IntByReference hmdErrorStore;
-    
+
     private final Quaternion rotStore = new Quaternion();
     private final Vector3f posStore = new Vector3f();
-    
+
     private static FloatByReference tlastVsync;
-    
+
     /**
      * The actual frame count.
      */
     public static LongByReference _tframeCount;
-    
+
     // for debugging latency
-    private int frames = 0;    
-    
+    private int frames = 0;
+
     protected Matrix4f[] poseMatrices;
-    
+
     private final Matrix4f hmdPose = Matrix4f.IDENTITY.clone();
     private Matrix4f hmdProjectionLeftEye;
     private Matrix4f hmdProjectionRightEye;
     private Matrix4f hmdPoseLeftEye;
     private Matrix4f hmdPoseRightEye;
-    
+
     private Vector3f hmdPoseLeftEyeVec, hmdPoseRightEyeVec, hmdSeatToStand;
-    
+
     private float vsyncToPhotons;
     private double timePerFrame, frameCountRun;
     private long frameCount;
     private OpenVRInput VRinput;
-    
-    
+
     private VREnvironment environment = null;
-    
+
     /**
      * Convert specific OpenVR {@link com.jme3.system.jopenvr.HmdMatrix34_t HmdMatrix34_t} into JME {@link Matrix4f Matrix4f}
      * @param hmdMatrix the input matrix
@@ -89,13 +87,13 @@ public class OpenVR implements VRAPI {
      * @return the converted matrix
      */
     public static Matrix4f convertSteamVRMatrix3ToMatrix4f(com.jme3.system.jopenvr.HmdMatrix34_t hmdMatrix, Matrix4f mat){
-        mat.set(hmdMatrix.m[0], hmdMatrix.m[1], hmdMatrix.m[2], hmdMatrix.m[3], 
-                hmdMatrix.m[4], hmdMatrix.m[5], hmdMatrix.m[6], hmdMatrix.m[7], 
-                hmdMatrix.m[8], hmdMatrix.m[9], hmdMatrix.m[10], hmdMatrix.m[11], 
+        mat.set(hmdMatrix.m[0], hmdMatrix.m[1], hmdMatrix.m[2], hmdMatrix.m[3],
+                hmdMatrix.m[4], hmdMatrix.m[5], hmdMatrix.m[6], hmdMatrix.m[7],
+                hmdMatrix.m[8], hmdMatrix.m[9], hmdMatrix.m[10], hmdMatrix.m[11],
                 0f, 0f, 0f, 1f);
         return mat;
     }
-    
+
     /**
      * Convert specific OpenVR {@link com.jme3.system.jopenvr.HmdMatrix44_t HmdMatrix34_t} into JME {@link Matrix4f Matrix4f}
      * @param hmdMatrix the input matrix
@@ -103,56 +101,55 @@ public class OpenVR implements VRAPI {
      * @return the converted matrix
      */
     public static Matrix4f convertSteamVRMatrix4ToMatrix4f(com.jme3.system.jopenvr.HmdMatrix44_t hmdMatrix, Matrix4f mat){
-        mat.set(hmdMatrix.m[0], hmdMatrix.m[1], hmdMatrix.m[2], hmdMatrix.m[3], 
+        mat.set(hmdMatrix.m[0], hmdMatrix.m[1], hmdMatrix.m[2], hmdMatrix.m[3],
                 hmdMatrix.m[4], hmdMatrix.m[5], hmdMatrix.m[6], hmdMatrix.m[7],
-                hmdMatrix.m[8], hmdMatrix.m[9], hmdMatrix.m[10], hmdMatrix.m[11], 
+                hmdMatrix.m[8], hmdMatrix.m[9], hmdMatrix.m[10], hmdMatrix.m[11],
                 hmdMatrix.m[12], hmdMatrix.m[13], hmdMatrix.m[14], hmdMatrix.m[15]);
         return mat;
     }
-    
-    
+
     /**
-     * Create a new <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system 
+     * Create a new <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> system
      * attached to the given {@link VREnvironment VR environment}.
      * @param environment the VR environment to which this API is attached.
      */
     public OpenVR(VREnvironment environment){
       this.environment = environment;
     }
-    
+
     @Override
     public OpenVRInput getVRinput() {
         return VRinput;
     }
-    
+
     @Override
     public VR_IVRSystem_FnTable getVRSystem() {
         return vrsystemFunctions;
     }
-    
+
     @Override
     public VR_IVRCompositor_FnTable getCompositor() {
         return compositorFunctions;
     }
-    
+
     public VR_IVRTrackedCamera_FnTable getTrackedCamera(){
       return cameraFunctions;
     }
-    
+
     @Override
     public String getName() {
         return "OpenVR";
     }
-    
+
     private static long latencyWaitTime = 0;
-    
+
     @Override
     public void setFlipEyes(boolean set) {
         flipEyes = set;
     }
-    
+
     private boolean enableDebugLatency = false;
-    
+
     @Override
     public void printLatencyInfoToConsole(boolean set) {
         enableDebugLatency = set;
@@ -163,15 +160,14 @@ public class OpenVR implements VRAPI {
         if( hmdDisplayFrequency == null ) return 0;
         return hmdDisplayFrequency.get(0);
     }
-    
+
     @Override
     public boolean initialize() {
-    	
-    	logger.config("Initializing OpenVR system...");
-    	
+        logger.config("Initializing OpenVR system...");
+
         hmdErrorStore = new IntByReference();
         vrsystemFunctions = null;
-        
+
         // Init the native linking to the OpenVR library.
         try{
           JOpenVRLibrary.init();
@@ -179,27 +175,26 @@ public class OpenVR implements VRAPI {
           logger.log(Level.SEVERE, "Cannot link to OpenVR system library: "+t.getMessage(), t);
           return false;
         }
-        
+
         JOpenVRLibrary.VR_InitInternal(hmdErrorStore, JOpenVRLibrary.EVRApplicationType.EVRApplicationType_VRApplication_Scene);
-        
+
         if( hmdErrorStore.getValue() == 0 ) {
             vrsystemFunctions = new VR_IVRSystem_FnTable(JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRSystem_Version, hmdErrorStore).getPointer());
         }
-        
+
         if( vrsystemFunctions == null || hmdErrorStore.getValue() != 0 ) {
             logger.severe("OpenVR Initialize Result: " + JOpenVRLibrary.VR_GetVRInitErrorAsEnglishDescription(hmdErrorStore.getValue()).getString(0));
             logger.severe("Initializing OpenVR system [FAILED]");
             return false;
         } else {
             logger.config("OpenVR initialized & VR connected.");
-            
+
             vrsystemFunctions.setAutoSynch(false);
             vrsystemFunctions.read();
-            
-            
+
             tlastVsync = new FloatByReference();
             _tframeCount = new LongByReference();
-            
+
             hmdDisplayFrequency = IntBuffer.allocate(1);
             hmdDisplayFrequency.put(JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_DisplayFrequency_Float);
             hmdTrackedDevicePoseReference = new TrackedDevicePose_t.ByReference();
@@ -208,7 +203,7 @@ public class OpenVR implements VRAPI {
             for(int i=0;i<poseMatrices.length;i++) poseMatrices[i] = new Matrix4f();
 
             timePerFrame = 1.0 / hmdDisplayFrequency.get(0);
-            
+
             // disable all this stuff which kills performance
             hmdTrackedDevicePoseReference.setAutoRead(false);
             hmdTrackedDevicePoseReference.setAutoWrite(false);
@@ -218,57 +213,55 @@ public class OpenVR implements VRAPI {
                 hmdTrackedDevicePoses[i].setAutoWrite(false);
                 hmdTrackedDevicePoses[i].setAutoSynch(false);
             }
-            
+
             // init controllers for the first time
             VRinput = new OpenVRInput(environment);
             VRinput.init();
             VRinput.updateConnectedControllers();
-            
+
             // init bounds & chaperone info
             OpenVRBounds bounds = new OpenVRBounds();
             bounds.init(this);
             environment.setVRBounds(bounds);
-            
+
             logger.config("Initializing OpenVR system [SUCCESS]");
             initSuccess = true;
             return true;
         }
     }
-    
+
     @Override
     public boolean initVRCompositor(boolean allowed) {
         hmdErrorStore.setValue(0); // clear the error store
         if( allowed && vrsystemFunctions != null ) {
-        	
-        	IntByReference intptr = JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRCompositor_Version, hmdErrorStore);
-        	if (intptr != null){
-        	
-        		if (intptr.getPointer() != null){
-            		compositorFunctions = new VR_IVRCompositor_FnTable(intptr.getPointer());
-                    if(compositorFunctions != null && hmdErrorStore.getValue() == 0 ){          
+
+            IntByReference intptr = JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRCompositor_Version, hmdErrorStore);
+            if (intptr != null){
+
+                if (intptr.getPointer() != null){
+                    compositorFunctions = new VR_IVRCompositor_FnTable(intptr.getPointer());
+                    if(compositorFunctions != null && hmdErrorStore.getValue() == 0 ){
                         compositorFunctions.setAutoSynch(false);
                         compositorFunctions.read();
-                        if( environment.isSeatedExperience() ) {                    
+                        if( environment.isSeatedExperience() ) {
                             compositorFunctions.SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseSeated);
                         } else {
-                            compositorFunctions.SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseStanding);                
+                            compositorFunctions.SetTrackingSpace.apply(JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseStanding);
                         }
                         logger.config("OpenVR Compositor initialized");
                     } else {
                         logger.severe("OpenVR Compositor error: " + hmdErrorStore.getValue());
                         compositorFunctions = null;
                     }
-        		} else {
-        			logger.log(Level.SEVERE, "Cannot get valid pointer for generic interface \""+JOpenVRLibrary.IVRCompositor_Version+"\", "+OpenVRUtil.getEVRInitErrorString(hmdErrorStore.getValue())+" ("+hmdErrorStore.getValue()+")");
-        			compositorFunctions = null;
-        		}
-
-        	} else {
-        		logger.log(Level.SEVERE, "Cannot get generic interface for \""+JOpenVRLibrary.IVRCompositor_Version+"\", "+OpenVRUtil.getEVRInitErrorString(hmdErrorStore.getValue())+" ("+hmdErrorStore.getValue()+")");
-        		compositorFunctions = null;
-        	}
-        	
-            
+                } else {
+                    logger.log(Level.SEVERE, "Cannot get valid pointer for generic interface \""+JOpenVRLibrary.IVRCompositor_Version+"\", "+OpenVRUtil.getEVRInitErrorString(hmdErrorStore.getValue())+" ("+hmdErrorStore.getValue()+")");
+                    compositorFunctions = null;
+                }
+
+            } else {
+                logger.log(Level.SEVERE, "Cannot get generic interface for \""+JOpenVRLibrary.IVRCompositor_Version+"\", "+OpenVRUtil.getEVRInitErrorString(hmdErrorStore.getValue())+" ("+hmdErrorStore.getValue()+")");
+                compositorFunctions = null;
+            }
         }
         if( compositorFunctions == null ) {
             logger.severe("Skipping VR Compositor...");
@@ -287,20 +280,20 @@ public class OpenVR implements VRAPI {
      */
     public void initCamera(boolean allowed) {
       hmdErrorStore.setValue(0); // clear the error store
-      
+
       if( allowed && vrsystemFunctions != null ) {
         IntByReference intptr = JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRTrackedCamera_Version, hmdErrorStore);
-    	  if (intptr != null){
-    	    cameraFunctions = new VR_IVRTrackedCamera_FnTable(intptr.getPointer());
-    	    if(cameraFunctions != null && hmdErrorStore.getValue() == 0 ){
-    	      cameraFunctions.setAutoSynch(false);
-    	        cameraFunctions.read();
-    	        logger.config("OpenVR Camera initialized");
-    	    }
-    	  }
+          if (intptr != null){
+            cameraFunctions = new VR_IVRTrackedCamera_FnTable(intptr.getPointer());
+            if(cameraFunctions != null && hmdErrorStore.getValue() == 0 ){
+              cameraFunctions.setAutoSynch(false);
+                cameraFunctions.read();
+                logger.config("OpenVR Camera initialized");
+            }
+          }
        }
     }
-    
+
     @Override
     public void destroy() {
         JOpenVRLibrary.VR_ShutdownInternal();
@@ -336,7 +329,7 @@ public class OpenVR implements VRAPI {
     @Override
     public float getFOV(int dir) {
         float val = 0f;
-        if( vrsystemFunctions != null ) {      
+        if( vrsystemFunctions != null ) {
             val = vrsystemFunctions.GetFloatTrackedDeviceProperty.apply(JOpenVRLibrary.k_unTrackedDeviceIndex_Hmd, dir, hmdErrorStore);
         }
         // verification of number
@@ -349,13 +342,13 @@ public class OpenVR implements VRAPI {
         return val;
     }
     */
-    
+
     @Override
     public float getInterpupillaryDistance() {
         if( vrsystemFunctions == null ) return 0.065f;
         return vrsystemFunctions.GetFloatTrackedDeviceProperty.apply(JOpenVRLibrary.k_unTrackedDeviceIndex_Hmd, JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_UserIpdMeters_Float, hmdErrorStore);
     }
-    
+
     @Override
     public Quaternion getOrientation() {
         VRUtil.convertMatrix4toQuat(hmdPose, rotStore);
@@ -370,15 +363,15 @@ public class OpenVR implements VRAPI {
         posStore.z = -posStore.z;
         return posStore;
     }
-    
+
     @Override
     public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot) {
         hmdPose.toTranslationVector(storePos);
         storePos.x = -storePos.x;
         storePos.z = -storePos.z;
         storeRot.set(getOrientation());
-    }    
-    
+    }
+
     @Override
     public void updatePose(){
         if(vrsystemFunctions == null) return;
@@ -387,18 +380,18 @@ public class OpenVR implements VRAPI {
         } else {
             // wait
             if( latencyWaitTime > 0 ) VRUtil.sleepNanos(latencyWaitTime);
-                        
+
             vrsystemFunctions.GetTimeSinceLastVsync.apply(tlastVsync, _tframeCount);
             float fSecondsUntilPhotons = (float)timePerFrame - tlastVsync.getValue() + vsyncToPhotons;
-            
+
             if( enableDebugLatency ) {
                 if( frames == 10 ) {
                     System.out.println("Waited (nanos): " + Long.toString(latencyWaitTime));
                     System.out.println("Predict ahead time: " + Float.toString(fSecondsUntilPhotons));
                 }
-                frames = (frames + 1) % 60;            
-            }            
-            
+                frames = (frames + 1) % 60;
+            }
+
             // handle skipping frame stuff
             long nowCount = _tframeCount.getValue();
             if( nowCount - frameCount > 1 ) {
@@ -416,13 +409,13 @@ public class OpenVR implements VRAPI {
             }
 
             frameCount = nowCount;
-            
+
             vrsystemFunctions.GetDeviceToAbsoluteTrackingPose.apply(
                     environment.isSeatedExperience()?JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseSeated:
                                                        JOpenVRLibrary.ETrackingUniverseOrigin.ETrackingUniverseOrigin_TrackingUniverseStanding,
-                    fSecondsUntilPhotons, hmdTrackedDevicePoseReference, JOpenVRLibrary.k_unMaxTrackedDeviceCount);   
+                    fSecondsUntilPhotons, hmdTrackedDevicePoseReference, JOpenVRLibrary.k_unMaxTrackedDeviceCount);
         }
-        
+
         // deal with controllers being plugged in and out
         // causing an invalid memory crash... skipping for now
         /*boolean hasEvent = false;
@@ -436,16 +429,16 @@ public class OpenVR implements VRAPI {
         }*/
         //update controllers pose information
         environment.getVRinput().updateControllerStates();
-                
+
         // read pose data from native
         for (int nDevice = 0; nDevice < JOpenVRLibrary.k_unMaxTrackedDeviceCount; ++nDevice ){
             hmdTrackedDevicePoses[nDevice].readField("bPoseIsValid");
             if( hmdTrackedDevicePoses[nDevice].bPoseIsValid != 0 ){
                 hmdTrackedDevicePoses[nDevice].readField("mDeviceToAbsoluteTracking");
                 convertSteamVRMatrix3ToMatrix4f(hmdTrackedDevicePoses[nDevice].mDeviceToAbsoluteTracking, poseMatrices[nDevice]);
-            }            
+            }
         }
-        
+
         if ( hmdTrackedDevicePoses[JOpenVRLibrary.k_unTrackedDeviceIndex_Hmd].bPoseIsValid != 0 ){
             hmdPose.set(poseMatrices[JOpenVRLibrary.k_unTrackedDeviceIndex_Hmd]);
         } else {
@@ -466,7 +459,7 @@ public class OpenVR implements VRAPI {
             return hmdProjectionLeftEye;
         }
     }
-        
+
     @Override
     public Matrix4f getHMDMatrixProjectionRightEye(Camera cam){
         if( hmdProjectionRightEye != null ) {
@@ -480,7 +473,7 @@ public class OpenVR implements VRAPI {
             return hmdProjectionRightEye;
         }
     }
-    
+
     @Override
     public Vector3f getHMDVectorPoseLeftEye() {
         if( hmdPoseLeftEyeVec == null ) {
@@ -493,7 +486,7 @@ public class OpenVR implements VRAPI {
         }
         return hmdPoseLeftEyeVec;
     }
-    
+
     @Override
     public Vector3f getHMDVectorPoseRightEye() {
         if( hmdPoseRightEyeVec == null ) {
@@ -506,7 +499,7 @@ public class OpenVR implements VRAPI {
         }
         return hmdPoseRightEyeVec;
     }
-    
+
     @Override
     public Vector3f getSeatedToAbsolutePosition() {
         if( environment.isSeatedExperience() == false ) return Vector3f.ZERO;
@@ -519,7 +512,7 @@ public class OpenVR implements VRAPI {
         }
         return hmdSeatToStand;
     }
-    
+
     @Override
     public Matrix4f getHMDMatrixPoseLeftEye(){
         if( hmdPoseLeftEye != null ) {
@@ -532,10 +525,10 @@ public class OpenVR implements VRAPI {
             return convertSteamVRMatrix3ToMatrix4f(mat, hmdPoseLeftEye);
         }
     }
-    
+
     @Override
     public HmdType getType() {
-        if( vrsystemFunctions != null ) {      
+        if( vrsystemFunctions != null ) {
             Pointer str1 = new Memory(128);
             Pointer str2 = new Memory(128);
             String completeName = "";
@@ -575,7 +568,7 @@ public class OpenVR implements VRAPI {
         } else return HmdType.NONE;
         return HmdType.OTHER;
     }
-    
+
     @Override
     public Matrix4f getHMDMatrixPoseRightEye(){
         if( hmdPoseRightEye != null ) {
@@ -588,5 +581,4 @@ public class OpenVR implements VRAPI {
             return convertSteamVRMatrix3ToMatrix4f(mat, hmdPoseRightEye);
         }
     }
-  
 }

+ 8 - 11
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRBounds.java

@@ -14,20 +14,18 @@ import java.util.logging.Logger;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OpenVRBounds implements VRBounds {
+    private static Logger logger = Logger.getLogger(OpenVRBounds.class.getName());
 
-	private static Logger logger = Logger.getLogger(OpenVRBounds.class.getName());
-	
     private VR_IVRChaperone_FnTable vrChaperone;
     private Vector2f playSize;
-    
+
     /**
      * Initialize the VR bounds.
      * @return <code>true</code> if the initialization is a success and <code>false</code> otherwise.
      */
     public boolean init(OpenVR api) {
-    	
-    	logger.config("Initialize VR bounds...");
-    	
+        logger.config("Initialize VR bounds...");
+
         if( vrChaperone == null ) {
             vrChaperone = new VR_IVRChaperone_FnTable(JOpenVRLibrary.VR_GetGenericInterface(JOpenVRLibrary.IVRChaperone_Version, api.hmdErrorStore).getPointer());
             if( vrChaperone != null ) {
@@ -37,23 +35,22 @@ public class OpenVRBounds implements VRBounds {
                 FloatByReference fbZ = new FloatByReference();
                 vrChaperone.GetPlayAreaSize.apply(fbX, fbZ);
                 playSize = new Vector2f(fbX.getValue(), fbZ.getValue());
-                
+
                 logger.config("Initialize VR bounds [SUCCESS]");
                 return true; // init success
             }
-            
+
             logger.warning("Initialize VR bounds [FAILED].");
             return false; // failed to init
         }
-        
+
         logger.config("Initialize VR bounds already done.");
         return true; // already initialized
     }
-    
+
     @Override
     public Vector2f getPlaySize() {
         return playSize;
     }
-    
 }
 

+ 193 - 211
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRInput.java

@@ -65,39 +65,38 @@ Button press: 2, touch: 2
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OpenVRInput implements VRInputAPI {
-        
-	private static final Logger logger = Logger.getLogger(OpenVRInput.class.getName());
-	
+    private static final Logger logger = Logger.getLogger(OpenVRInput.class.getName());
+
     private final VRControllerState_t[] cStates = new VRControllerState_t[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private final Quaternion[] rotStore = new Quaternion[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private final Vector3f[] posStore   = new Vector3f[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private static final int[] controllerIndex = new int[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private int controllerCount = 0;
-    
+
     private final Vector2f tempAxis = new Vector2f(), temp2Axis = new Vector2f();
-    
+
     private final Vector2f lastCallAxis[] = new Vector2f[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private final boolean needsNewVelocity[]    = new boolean[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private final boolean needsNewAngVelocity[] = new boolean[JOpenVRLibrary.k_unMaxTrackedDeviceCount];
-    
+
     private final boolean buttonDown[][]        = new boolean[JOpenVRLibrary.k_unMaxTrackedDeviceCount][16];
-    
+
     private float axisMultiplier = 1f;
-    
+
     private final Vector3f tempVel = new Vector3f();
-    
+
     private final Quaternion tempq = new Quaternion();
 
     private VREnvironment environment;
 
     private List<VRTrackedController> trackedControllers = null;
-    
+
     /**
      * Create a new <a href="https://github.com/ValveSoftware/openvr/wiki/API-Documentation">OpenVR</a> input attached to the given VR environment.
      * @param environment the VR environment to which the input is attached.
@@ -105,25 +104,25 @@ public class OpenVRInput implements VRInputAPI {
     public OpenVRInput(VREnvironment environment){
       this.environment = environment;
     }
-    
+
     @Override
     public float getAxisMultiplier() {
         return axisMultiplier;
     }
-    
+
     @Override
     public void setAxisMultiplier(float set) {
         axisMultiplier = set;
     }
-    
+
     @Override
     public void swapHands() {
-        if( controllerCount != 2 ) return; 
+        if( controllerCount != 2 ) return;
         int temp = controllerIndex[0];
         controllerIndex[0] = controllerIndex[1];
         controllerIndex[1] = temp;
     }
-    
+
     @Override
     public boolean isButtonDown(int controllerIndex, VRInputType checkButton) {
         VRControllerState_t cs = cStates[OpenVRInput.controllerIndex[controllerIndex]];
@@ -133,14 +132,14 @@ public class OpenVRInput implements VRInputAPI {
             case ViveGripButton:
                 return (cs.ulButtonPressed & 4) != 0;
             case ViveMenuButton:
-                return (cs.ulButtonPressed & 2) != 0;                
+                return (cs.ulButtonPressed & 2) != 0;
             case ViveTrackpadAxis:
                 return (cs.ulButtonPressed & 4294967296l) != 0;
             case ViveTriggerAxis:
-                return (cs.ulButtonPressed & 8589934592l) != 0;                
+                return (cs.ulButtonPressed & 8589934592l) != 0;
         }
     }
-    
+
     @Override
     public boolean wasButtonPressedSinceLastCall(int controllerIndex, VRInputType checkButton) {
         boolean buttonDownNow = isButtonDown(controllerIndex, checkButton);
@@ -150,7 +149,7 @@ public class OpenVRInput implements VRInputAPI {
         buttonDown[cIndex][checkButtonValue] = buttonDownNow;
         return retval;
     }
-    
+
     @Override
     public void resetInputSinceLastCall() {
         for(int i=0;i<lastCallAxis.length;i++) {
@@ -163,14 +162,14 @@ public class OpenVRInput implements VRInputAPI {
             }
         }
     }
-    
+
     @Override
-    public Vector2f getAxisDeltaSinceLastCall(int controllerIndex, VRInputType forAxis) {                
+    public Vector2f getAxisDeltaSinceLastCall(int controllerIndex, VRInputType forAxis) {
         int axisIndex = forAxis.getValue();
         temp2Axis.set(lastCallAxis[axisIndex]);
         lastCallAxis[axisIndex].set(getAxis(controllerIndex, forAxis));
         if( (temp2Axis.x != 0f || temp2Axis.y != 0f) && (lastCallAxis[axisIndex].x != 0f || lastCallAxis[axisIndex].y != 0f) ) {
-            temp2Axis.subtractLocal(lastCallAxis[axisIndex]);        
+            temp2Axis.subtractLocal(lastCallAxis[axisIndex]);
         } else {
             // move made from rest, don't count as a delta move
             temp2Axis.x = 0f;
@@ -178,13 +177,11 @@ public class OpenVRInput implements VRInputAPI {
         }
         return temp2Axis;
     }
-    
+
     @Override
     public Vector3f getVelocity(int controllerIndex) {
-    	
-    	if (environment != null){
-    		
-    		if (environment.getVRHardware() instanceof OpenVR){
+        if (environment != null){
+            if (environment.getVRHardware() instanceof OpenVR){
                 int index = OpenVRInput.controllerIndex[controllerIndex];
                 if( needsNewVelocity[index] ) {
                     ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].readField("vVelocity");
@@ -194,39 +191,36 @@ public class OpenVRInput implements VRInputAPI {
                 tempVel.y = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vVelocity.v[1];
                 tempVel.z = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vVelocity.v[2];
                 return tempVel;
-    		} else {
-        		throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
+            } else {
+                throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-    
+
     @Override
     public Vector3f getAngularVelocity(int controllerIndex) {
-    	
-    	if (environment != null){
-    		
-    		if (environment.getVRHardware() instanceof OpenVR){
-    	    	
-    	        int index = OpenVRInput.controllerIndex[controllerIndex];
-    	        if( needsNewAngVelocity[index] ) {
-    	        	((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].readField("vAngularVelocity");
-    	            needsNewAngVelocity[index] = false;
-    	        }
-    	        tempVel.x = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[0];
-    	        tempVel.y = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[1];
-    	        tempVel.z = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[2];
-    	        return tempVel;
-    		} else {
-        		throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
+        if (environment != null){
+            if (environment.getVRHardware() instanceof OpenVR){
 
+                int index = OpenVRInput.controllerIndex[controllerIndex];
+                if( needsNewAngVelocity[index] ) {
+                    ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].readField("vAngularVelocity");
+                    needsNewAngVelocity[index] = false;
+                }
+                tempVel.x = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[0];
+                tempVel.y = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[1];
+                tempVel.z = ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[index].vAngularVelocity.v[2];
+                return tempVel;
+            } else {
+                throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-    
+
     @Override
     public Vector2f getAxisRaw(int controllerIndex, VRInputType forAxis) {
         VRControllerState_t cs = cStates[OpenVRInput.controllerIndex[controllerIndex]];
@@ -241,7 +235,7 @@ public class OpenVRInput implements VRInputAPI {
                 tempAxis.x = cs.rAxis[0].x;
                 tempAxis.y = cs.rAxis[0].y;
                 break;
-        }       
+        }
         return tempAxis;
     }
 
@@ -259,17 +253,16 @@ public class OpenVRInput implements VRInputAPI {
                 tempAxis.x = cs.rAxis[0].x;
                 tempAxis.y = cs.rAxis[0].y;
                 break;
-        }       
+        }
         tempAxis.x *= axisMultiplier;
         tempAxis.y *= axisMultiplier;
         return tempAxis;
     }
-    
+
     @Override
     public boolean init() {
-    	
-    	logger.config("Initialize OpenVR input.");
-    	
+        logger.config("Initialize OpenVR input.");
+
         for(int i=0;i<JOpenVRLibrary.k_unMaxTrackedDeviceCount;i++) {
             rotStore[i] = new Quaternion();
             posStore[i] = new Vector3f();
@@ -281,149 +274,141 @@ public class OpenVRInput implements VRInputAPI {
             needsNewVelocity[i] = true;
             needsNewAngVelocity[i] = true;
             logger.config("  Input "+(i+1)+"/"+JOpenVRLibrary.k_unMaxTrackedDeviceCount+" bound.");
-        }        
-        
+        }
+
         return true;
     }
-    
+
     @Override
     public VRTrackedController getTrackedController(int index){
-    	if (trackedControllers != null){
-    		if ((trackedControllers.size() > 0) && (index < trackedControllers.size())){
-    			return trackedControllers.get(index);
-    		}
-    	}
-    	
-    	return null;
+        if (trackedControllers != null){
+            if ((trackedControllers.size() > 0) && (index < trackedControllers.size())){
+                return trackedControllers.get(index);
+            }
+        }
+
+        return null;
     }
-    
+
     @Override
     public int getTrackedControllerCount() {
         return controllerCount;
     }
-    
+
     @Override
     public VRControllerState_t getRawControllerState(int index) {
         if( isInputDeviceTracking(index) == false ) return null;
         return cStates[controllerIndex[index]];
     }
-    
+
     //public Matrix4f getPoseForInputDevice(int index) {
     //    if( isInputDeviceTracking(index) == false ) return null;
     //    return OpenVR.poseMatrices[controllerIndex[index]];
     //}
-    
+
     @Override
     public boolean isInputFocused() {
-    	
-    	if (environment != null){
-    		return ((VR_IVRSystem_FnTable)environment.getVRHardware().getVRSystem()).IsInputAvailable.apply() == 0;
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}      
+        if (environment != null){
+            return ((VR_IVRSystem_FnTable)environment.getVRHardware().getVRSystem()).IsInputAvailable.apply() == 0;
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-    
+
     @Override
     public boolean isInputDeviceTracking(int index) {
         if( index < 0 || index >= controllerCount ){
-        	return false;
+            return false;
+        }
+
+        if (environment != null){
+            if (environment.getVRHardware() instanceof OpenVR){
+                 return ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[controllerIndex[index]].bPoseIsValid != 0;
+            } else {
+                throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
         }
-        
-    	if (environment != null){
-    		
-    		if (environment.getVRHardware() instanceof OpenVR){
-    			 return ((OpenVR)environment.getVRHardware()).hmdTrackedDevicePoses[controllerIndex[index]].bPoseIsValid != 0;
-    		} else {
-        		throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
     }
-    
+
     @Override
     public Quaternion getOrientation(int index) {
         if( isInputDeviceTracking(index) == false ){
-        	return null;
+            return null;
         }
-        
+
         if (environment != null){
-    		
-    		if (environment.getVRHardware() instanceof OpenVR){
-    	        index = controllerIndex[index];
-    	        VRUtil.convertMatrix4toQuat(((OpenVR)environment.getVRHardware()).poseMatrices[index], rotStore[index]);
-    	        return rotStore[index];
-    		} else {
-        		throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
+
+            if (environment.getVRHardware() instanceof OpenVR){
+                index = controllerIndex[index];
+                VRUtil.convertMatrix4toQuat(((OpenVR)environment.getVRHardware()).poseMatrices[index], rotStore[index]);
+                return rotStore[index];
+            } else {
+                throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
 
     @Override
     public Vector3f getPosition(int index) {
         if( isInputDeviceTracking(index) == false ){
-        	return null;
+            return null;
         }
-        
-        if (environment != null){
-    		
-    		if (environment.getVRHardware() instanceof OpenVR){
-    	        // the hmdPose comes in rotated funny, fix that here
-    	        index = controllerIndex[index];
-    	        ((OpenVR)environment.getVRHardware()).poseMatrices[index].toTranslationVector(posStore[index]);
-    	        posStore[index].x = -posStore[index].x;
-    	        posStore[index].z = -posStore[index].z;
-    	        return posStore[index];
-    		} else {
-        		throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
-        
 
+        if (environment != null){
+            if (environment.getVRHardware() instanceof OpenVR){
+                // the hmdPose comes in rotated funny, fix that here
+                index = controllerIndex[index];
+                ((OpenVR)environment.getVRHardware()).poseMatrices[index].toTranslationVector(posStore[index]);
+                posStore[index].x = -posStore[index].x;
+                posStore[index].z = -posStore[index].z;
+                return posStore[index];
+            } else {
+                throw new IllegalStateException("VR hardware "+environment.getVRHardware().getClass().getSimpleName()+" is not a subclass of "+OpenVR.class.getSimpleName());
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-    
+
     @Override
     public Quaternion getFinalObserverRotation(int index) {
-    	
-    	if (environment != null){
+        if (environment != null){
             OpenVRViewManager vrvm = (OpenVRViewManager)environment.getVRViewManager();
-            
+
             if (vrvm != null){
                 if(isInputDeviceTracking(index) == false ){
-                	return null;
+                    return null;
                 }
-                
+
                 Object obs = environment.getObserver();
                 if( obs instanceof Camera ) {
                     tempq.set(((Camera)obs).getRotation());
                 } else {
                     tempq.set(((Spatial)obs).getWorldRotation());
                 }
-                
+
                 return tempq.multLocal(getOrientation(index));
             } else {
-            	throw new IllegalStateException("VR environment has no valid view manager.");
+                throw new IllegalStateException("VR environment has no valid view manager.");
             }
-            
 
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-    
-    @Override 
+
+    @Override
     public Vector3f getFinalObserverPosition(int index) {
-    	
-    	if (environment != null){
+        if (environment != null){
             OpenVRViewManager vrvm = (OpenVRViewManager)environment.getVRViewManager();
-            
+
             if (vrvm != null){
                 if(isInputDeviceTracking(index) == false ){
-                	return null;
+                    return null;
                 }
                 Object obs = environment.getObserver();
                 Vector3f pos = getPosition(index);
@@ -435,82 +420,79 @@ public class OpenVRInput implements VRInputAPI {
                     return pos.addLocal(((Spatial)obs).getWorldTranslation());
                 }
             } else {
-            	throw new IllegalStateException("VR environment has no valid view manager.");
+                throw new IllegalStateException("VR environment has no valid view manager.");
             }
-            
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
-    }    
-    
+
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
+    }
+
     @Override
     public void triggerHapticPulse(int controllerIndex, float seconds) {
         if( environment.isInVR() == false || isInputDeviceTracking(controllerIndex) == false ){
-        	return;
+            return;
         }
-        
+
         // apparently only axis ID of 0 works
         ((VR_IVRSystem_FnTable)environment.getVRHardware().getVRSystem()).TriggerHapticPulse.apply(OpenVRInput.controllerIndex[controllerIndex],
                                                                                                      0, (short)Math.round(3f * seconds / 1e-3f));
     }
-    
+
     @Override
     public void updateConnectedControllers() {
-    	logger.config("Updating connected controllers.");
-    	
-    	if (environment != null){
-    		controllerCount = 0;
-        	for(int i=0;i<JOpenVRLibrary.k_unMaxTrackedDeviceCount;i++) {
-        		int classCallback = ((OpenVR)environment.getVRHardware()).getVRSystem().GetTrackedDeviceClass.apply(i);
-        		if( classCallback == JOpenVRLibrary.ETrackedDeviceClass.ETrackedDeviceClass_TrackedDeviceClass_Controller || classCallback == JOpenVRLibrary.ETrackedDeviceClass.ETrackedDeviceClass_TrackedDeviceClass_GenericTracker) {
-	
-        			String controllerName   = "Unknown";
-    				String manufacturerName = "Unknown";
-    				try {
-    					controllerName = OpenVRUtil.getTrackedDeviceStringProperty(((OpenVR)environment.getVRHardware()).getVRSystem(), i, JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_TrackingSystemName_String);
-    					manufacturerName = OpenVRUtil.getTrackedDeviceStringProperty(((OpenVR)environment.getVRHardware()).getVRSystem(), i, JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_ManufacturerName_String);
-    				} catch (Exception e) {
+        logger.config("Updating connected controllers.");
+
+        if (environment != null){
+            controllerCount = 0;
+            for(int i=0;i<JOpenVRLibrary.k_unMaxTrackedDeviceCount;i++) {
+                int classCallback = ((OpenVR)environment.getVRHardware()).getVRSystem().GetTrackedDeviceClass.apply(i);
+                if( classCallback == JOpenVRLibrary.ETrackedDeviceClass.ETrackedDeviceClass_TrackedDeviceClass_Controller || classCallback == JOpenVRLibrary.ETrackedDeviceClass.ETrackedDeviceClass_TrackedDeviceClass_GenericTracker) {
+
+                    String controllerName   = "Unknown";
+                    String manufacturerName = "Unknown";
+                    try {
+                        controllerName = OpenVRUtil.getTrackedDeviceStringProperty(((OpenVR)environment.getVRHardware()).getVRSystem(), i, JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_TrackingSystemName_String);
+                        manufacturerName = OpenVRUtil.getTrackedDeviceStringProperty(((OpenVR)environment.getVRHardware()).getVRSystem(), i, JOpenVRLibrary.ETrackedDeviceProperty.ETrackedDeviceProperty_Prop_ManufacturerName_String);
+                    } catch (Exception e) {
                       logger.log(Level.WARNING, e.getMessage(), e);
-    				}
-        			
-        			controllerIndex[controllerCount] = i;
-        			
-        			// Adding tracked controller to control.
-        			if (trackedControllers == null){
-        				trackedControllers = new ArrayList<VRTrackedController>(JOpenVRLibrary.k_unMaxTrackedDeviceCount);
-        			}
-        			trackedControllers.add(new OpenVRTrackedController(i, this, controllerName, manufacturerName, environment));
-        			
-        			// Send a Haptic pulse to the controller
-        			triggerHapticPulse(controllerCount, 1.0f);
-        			
-        			controllerCount++;
-        			logger.config("  Tracked controller "+(i+1)+"/"+JOpenVRLibrary.k_unMaxTrackedDeviceCount+" "+controllerName+" ("+manufacturerName+") attached.");
-        		} else {
-        			logger.config("  Controller "+(i+1)+"/"+JOpenVRLibrary.k_unMaxTrackedDeviceCount+" ignored.");
-        		}
-        	}
-    	} else {
-    	  throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
+                    }
+
+                    controllerIndex[controllerCount] = i;
+
+                    // Adding tracked controller to control.
+                    if (trackedControllers == null){
+                        trackedControllers = new ArrayList<VRTrackedController>(JOpenVRLibrary.k_unMaxTrackedDeviceCount);
+                    }
+                    trackedControllers.add(new OpenVRTrackedController(i, this, controllerName, manufacturerName, environment));
+
+                    // Send a Haptic pulse to the controller
+                    triggerHapticPulse(controllerCount, 1.0f);
+
+                    controllerCount++;
+                    logger.config("  Tracked controller "+(i+1)+"/"+JOpenVRLibrary.k_unMaxTrackedDeviceCount+" "+controllerName+" ("+manufacturerName+") attached.");
+                } else {
+                    logger.config("  Controller "+(i+1)+"/"+JOpenVRLibrary.k_unMaxTrackedDeviceCount+" ignored.");
+                }
+            }
+        } else {
+          throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
 
     @Override
     public void updateControllerStates() {
-    	
-    	if (environment != null){
-        	for(int i=0;i<controllerCount;i++) {
-        		int index = controllerIndex[i];
-        		((OpenVR)environment.getVRHardware()).getVRSystem().GetControllerState.apply(index, cStates[index], 64);
-        		cStates[index].readField("ulButtonPressed");
-        		cStates[index].readField("rAxis");
-        		needsNewVelocity[index] = true;
-        		needsNewAngVelocity[index] = true;
-        	}
-    	} else {
-    		throw new IllegalStateException("VR input is not attached to a VR environment.");
-    	}
-
+        if (environment != null){
+            for(int i=0;i<controllerCount;i++) {
+                int index = controllerIndex[i];
+                ((OpenVR)environment.getVRHardware()).getVRSystem().GetControllerState.apply(index, cStates[index], 64);
+                cStates[index].readField("ulButtonPressed");
+                cStates[index].readField("rAxis");
+                needsNewVelocity[index] = true;
+                needsNewAngVelocity[index] = true;
+            }
+        } else {
+            throw new IllegalStateException("VR input is not attached to a VR environment.");
+        }
     }
-
 }

+ 72 - 75
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRMouseManager.java

@@ -12,95 +12,92 @@ import com.jme3.math.Vector2f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OpenVRMouseManager extends AbstractVRMouseManager {
+    private final int AVERAGE_AMNT = 4;
 
-	private final int AVERAGE_AMNT = 4;
-	
     private int avgCounter;
-	
+
     private final float[] lastXmv = new float[AVERAGE_AMNT];
-    
+
     private final float[] lastYmv = new float[AVERAGE_AMNT];
-    
+
     /**
      * Create a new VR mouse manager within the given {@link VREnvironment VR environment}.
      * @param environment the VR environment of the mouse manager.
      */
     public OpenVRMouseManager(VREnvironment environment){
-    	super(environment);
+        super(environment);
     }
-    
-    
+
     @Override
     public void updateAnalogAsMouse(int inputIndex, AnalogListener mouseListener, String mouseXName, String mouseYName, float tpf) {
-        
-    	if (getVREnvironment() != null){
-    		if (getVREnvironment().getApplication() != null){
-    			// got a tracked controller to use as the "mouse"
-    	        if( getVREnvironment().isInVR() == false || 
-    	        	getVREnvironment().getVRinput() == null ||
-    	        	getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
-    	        	return;
-    	        }
-    	        
-    	        Vector2f tpDelta;
-    	        // TODO option to use Touch joysticks
-    	        if( isThumbstickMode() ) {
-    	            tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
-    	        } else {
-    	            tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);            
-    	        }
-    	        
-    	        float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        
-    	        if( tpDelta.x < 0f ){
-    	        	Xamount = -Xamount;
-    	        }
-    	        
-    	        if( tpDelta.y < 0f ){
-    	        	Yamount = -Yamount;
-    	        }
-    	        
-    	        Xamount *= getMouseMoveScale(); 
-    	        Yamount *= getMouseMoveScale();
-    	        
-    	        if( mouseListener != null ) {
-    	            if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
-    	            if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);            
-    	        }
-    	        
-    	        if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
-    	            int index = (avgCounter+1) % AVERAGE_AMNT;
-    	            lastXmv[index] = Xamount * 133f;
-    	            lastYmv[index] = Yamount * 133f;
-    	            cursorPos.x -= avg(lastXmv);
-    	            cursorPos.y -= avg(lastYmv);
-    	            Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
-    	            
-    	            if( cursorPos.x > maxsize.x ){
-    	            	cursorPos.x = maxsize.x;
-    	            }
-    	            
-    	            if( cursorPos.x < 0f ){
-    	            	cursorPos.x = 0f;
-    	            }
-    	            
-    	            if( cursorPos.y > maxsize.y ){
-    	            	cursorPos.y = maxsize.y;
-    	            }
-    	            
-    	            if( cursorPos.y < 0f ){
-    	            	cursorPos.y = 0f;
-    	            }
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (getVREnvironment() != null){
+            if (getVREnvironment().getApplication() != null){
+                // got a tracked controller to use as the "mouse"
+                if( getVREnvironment().isInVR() == false ||
+                    getVREnvironment().getVRinput() == null ||
+                    getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
+                    return;
+                }
+
+                Vector2f tpDelta;
+                // TODO option to use Touch joysticks
+                if( isThumbstickMode() ) {
+                    tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
+                } else {
+                    tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);
+                }
+
+                float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
+                float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
+
+                if( tpDelta.x < 0f ){
+                    Xamount = -Xamount;
+                }
+
+                if( tpDelta.y < 0f ){
+                    Yamount = -Yamount;
+                }
+
+                Xamount *= getMouseMoveScale();
+                Yamount *= getMouseMoveScale();
+
+                if( mouseListener != null ) {
+                    if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
+                    if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);
+                }
+
+                if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
+                    int index = (avgCounter+1) % AVERAGE_AMNT;
+                    lastXmv[index] = Xamount * 133f;
+                    lastYmv[index] = Yamount * 133f;
+                    cursorPos.x -= avg(lastXmv);
+                    cursorPos.y -= avg(lastYmv);
+                    Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
+
+                    if( cursorPos.x > maxsize.x ){
+                        cursorPos.x = maxsize.x;
+                    }
+
+                    if( cursorPos.x < 0f ){
+                        cursorPos.x = 0f;
+                    }
+
+                    if( cursorPos.y > maxsize.y ){
+                        cursorPos.y = maxsize.y;
+                    }
+
+                    if( cursorPos.y < 0f ){
+                        cursorPos.y = 0f;
+                    }
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     private float avg(float[] arr) {
         float amt = 0f;
         for(float f : arr) amt += f;

+ 72 - 76
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRTrackedController.java

@@ -12,88 +12,84 @@ import com.jme3.math.Vector3f;
  *
  */
 public class OpenVRTrackedController implements VRTrackedController{
+    /**
+     * The index of the controller within the underlying VR API.
+     */
+    private int controllerIndex = -1;
+
+    /**
+     * The underlying VRAPI.
+     */
+    private OpenVRInput hardware     = null;
 
-	/**
-	 * The index of the controller within the underlying VR API.
-	 */
-	private int controllerIndex = -1;
-	
-	/**
-	 * The underlying VRAPI.
-	 */
-	private OpenVRInput hardware     = null;
-	
-	/**
-	 * The name of the controller.
-	 */
-	private String name;
-	
-	private VREnvironment environment;
-	
     /**
-	 * Wrap a new VR tracked controller on an OpenVR system.
-	 * @param controllerIndex the index of the controller within the underlying VR system.
-	 * @param hardware the underlying VR system.
-	 * @param name the name of the controller.
-	 * @param manufacturer the manufacturer of the controller.
-	 * @param environment the VR environment.
-	 */
+     * The name of the controller.
+     */
+    private String name;
+
+    private VREnvironment environment;
+
+    /**
+     * Wrap a new VR tracked controller on an OpenVR system.
+     * @param controllerIndex the index of the controller within the underlying VR system.
+     * @param hardware the underlying VR system.
+     * @param name the name of the controller.
+     * @param manufacturer the manufacturer of the controller.
+     * @param environment the VR environment.
+     */
     public OpenVRTrackedController(int controllerIndex, OpenVRInput hardware, String name, String manufacturer, VREnvironment environment){
-    	this.controllerIndex = controllerIndex;
-    	this.hardware        = hardware;
-    	
-    	this.name            = name;
-    	this.manufacturer    = manufacturer;
-    	
-    	this.environment     = environment;
+        this.controllerIndex = controllerIndex;
+        this.hardware        = hardware;
+
+        this.name            = name;
+        this.manufacturer    = manufacturer;
+
+        this.environment     = environment;
+    }
+
+    /**
+     * The manufacturer of the controller.
+     */
+    private String manufacturer;
+
+    @Override
+    public Vector3f getPosition() {
+        if (hardware != null){
+            return hardware.getPosition(controllerIndex);
+        } else {
+            throw new IllegalStateException("No underlying VR API.");
+        }
     }
-	
-	/**
-	 * The manufacturer of the controller.
-	 */
-	private String manufacturer;
-	
-	@Override
-	public Vector3f getPosition() {
-		if (hardware != null){
-			return hardware.getPosition(controllerIndex);
-		} else {
-			throw new IllegalStateException("No underlying VR API.");
-		}
-	}
 
-	@Override
-	public Quaternion getOrientation() {
+    @Override
+    public Quaternion getOrientation() {
         if (hardware != null){
-			return hardware.getOrientation(controllerIndex);
-		} else {
-			throw new IllegalStateException("No underlying VR API.");
-		}
-	}
+            return hardware.getOrientation(controllerIndex);
+        } else {
+            throw new IllegalStateException("No underlying VR API.");
+        }
+    }
 
-	@Override
-	public Matrix4f getPose(){
-		
-		if (environment != null){
-			 if (hardware != null){
-					return ((OpenVR)environment.getVRHardware()).poseMatrices[controllerIndex];
-				} else {
-					throw new IllegalStateException("No underlying VR API.");
-				}
-		} else {
-			throw new IllegalStateException("VR tracked device is not attached to any environment.");
-		}
-		
-		
-	}
-	
-	@Override
-	public String getControllerName() {
-		return name;
-	}
+    @Override
+    public Matrix4f getPose(){
+        if (environment != null){
+             if (hardware != null){
+                    return ((OpenVR)environment.getVRHardware()).poseMatrices[controllerIndex];
+                } else {
+                    throw new IllegalStateException("No underlying VR API.");
+                }
+        } else {
+            throw new IllegalStateException("VR tracked device is not attached to any environment.");
+        }
+    }
+
+    @Override
+    public String getControllerName() {
+        return name;
+    }
 
-	@Override
-	public String getControllerManufacturer() {
-		return manufacturer;
-	}
+    @Override
+    public String getControllerManufacturer() {
+        return manufacturer;
+    }
 }

+ 311 - 339
jme3-vr/src/main/java/com/jme3/input/vr/openvr/OpenVRViewManager.java

@@ -38,32 +38,31 @@ import java.util.logging.Logger;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OpenVRViewManager extends AbstractVRViewManager {
-
-	private static final Logger logger = Logger.getLogger(OpenVRViewManager.class.getName());
+    private static final Logger logger = Logger.getLogger(OpenVRViewManager.class.getName());
 
     // OpenVR values
     private VRTextureBounds_t leftTextureBounds;
     private Texture_t leftTextureType;
-    
+
     private VRTextureBounds_t rightTextureBounds;
     private Texture_t rightTextureType;
 
     private Texture2D dualEyeTex;
-    
+
     //final & temp values for camera calculations
     private final Vector3f finalPosition   = new Vector3f();
     private final Quaternion finalRotation = new Quaternion();
     private final Vector3f hmdPos          = new Vector3f();
     private final Quaternion hmdRot        = new Quaternion();
-    
+
     /**
      * Create a new VR view manager attached to the given {@link VREnvironment VR environment}.
      * @param environment the {@link VREnvironment VR environment} to which this view manager is attached.
      */
     public OpenVRViewManager(VREnvironment environment){
-    	this.environment = environment;
+        this.environment = environment;
     }
-    
+
     /**
      * Get the identifier of the left eye texture.
      * @return the identifier of the left eye texture.
@@ -73,7 +72,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
     protected int getLeftTexId() {
         return getLeftTexture().getImage().getId();
     }
-    
+
     /**
      * Get the identifier of the right eye texture.
      * @return the identifier of the right eye texture.
@@ -83,7 +82,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
     protected int getRightTexId() {
         return getRightTexture().getImage().getId();
     }
-    
+
     /**
      * Get the identifier of the full (dual eye) texture.
      * @return the identifier of the full (dual eye) texture.
@@ -93,16 +92,16 @@ public class OpenVRViewManager extends AbstractVRViewManager {
     private int getFullTexId() {
         return dualEyeTex.getImage().getId();
     }
-      
+
     /**
      * Initialize the system binds of the textures.
      */
     private void initTextureSubmitStructs() {
         leftTextureType = new Texture_t();
         rightTextureType = new Texture_t();
-        
+
         if (environment != null){
-        	if( environment.getVRHardware() instanceof OpenVR ) {
+            if( environment.getVRHardware() instanceof OpenVR ) {
                 leftTextureBounds = new VRTextureBounds_t();
                 rightTextureBounds = new VRTextureBounds_t();
                 // left eye
@@ -136,8 +135,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                 rightTextureType.setAutoRead(false);
                 rightTextureType.setAutoWrite(false);
                 rightTextureType.handle = -1;
-                
-                
+
                 logger.config("Init eyes native texture binds");
                 logger.config("  Left eye texture");
                 logger.config("           address: "+leftTextureType.getPointer());
@@ -157,30 +155,28 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                 logger.config("         auto read: "+rightTextureType.getAutoRead());
                 logger.config("        auto write: "+rightTextureType.getAutoWrite());
                 logger.config("    handle address: "+rightTextureType.handle);
-                logger.config("      handle value: "+rightTextureType.handle); 
+                logger.config("      handle value: "+rightTextureType.handle);
             }
         } else {
-    		throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
+            throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
+        }
     }
-    
+
     @Override
     public void render() {
-    	
     }
-    
+
     @Override
     public void postRender() {
-    	
-    	if (environment != null){
-    		if( environment.isInVR() ) {
+        if (environment != null){
+            if( environment.isInVR() ) {
                 VRAPI api = environment.getVRHardware();
                 if( api.getCompositor() != null ) {
                     // using the compositor...
                     int errl = 0, errr = 0;
                     if( environment.isInstanceRendering() ) {
                         if( leftTextureType.handle == -1 || leftTextureType.handle != getFullTexId() ) {
-                        	leftTextureType.handle = getFullTexId();
+                            leftTextureType.handle = getFullTexId();
                             if( leftTextureType.handle != -1 ) {
                                 leftTextureType.write();
                             }
@@ -195,14 +191,14 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                                leftTextureType.handle != getLeftTexId() || rightTextureType.handle != getRightTexId() ) {
                         leftTextureType.handle = getLeftTexId();
                         if( leftTextureType.handle != -1 ) {
-                        	logger.fine("Writing Left texture to native memory at " + leftTextureType.getPointer());
+                            logger.fine("Writing Left texture to native memory at " + leftTextureType.getPointer());
                             leftTextureType.write();
                         }
                         rightTextureType.handle = getRightTexId();
                         if( rightTextureType.handle != -1 ) {
-                        	logger.fine("Writing Right texture to native memory at " + leftTextureType.getPointer());
+                            logger.fine("Writing Right texture to native memory at " + leftTextureType.getPointer());
                             rightTextureType.write();
-                        }                    
+                        }
                     } else {
                         if( api instanceof OpenVR ) {
                             errl = ((OpenVR)api).getCompositor().Submit.apply(JOpenVRLibrary.EVREye.EVREye_Eye_Left, leftTextureType, null,
@@ -210,31 +206,30 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                             errr = ((OpenVR)api).getCompositor().Submit.apply(JOpenVRLibrary.EVREye.EVREye_Eye_Right, rightTextureType, null,
                                                                    JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default);
                         } else {
-                        	
+
                         }
                     }
-                    
+
                     if( errl != 0 ){
-                    	logger.severe("Submit to left compositor error: " + OpenVRUtil.getEVRCompositorErrorString(errl)+" ("+Integer.toString(errl)+")");
-                    	logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(leftTextureType.eColorSpace));
-                    	logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(leftTextureType.eType));
-                    	logger.severe("  Texture handle: "+leftTextureType.handle);
-                    	
+                        logger.severe("Submit to left compositor error: " + OpenVRUtil.getEVRCompositorErrorString(errl)+" ("+Integer.toString(errl)+")");
+                        logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(leftTextureType.eColorSpace));
+                        logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(leftTextureType.eType));
+                        logger.severe("  Texture handle: "+leftTextureType.handle);
+
                         logger.severe("  Left eye texture "+leftEyeTexture.getName()+" ("+leftEyeTexture.getImage().getId()+")");
                         logger.severe("                 Type: "+leftEyeTexture.getType());
                         logger.severe("                 Size: "+leftEyeTexture.getImage().getWidth()+"x"+leftEyeTexture.getImage().getHeight());
                         logger.severe("          Image depth: "+leftEyeTexture.getImage().getDepth());
                         logger.severe("         Image format: "+leftEyeTexture.getImage().getFormat());
                         logger.severe("    Image color space: "+leftEyeTexture.getImage().getColorSpace());
-                    	
                     }
-                    
+
                     if( errr != 0 ){
-                    	logger.severe("Submit to right compositor error: " + OpenVRUtil.getEVRCompositorErrorString(errl)+" ("+Integer.toString(errl)+")");
-                    	logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(rightTextureType.eColorSpace));
-                    	logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(rightTextureType.eType));
-                    	logger.severe("  Texture handle: "+rightTextureType.handle);
-                    	
+                        logger.severe("Submit to right compositor error: " + OpenVRUtil.getEVRCompositorErrorString(errl)+" ("+Integer.toString(errl)+")");
+                        logger.severe("  Texture color space: "+OpenVRUtil.getEColorSpaceString(rightTextureType.eColorSpace));
+                        logger.severe("  Texture type: "+OpenVRUtil.getETextureTypeString(rightTextureType.eType));
+                        logger.severe("  Texture handle: "+rightTextureType.handle);
+
                         logger.severe("  Right eye texture "+rightEyeTexture.getName()+" ("+rightEyeTexture.getImage().getId()+")");
                         logger.severe("                 Type: "+rightEyeTexture.getType());
                         logger.severe("                 Size: "+rightEyeTexture.getImage().getWidth()+"x"+rightEyeTexture.getImage().getHeight());
@@ -244,166 +239,152 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                     }
                 }
             }
-    	} else {
-    		throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
-    	
-    	
-                        
+        } else {
+            throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
+        }
     }
 
-
     @Override
-    public void initialize() {     
-    	
-    	logger.config("Initializing VR view manager.");
-    	
-    	if (environment != null){
-    	
+    public void initialize() {
+        logger.config("Initializing VR view manager.");
+
+        if (environment != null){
           initTextureSubmitStructs();
-          setupCamerasAndViews();        
-          setupVRScene();                    
-          moveScreenProcessingToEyes(); 
-        
+          setupCamerasAndViews();
+          setupVRScene();
+          moveScreenProcessingToEyes();
+
           if( environment.hasTraditionalGUIOverlay() ) {
-            	
             environment.getVRMouseManager().initialize();
-                
+
             // update the pose to position the gui correctly on start
             update(0f);
             environment.getVRGUIManager().positionGui();
-          }  
-            
+          }
+
           logger.config("Initialized VR view manager [SUCCESS]");
-          
+
         } else {
           throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
+        }
     }
-    
+
     /**
      * Prepare the size of the given {@link Camera camera} to adapt it to the underlying rendering context.
      * @param cam the {@link Camera camera} to prepare.
      * @param xMult the camera width multiplier.
      */
     private void prepareCameraSize(Camera cam, float xMult) {
-    	
-    	if (environment != null){
-    		
-    		if (environment.getApplication() != null){
-    			Vector2f size = new Vector2f();
-    	        VRAPI vrhmd = environment.getVRHardware();
-
-    	        if( vrhmd == null ) {
-    	            size.x = 1280f;
-    	            size.y = 720f;
-    	        } else {
-    	            vrhmd.getRenderSize(size);
-    	        }
-    	        
-    	        if( size.x < environment.getApplication().getContext().getSettings().getWidth() ) {
-    	            size.x = environment.getApplication().getContext().getSettings().getWidth();
-    	        }
-    	        if( size.y < environment.getApplication().getContext().getSettings().getHeight() ) {
-    	            size.y = environment.getApplication().getContext().getSettings().getHeight();
-    	        }
-    	        
-    	        if( environment.isInstanceRendering() ){
-    	        	size.x *= 2f;
-    	        }
-    	        
-    	        // other adjustments
-    	        size.x *= xMult;
-    	        size.x *= getResolutionMuliplier();
-    	        size.y *= getResolutionMuliplier();
-    	        
-    	        if( cam.getWidth() != size.x || cam.getHeight() != size.y ){
-    	        	cam.resize((int)size.x, (int)size.y, false);
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    		
-    	} else {
+        if (environment != null){
+
+            if (environment.getApplication() != null){
+                Vector2f size = new Vector2f();
+                VRAPI vrhmd = environment.getVRHardware();
+
+                if( vrhmd == null ) {
+                    size.x = 1280f;
+                    size.y = 720f;
+                } else {
+                    vrhmd.getRenderSize(size);
+                }
+
+                if( size.x < environment.getApplication().getContext().getSettings().getWidth() ) {
+                    size.x = environment.getApplication().getContext().getSettings().getWidth();
+                }
+                if( size.y < environment.getApplication().getContext().getSettings().getHeight() ) {
+                    size.y = environment.getApplication().getContext().getSettings().getHeight();
+                }
+
+                if( environment.isInstanceRendering() ){
+                    size.x *= 2f;
+                }
+
+                // other adjustments
+                size.x *= xMult;
+                size.x *= getResolutionMuliplier();
+                size.y *= getResolutionMuliplier();
+
+                if( cam.getWidth() != size.x || cam.getHeight() != size.y ){
+                    cam.resize((int)size.x, (int)size.y, false);
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+
+        } else {
           throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-    	}
-    	
-        
+        }
     }
-    
+
     /**
      * Replaces rootNode as the main cameras scene with the distortion mesh
      */
     private void setupVRScene(){
-    	
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    			// no special scene to setup if we are doing instancing
-    	        if( environment.isInstanceRendering() ) {
-    	            // distortion has to be done with compositor here... we want only one pass on our end!
-    	            if( environment.getApplication().getContext().getSettings().isSwapBuffers() ) {
-    	                setupMirrorBuffers(environment.getCamera(), dualEyeTex, true);
-    	            }       
-    	            return;
-    	        }
-    	        
-    	        leftEyeTexture  = (Texture2D) getLeftViewPort().getOutputFrameBuffer().getColorBuffer().getTexture();
-    	        rightEyeTexture = (Texture2D)getRightViewPort().getOutputFrameBuffer().getColorBuffer().getTexture();        
-    	        leftEyeDepth    = (Texture2D) getLeftViewPort().getOutputFrameBuffer().getDepthBuffer().getTexture();
-    	        rightEyeDepth   = (Texture2D)getRightViewPort().getOutputFrameBuffer().getDepthBuffer().getTexture();        
-    	      
-    	        // main viewport is either going to be a distortion scene or nothing
-    	        // mirroring is handled by copying framebuffers
-    	        Iterator<Spatial> spatialIter = environment.getApplication().getViewPort().getScenes().iterator();
-    	        while(spatialIter.hasNext()){
-    	        	environment.getApplication().getViewPort().detachScene(spatialIter.next());
-    	        }
-    	        
-    	        spatialIter = environment.getApplication().getGuiViewPort().getScenes().iterator();
-    	        while(spatialIter.hasNext()){
-    	        	environment.getApplication().getGuiViewPort().detachScene(spatialIter.next());
-    	        }
-    	        
-    	        // only setup distortion scene if compositor isn't running (or using custom mesh distortion option)
-    	        if( environment.getVRHardware().getCompositor() == null ) {
-    	            Node distortionScene = new Node();
-    	            Material leftMat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/OpenVR.j3md");
-    	            leftMat.setTexture("Texture", leftEyeTexture);
-    	            Geometry leftEye = new Geometry("box", setupDistortionMesh(JOpenVRLibrary.EVREye.EVREye_Eye_Left, environment.getVRHardware()));
-    	            leftEye.setMaterial(leftMat);
-    	            distortionScene.attachChild(leftEye);
-
-    	            Material rightMat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/OpenVR.j3md");
-    	            rightMat.setTexture("Texture", rightEyeTexture);
-    	            Geometry rightEye = new Geometry("box", setupDistortionMesh(JOpenVRLibrary.EVREye.EVREye_Eye_Right, environment.getVRHardware()));
-    	            rightEye.setMaterial(rightMat);
-    	            distortionScene.attachChild(rightEye);
-
-    	            distortionScene.updateGeometricState();
-
-    	            environment.getApplication().getViewPort().attachScene(distortionScene);
-    	            
-    	            //if( useCustomDistortion ) setupFinalFullTexture(app.getViewPort().getCamera());
-    	        }
-    	        
-    	        if( environment.getApplication().getContext().getSettings().isSwapBuffers() ) {
-    	            setupMirrorBuffers(environment.getCamera(), leftEyeTexture, false);
-    	            
-    	        } 
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (environment != null){
+            if (environment.getApplication() != null){
+                // no special scene to setup if we are doing instancing
+                if( environment.isInstanceRendering() ) {
+                    // distortion has to be done with compositor here... we want only one pass on our end!
+                    if( environment.getApplication().getContext().getSettings().isSwapBuffers() ) {
+                        setupMirrorBuffers(environment.getCamera(), dualEyeTex, true);
+                    }
+                    return;
+                }
+
+                leftEyeTexture  = (Texture2D) getLeftViewPort().getOutputFrameBuffer().getColorBuffer().getTexture();
+                rightEyeTexture = (Texture2D)getRightViewPort().getOutputFrameBuffer().getColorBuffer().getTexture();
+                leftEyeDepth    = (Texture2D) getLeftViewPort().getOutputFrameBuffer().getDepthBuffer().getTexture();
+                rightEyeDepth   = (Texture2D)getRightViewPort().getOutputFrameBuffer().getDepthBuffer().getTexture();
+
+                // main viewport is either going to be a distortion scene or nothing
+                // mirroring is handled by copying framebuffers
+                Iterator<Spatial> spatialIter = environment.getApplication().getViewPort().getScenes().iterator();
+                while(spatialIter.hasNext()){
+                    environment.getApplication().getViewPort().detachScene(spatialIter.next());
+                }
+
+                spatialIter = environment.getApplication().getGuiViewPort().getScenes().iterator();
+                while(spatialIter.hasNext()){
+                    environment.getApplication().getGuiViewPort().detachScene(spatialIter.next());
+                }
+
+                // only setup distortion scene if compositor isn't running (or using custom mesh distortion option)
+                if( environment.getVRHardware().getCompositor() == null ) {
+                    Node distortionScene = new Node();
+                    Material leftMat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/OpenVR.j3md");
+                    leftMat.setTexture("Texture", leftEyeTexture);
+                    Geometry leftEye = new Geometry("box", setupDistortionMesh(JOpenVRLibrary.EVREye.EVREye_Eye_Left, environment.getVRHardware()));
+                    leftEye.setMaterial(leftMat);
+                    distortionScene.attachChild(leftEye);
+
+                    Material rightMat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/OpenVR.j3md");
+                    rightMat.setTexture("Texture", rightEyeTexture);
+                    Geometry rightEye = new Geometry("box", setupDistortionMesh(JOpenVRLibrary.EVREye.EVREye_Eye_Right, environment.getVRHardware()));
+                    rightEye.setMaterial(rightMat);
+                    distortionScene.attachChild(rightEye);
+
+                    distortionScene.updateGeometricState();
+
+                    environment.getApplication().getViewPort().attachScene(distortionScene);
+
+                    //if( useCustomDistortion ) setupFinalFullTexture(app.getViewPort().getCamera());
+                }
+
+                if( environment.getApplication().getContext().getSettings().isSwapBuffers() ) {
+                    setupMirrorBuffers(environment.getCamera(), leftEyeTexture, false);
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	}         
+        }
     }
-    
+
     @Override
     public void update(float tpf) {
-        
-    	if (environment != null){
-    		// grab the observer
+        if (environment != null){
+            // grab the observer
             Object obs = environment.getObserver();
             Quaternion objRot;
             Vector3f objPos;
@@ -417,12 +398,10 @@ public class OpenVRViewManager extends AbstractVRViewManager {
             // grab the hardware handle
             VRAPI dev = environment.getVRHardware();
             if( dev != null ) {
-            	
-
                 // update the HMD's position & orientation
                 dev.updatePose();
                 dev.getPositionAndOrientation(hmdPos, hmdRot);
-/*                
+/*
                 // TOREMOVE
                 Vector3f v   = dev.getVRinput().getTrackedController(0).getPosition();
                 Quaternion q = dev.getVRinput().getTrackedController(0).getOrientation();
@@ -430,51 +409,51 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                     hmdPos.set(v);
                     hmdRot.set(q);
                 }
-                
-            	logger.severe("HMD controller ");
-            	logger.severe("  Position "+hmdPos);
-            	logger.severe("  Orientation "+hmdRot);
-            	
-            	VRTrackedController tc = null;
+
+                logger.severe("HMD controller ");
+                logger.severe("  Position "+hmdPos);
+                logger.severe("  Orientation "+hmdRot);
+
+                VRTrackedController tc = null;
                 for(int i = 0; i < dev.getVRinput().getTrackedControllerCount(); i++){
-                	tc = dev.getVRinput().getTrackedController(i);
-                	logger.severe("Tracked controller "+i+": "+tc.getControllerName());
-                	logger.severe("  Position "+tc.getPosition());
-                	logger.severe("  Orientation "+tc.getOrientation());
-                	logger.severe("");
+                    tc = dev.getVRinput().getTrackedController(i);
+                    logger.severe("Tracked controller "+i+": "+tc.getControllerName());
+                    logger.severe("  Position "+tc.getPosition());
+                    logger.severe("  Orientation "+tc.getOrientation());
+                    logger.severe("");
                 }
-*/                
+*/
                 // TOREMOVE
-                
+
                 if( obs != null ) {
                     // update hmdPos based on obs rotation
                     finalRotation.set(objRot);
                     finalRotation.mult(hmdPos, hmdPos);
                     finalRotation.multLocal(hmdRot);
                 }
-                
+
                 finalizeCamera(dev.getHMDVectorPoseLeftEye(), objPos, getLeftCamera());
                 finalizeCamera(dev.getHMDVectorPoseRightEye(), objPos, getRightCamera());
             } else {
-            	getLeftCamera().setFrame(objPos, objRot);
-            	getRightCamera().setFrame(objPos, objRot);
+                getLeftCamera().setFrame(objPos, objRot);
+                getRightCamera().setFrame(objPos, objRot);
             }
-            
+
             if( environment.hasTraditionalGUIOverlay() ) {
                 // update the mouse?
-            	environment.getVRMouseManager().update(tpf);
-            
+                environment.getVRMouseManager().update(tpf);
+
                 // update GUI position?
                 if( environment.getVRGUIManager().isWantsReposition() || environment.getVRGUIManager().getPositioningMode() != VRGUIPositioningMode.MANUAL ) {
-                	environment.getVRGUIManager().positionGuiNow(tpf);
-                	environment.getVRGUIManager().updateGuiQuadGeometricState();
+                    environment.getVRGUIManager().positionGuiNow(tpf);
+                    environment.getVRGUIManager().updateGuiQuadGeometricState();
                 }
             }
-    	} else {
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     /**
      * Place the camera within the scene.
      * @param eyePos the eye position.
@@ -488,184 +467,177 @@ public class OpenVRViewManager extends AbstractVRViewManager {
         finalPosition.y += getHeightAdjustment();
         cam.setFrame(finalPosition, finalRotation);
     }
-    
 
-    private void setupCamerasAndViews() { 
-    	
-    	if (environment != null){
-    		// get desired frustum from original camera
-            Camera origCam = environment.getCamera();        
+    private void setupCamerasAndViews() {
+        if (environment != null){
+            // get desired frustum from original camera
+            Camera origCam = environment.getCamera();
             float fFar = origCam.getFrustumFar();
             float fNear = origCam.getFrustumNear();
-            
+
             // restore frustum on distortion scene cam, if needed
             if( environment.isInstanceRendering() ) {
                 leftCamera = origCam;
             } else if( environment.compositorAllowed() == false ) {
                 origCam.setFrustumFar(100f);
-                origCam.setFrustumNear(1f); 
-                leftCamera = origCam.clone();  
+                origCam.setFrustumNear(1f);
+                leftCamera = origCam.clone();
                 prepareCameraSize(origCam, 2f);
             } else {
                 leftCamera = origCam.clone();
             }
-            
-            getLeftCamera().setFrustumPerspective(environment.getDefaultFOV(), environment.getDefaultAspect(), fNear, fFar);                     
-                    
+
+            getLeftCamera().setFrustumPerspective(environment.getDefaultFOV(), environment.getDefaultAspect(), fNear, fFar);
+
             prepareCameraSize(getLeftCamera(), 1f);
             if( environment.getVRHardware() != null ) {
-            	getLeftCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionLeftEye(getLeftCamera()));
+                getLeftCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionLeftEye(getLeftCamera()));
             }
             //org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_SRGB);
-            
+
             if( !environment.isInstanceRendering()) {
                 leftViewPort = setupViewBuffers(getLeftCamera(), LEFT_VIEW_NAME);
                 rightCamera = getLeftCamera().clone();
                 if( environment.getVRHardware() != null ){
-                	getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
+                    getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
                 }
                 rightViewPort = setupViewBuffers(getRightCamera(), RIGHT_VIEW_NAME);
             } else {
-            	
-            	if (environment.getApplication() != null){
-                	
-                	logger.severe("THIS CODE NEED CHANGES !!!");
+                if (environment.getApplication() != null){
+
+                    logger.severe("THIS CODE NEED CHANGES !!!");
                     leftViewPort = environment.getApplication().getViewPort();
                     //leftViewport.attachScene(app.getRootNode());
                     rightCamera = getLeftCamera().clone();
                     if( environment.getVRHardware() != null ){
-                    	getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
+                        getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
                     }
-                    
+
                     org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL30.GL_CLIP_DISTANCE0);
-                    
+
                     //FIXME: [jme-vr] Fix with JMonkey next release
                     //RenderManager._VRInstancing_RightCamProjection = camRight.getViewProjectionMatrix();
-                    setupFinalFullTexture(environment.getApplication().getViewPort().getCamera());   
-            	} else {
-        			throw new IllegalStateException("This VR environment is not attached to any application.");
-        		}
-         
+                    setupFinalFullTexture(environment.getApplication().getViewPort().getCamera());
+                } else {
+                    throw new IllegalStateException("This VR environment is not attached to any application.");
+                }
             }
-            
+
             // setup gui
             environment.getVRGUIManager().setupGui(getLeftCamera(), getRightCamera(), getLeftViewPort(), getRightViewPort());
-            
+
             if( environment.getVRHardware() != null ) {
                 // call these to cache the results internally
-            	environment.getVRHardware().getHMDMatrixPoseLeftEye();
-            	environment.getVRHardware().getHMDMatrixPoseRightEye();
+                environment.getVRHardware().getHMDMatrixPoseLeftEye();
+                environment.getVRHardware().getHMDMatrixPoseRightEye();
             }
-    	} else {
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
-    private ViewPort setupMirrorBuffers(Camera cam, Texture tex, boolean expand) {   
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    	        Camera clonecam = cam.clone();
-    	        ViewPort viewPort = environment.getApplication().getRenderManager().createPostView("MirrorView", clonecam);
-    	        clonecam.setParallelProjection(true);
-    	        viewPort.setClearFlags(true, true, true);
-    	        viewPort.setBackgroundColor(ColorRGBA.Black);
-    	        Picture pic = new Picture("fullscene");
-    	        pic.setLocalTranslation(-0.75f, -0.5f, 0f);
-    	        if( expand ) {
-    	            pic.setLocalScale(3f, 1f, 1f);
-    	        } else {
-    	            pic.setLocalScale(1.5f, 1f, 1f);            
-    	        }
-    	        pic.setQueueBucket(Bucket.Opaque);
-    	        pic.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, false);
-    	        viewPort.attachScene(pic);
-    	        viewPort.setOutputFrameBuffer(null);
-    	        
-    	        pic.updateGeometricState();
-    	        
-    	        return viewPort;
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+
+    private ViewPort setupMirrorBuffers(Camera cam, Texture tex, boolean expand) {
+        if (environment != null){
+            if (environment.getApplication() != null){
+                Camera clonecam = cam.clone();
+                ViewPort viewPort = environment.getApplication().getRenderManager().createPostView("MirrorView", clonecam);
+                clonecam.setParallelProjection(true);
+                viewPort.setClearFlags(true, true, true);
+                viewPort.setBackgroundColor(ColorRGBA.Black);
+                Picture pic = new Picture("fullscene");
+                pic.setLocalTranslation(-0.75f, -0.5f, 0f);
+                if( expand ) {
+                    pic.setLocalScale(3f, 1f, 1f);
+                } else {
+                    pic.setLocalScale(1.5f, 1f, 1f);
+                }
+                pic.setQueueBucket(Bucket.Opaque);
+                pic.setTexture(environment.getApplication().getAssetManager(), (Texture2D)tex, false);
+                viewPort.attachScene(pic);
+                viewPort.setOutputFrameBuffer(null);
+
+                pic.updateGeometricState();
+
+                return viewPort;
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     private void setupFinalFullTexture(Camera cam) {
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    	        // create offscreen framebuffer
-    	        FrameBuffer out = new FrameBuffer(cam.getWidth(), cam.getHeight(), 1);
-    	        //offBuffer.setSrgb(true);
-
-    	        //setup framebuffer's texture
-    	        dualEyeTex = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8);
-    	        dualEyeTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
-    	        dualEyeTex.setMagFilter(Texture.MagFilter.Bilinear);
-
-    	        logger.config("Dual eye texture "+dualEyeTex.getName()+" ("+dualEyeTex.getImage().getId()+")");
-    	        logger.config("               Type: "+dualEyeTex.getType());
-    	        logger.config("               Size: "+dualEyeTex.getImage().getWidth()+"x"+dualEyeTex.getImage().getHeight());
-    	        logger.config("        Image depth: "+dualEyeTex.getImage().getDepth());
-    	        logger.config("       Image format: "+dualEyeTex.getImage().getFormat());
-    	        logger.config("  Image color space: "+dualEyeTex.getImage().getColorSpace());
-    	        
-    	        //setup framebuffer to use texture
-    	        out.setDepthBuffer(Image.Format.Depth);
-    	        out.setColorTexture(dualEyeTex);       
-
-    	        ViewPort viewPort = environment.getApplication().getViewPort();
-    	        viewPort.setClearFlags(true, true, true);
-    	        viewPort.setBackgroundColor(ColorRGBA.Black);
-    	        viewPort.setOutputFrameBuffer(out);
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (environment != null){
+            if (environment.getApplication() != null){
+                // create offscreen framebuffer
+                FrameBuffer out = new FrameBuffer(cam.getWidth(), cam.getHeight(), 1);
+                //offBuffer.setSrgb(true);
+
+                //setup framebuffer's texture
+                dualEyeTex = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8);
+                dualEyeTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
+                dualEyeTex.setMagFilter(Texture.MagFilter.Bilinear);
+
+                logger.config("Dual eye texture "+dualEyeTex.getName()+" ("+dualEyeTex.getImage().getId()+")");
+                logger.config("               Type: "+dualEyeTex.getType());
+                logger.config("               Size: "+dualEyeTex.getImage().getWidth()+"x"+dualEyeTex.getImage().getHeight());
+                logger.config("        Image depth: "+dualEyeTex.getImage().getDepth());
+                logger.config("       Image format: "+dualEyeTex.getImage().getFormat());
+                logger.config("  Image color space: "+dualEyeTex.getImage().getColorSpace());
+
+                //setup framebuffer to use texture
+                out.setDepthBuffer(Image.Format.Depth);
+                out.setColorTexture(dualEyeTex);
+
+                ViewPort viewPort = environment.getApplication().getViewPort();
+                viewPort.setClearFlags(true, true, true);
+                viewPort.setBackgroundColor(ColorRGBA.Black);
+                viewPort.setOutputFrameBuffer(out);
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	}  
+        }
     }
-    
+
     private ViewPort setupViewBuffers(Camera cam, String viewName){
-    	
-    	if (environment != null){
-    		if (environment.getApplication() != null){
-    			// create offscreen framebuffer
-    	        FrameBuffer offBufferLeft = new FrameBuffer(cam.getWidth(), cam.getHeight(), 1);
-    	        //offBufferLeft.setSrgb(true);
-    	        
-    	        //setup framebuffer's texture
-    	        Texture2D offTex = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8);
-    	        offTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
-    	        offTex.setMagFilter(Texture.MagFilter.Bilinear);
-
-    	        //setup framebuffer to use texture
-    	        offBufferLeft.setDepthBuffer(Image.Format.Depth);
-    	        offBufferLeft.setColorTexture(offTex);        
-    	        
-    	        ViewPort viewPort = environment.getApplication().getRenderManager().createPreView(viewName, cam);
-    	        viewPort.setClearFlags(true, true, true);
-    	        viewPort.setBackgroundColor(ColorRGBA.Black);
-    	        
-    	        Iterator<Spatial> spatialIter = environment.getApplication().getViewPort().getScenes().iterator();
-    	        while(spatialIter.hasNext()){
-    	        	viewPort.attachScene(spatialIter.next());
-    	        }
-
-    	        //set viewport to render to offscreen framebuffer
-    	        viewPort.setOutputFrameBuffer(offBufferLeft);
-    	        return viewPort;
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+        if (environment != null){
+            if (environment.getApplication() != null){
+                // create offscreen framebuffer
+                FrameBuffer offBufferLeft = new FrameBuffer(cam.getWidth(), cam.getHeight(), 1);
+                //offBufferLeft.setSrgb(true);
+
+                //setup framebuffer's texture
+                Texture2D offTex = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8);
+                offTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
+                offTex.setMagFilter(Texture.MagFilter.Bilinear);
+
+                //setup framebuffer to use texture
+                offBufferLeft.setDepthBuffer(Image.Format.Depth);
+                offBufferLeft.setColorTexture(offTex);
+
+                ViewPort viewPort = environment.getApplication().getRenderManager().createPreView(viewName, cam);
+                viewPort.setClearFlags(true, true, true);
+                viewPort.setBackgroundColor(ColorRGBA.Black);
+
+                Iterator<Spatial> spatialIter = environment.getApplication().getViewPort().getScenes().iterator();
+                while(spatialIter.hasNext()){
+                    viewPort.attachScene(spatialIter.next());
+                }
+
+                //set viewport to render to offscreen framebuffer
+                viewPort.setOutputFrameBuffer(offBufferLeft);
+                return viewPort;
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	}  
+        }
     }
-    
+
     /**
      * Setup a distortion mesh for the stereo view.
      * @param eye the eye to apply.
@@ -675,7 +647,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
     public static Mesh setupDistortionMesh(int eye, VRAPI api) {
         Mesh distortionMesh = new Mesh();
         float m_iLensGridSegmentCountH = 43, m_iLensGridSegmentCountV = 43;
-        
+
         float w = 1f / (m_iLensGridSegmentCountH - 1f);
         float h = 1f / (m_iLensGridSegmentCountV - 1f);
 
@@ -688,7 +660,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
         float texcoordB[] = new float[(int) (m_iLensGridSegmentCountV * m_iLensGridSegmentCountH) * 2];
 
         int vertPos = 0, coordPos = 0;
-        
+
         float Xoffset = eye == JOpenVRLibrary.EVREye.EVREye_Eye_Left ? -1f : 0;
         for (int y = 0; y < m_iLensGridSegmentCountV; y++) {
             for (int x = 0; x < m_iLensGridSegmentCountH; x++) {
@@ -707,18 +679,18 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                     texcoordG[coordPos] = u;
                     texcoordG[coordPos + 1] = 1 - v;
                     texcoordB[coordPos] = u;
-                    texcoordB[coordPos + 1] = 1 - v;                    
+                    texcoordB[coordPos + 1] = 1 - v;
                 } else {
                     ((VR_IVRSystem_FnTable)api.getVRSystem()).ComputeDistortion.apply(eye, u, v, dc0);
-                    
+
                     texcoordR[coordPos] = dc0.rfRed[0];
                     texcoordR[coordPos + 1] = 1 - dc0.rfRed[1];
                     texcoordG[coordPos] = dc0.rfGreen[0];
                     texcoordG[coordPos + 1] = 1 - dc0.rfGreen[1];
                     texcoordB[coordPos] = dc0.rfBlue[0];
                     texcoordB[coordPos + 1] = 1 - dc0.rfBlue[1];
-                }                
-                
+                }
+
                 coordPos += 2;
             }
         }
@@ -736,7 +708,7 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                 b = (int) (m_iLensGridSegmentCountH * y + x + 1 + offset);
                 c = (int) ((y + 1) * m_iLensGridSegmentCountH + x + 1 + offset);
                 d = (int) ((y + 1) * m_iLensGridSegmentCountH + x + offset);
-                
+
                 indices[indexPos] = a;
                 indices[indexPos + 1] = b;
                 indices[indexPos + 2] = c;
@@ -748,8 +720,8 @@ public class OpenVRViewManager extends AbstractVRViewManager {
                 indexPos += 6;
             }
         }
-        
-        // OK, create the mesh        
+
+        // OK, create the mesh
         distortionMesh.setBuffer(VertexBuffer.Type.Position, 3, verts);
         distortionMesh.setBuffer(VertexBuffer.Type.Index, 1, indices);
         distortionMesh.setBuffer(VertexBuffer.Type.TexCoord, 2, texcoordR);

+ 32 - 37
jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVR.java

@@ -36,65 +36,64 @@ import java.nio.FloatBuffer;
 import java.util.logging.Logger;
 
 /**
- * A class that wraps an <a href="http://www.osvr.org/">OSVR</a> system. 
+ * A class that wraps an <a href="http://www.osvr.org/">OSVR</a> system.
  * @author reden - phr00t - https://github.com/phr00t
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OSVR implements VRAPI {
+    private static final Logger logger = Logger.getLogger(OSVR.class.getName());
 
-	private static final Logger logger = Logger.getLogger(OSVR.class.getName());
-	
-	/**
-	 * The first viewer index.
-	 */
+    /**
+     * The first viewer index.
+     */
     public static final int FIRST_VIEWER = 0;
-    
+
     /**
      * The left eye index.
      */
     public static final int EYE_LEFT = 0;
-    
+
     /**
      * The right eye index.
      */
     public static final int EYE_RIGHT = 1;
-    
+
     /**
      * The size of the left eye.
      */
     public static final NativeSize EYE_LEFT_SIZE = new NativeSize(EYE_LEFT);
-    
+
     /**
      * The size of the right eye.
      */
     public static final NativeSize EYE_RIGHT_SIZE = new NativeSize(EYE_RIGHT);
-    
+
     /**
      * The default J String.
      */
     public static byte[] defaultJString = { 'j', (byte)0 };
-    
+
     /**
      * The default OpenGL String.
      */
     public static byte[] OpenGLString = { 'O', 'p', 'e', 'n', 'G', 'L', (byte)0 };
-    
+
     private final Matrix4f[] eyeMatrix = new Matrix4f[2];
-    
+
     private PointerByReference grabRM;
     private PointerByReference grabRMOGL;
     private PointerByReference grabRIC;
-    
+
     OSVR_RenderParams.ByValue renderParams;
     OsvrClientKitLibrary.OSVR_ClientContext context;
     com.jme3.system.osvr.osvrrendermanageropengl.OSVR_GraphicsLibraryOpenGL.ByValue graphicsLibrary;
     Pointer renderManager, renderManagerOpenGL, renderInfoCollection, registerBufferState;
     OSVRInput VRinput;
     NativeSize numRenderInfo;
-    NativeSizeByReference grabNumInfo = new NativeSizeByReference();    
+    NativeSizeByReference grabNumInfo = new NativeSizeByReference();
     OSVR_RenderInfoOpenGL.ByValue eyeLeftInfo, eyeRightInfo;
     Matrix4f hmdPoseLeftEye;
-    Matrix4f hmdPoseRightEye;    
+    Matrix4f hmdPoseRightEye;
     Vector3f hmdPoseLeftEyeVec, hmdPoseRightEyeVec, hmdSeatToStand;
     OSVR_DisplayConfig displayConfig;
     OSVR_Pose3 hmdPose = new OSVR_Pose3();
@@ -102,25 +101,25 @@ public class OSVR implements VRAPI {
     Quaternion storeRot = new Quaternion();
     PointerByReference presentState = new PointerByReference();
     OSVR_OpenResultsOpenGL openResults = new OSVR_OpenResultsOpenGL();
-    
+
     long glfwContext;
     long renderManagerContext;
     long wglGLFW;
     long wglRM;
-    
+
     boolean initSuccess = false;
     boolean flipEyes = false;
-    
+
     private VREnvironment environment = null;
-    
+
     /**
      * Create a new <a href="http://www.osvr.org/">OSVR</a> system attached to the given {@link VREnvironment VR environment}.
      * @param environment the {@link VREnvironment VR environment} to which the input is attached.
      */
     public OSVR(VREnvironment environment){
-    	this.environment = environment;
+        this.environment = environment;
     }
-    
+
     /**
      * Access to the underlying OSVR structures.
      * @param leftView the left viewport.
@@ -140,14 +139,11 @@ public class OSVR implements VRAPI {
         retval = OsvrRenderManagerOpenGLLibrary.osvrRenderManagerFinishPresentRenderBuffers(renderManager, presentState.getValue(), renderParams, (byte)0);
         return retval == 0; // only check the last error, since if something errored above, the last call won't work & all calls will log to syserr
     }
-    
 
-     
     @Override
     public boolean initialize() {
-    	
-    	logger.config("Initialize OSVR system.");
-    	
+        logger.config("Initialize OSVR system.");
+
         hmdPose.setAutoSynch(false);
         context = OsvrClientKitLibrary.osvrClientInit(defaultJString, 0);
         VRinput = new OSVRInput(environment);
@@ -187,7 +183,7 @@ public class OSVR implements VRAPI {
         wglGLFW = org.lwjgl.opengl.WGL.wglGetCurrentContext();
         glfwContext = org.lwjgl.glfw.GLFW.glfwGetCurrentContext();
     }
-    
+
     /**
      * Enable context sharing.
      * @return <code>true</code> if the context is successfully shared and <code>false</code> otherwise.
@@ -199,9 +195,9 @@ public class OSVR implements VRAPI {
         } else {
             System.out.println("Context sharing problem...");
             return false;
-        }        
+        }
     }
-    
+
     @Override
     public boolean initVRCompositor(boolean allowed) {
         if( !allowed || renderManager != null ) return false;
@@ -231,7 +227,7 @@ public class OSVR implements VRAPI {
                 retval = OsvrRenderManagerOpenGLLibrary.osvrRenderManagerGetRenderInfoCollection(renderManager, renderParams, grabRIC);
                 if( retval == 0 ) {
                     renderInfoCollection = grabRIC.getValue();
-                    OsvrRenderManagerOpenGLLibrary.osvrRenderManagerGetNumRenderInfoInCollection(renderInfoCollection, grabNumInfo);  
+                    OsvrRenderManagerOpenGLLibrary.osvrRenderManagerGetNumRenderInfoInCollection(renderInfoCollection, grabNumInfo);
                     numRenderInfo = grabNumInfo.getValue();
                     eyeLeftInfo = new OSVR_RenderInfoOpenGL.ByValue();
                     eyeRightInfo = new OSVR_RenderInfoOpenGL.ByValue();
@@ -242,7 +238,7 @@ public class OSVR implements VRAPI {
                 OsvrRenderManagerOpenGLLibrary.osvrDestroyRenderManager(renderManager);
                 System.out.println("OSVR Render Manager Info Collection Error: " + retval);
                 return false;
-            }                
+            }
             OsvrRenderManagerOpenGLLibrary.osvrDestroyRenderManager(renderManager);
             System.out.println("OSVR Open Render Manager Display Error: " + retval);
             return false;
@@ -278,7 +274,6 @@ public class OSVR implements VRAPI {
 
     @Override
     public void printLatencyInfoToConsole(boolean set) {
-        
     }
 
     @Override
@@ -306,13 +301,13 @@ public class OSVR implements VRAPI {
     @Override
     public void getRenderSize(Vector2f store) {
         if( eyeLeftInfo == null || eyeLeftInfo.viewport.width == 0.0 ) {
-            store.x = 1280f; store.y = 720f;            
+            store.x = 1280f; store.y = 720f;
         } else {
             store.x = (float)eyeLeftInfo.viewport.width;
             store.y = (float)eyeLeftInfo.viewport.height;
         }
     }
-    
+
     /**
      * Read and update the eye info from the underlying OSVR system.
      */
@@ -456,7 +451,7 @@ public class OSVR implements VRAPI {
         }*/
         return null;
     }
-    
+
     @Override
     public HmdType getType() {
         return HmdType.OSVR;

+ 44 - 50
jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRInput.java

@@ -24,43 +24,42 @@ import com.sun.jna.ptr.PointerByReference;
 
 
 /**
- * A class that wraps an <a href="http://www.osvr.org/">OSVR</a> input. 
+ * A class that wraps an <a href="http://www.osvr.org/">OSVR</a> input.
  * @author reden - phr00t - https://github.com/phr00t
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OSVRInput implements VRInputAPI {
+    private static final Logger logger = Logger.getLogger(OSVRInput.class.getName());
 
-	private static final Logger logger = Logger.getLogger(OSVRInput.class.getName());
-	
     // position example: https://github.com/OSVR/OSVR-Core/blob/master/examples/clients/TrackerState.c
     // button example: https://github.com/OSVR/OSVR-Core/blob/master/examples/clients/ButtonCallback.c
     // analog example: https://github.com/OSVR/OSVR-Core/blob/master/examples/clients/AnalogCallback.c
-    
+
     private static final int ANALOG_COUNT = 3, BUTTON_COUNT = 7, CHANNEL_COUNT = 3;
-    
+
     OSVR_ClientInterface[][] buttons;
     OSVR_ClientInterface[][][] analogs;
     OSVR_ClientInterface[] hands;
-    
+
     OSVR_Pose3[] handState;
     Callback buttonHandler, analogHandler;
     OSVR_TimeValue tv = new OSVR_TimeValue();
     boolean[] isHandTracked = new boolean[2];
-    
+
     private float[][][] analogState;
     private float[][] buttonState;
-    
+
     private final Quaternion tempq = new Quaternion();
     private final Vector3f tempv = new Vector3f();
     private final Vector2f temp2 = new Vector2f();
     private final boolean[][] buttonDown = new boolean[16][16];
-    
+
     private static final Vector2f temp2Axis = new Vector2f();
     private static final Vector2f lastCallAxis[] = new Vector2f[16];
     private static float axisMultiplier = 1f;
-    
+
     private VREnvironment environment = null;
-    
+
     /**
      * Get the system String that identifies a controller.
      * @param left is the controller is the left one (<code>false</code> if the right controller is needed).
@@ -73,18 +72,18 @@ public class OSVRInput implements VRInputAPI {
         }
         return new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'r', 'i', 'g', 'h', 't', '/', index, (byte)0 };
     }
-    
+
     /**
      * The left hand system String.
      */
     public static byte[] leftHand = { '/', 'm', 'e', '/', 'h', 'a', 'n', 'd', 's', '/', 'l', 'e', 'f', 't', (byte)0 };
-    
+
     /**
      * The right hand system String.
      */
     public static byte[] rightHand = { '/', 'm', 'e', '/', 'h', 'a', 'n', 'd', 's', '/', 'r', 'i', 'g', 'h', 't', (byte)0 };
 
-    
+
     /**
      * Create a new <a href="http://www.osvr.org/">OSVR</a> input attached to the given {@link VREnvironment VR environment}.
      * @param environment the {@link VREnvironment VR environment} to which the input is attached.
@@ -92,8 +91,7 @@ public class OSVRInput implements VRInputAPI {
     public OSVRInput(VREnvironment environment){
       this.environment = environment;
     }
-    
-    
+
     @Override
     public boolean isButtonDown(int controllerIndex, VRInputType checkButton) {
         return buttonState[controllerIndex][checkButton.getValue()] != 0f;
@@ -120,14 +118,14 @@ public class OSVRInput implements VRInputAPI {
             }
         }
     }
-    
+
     @Override
-    public Vector2f getAxisDeltaSinceLastCall(int controllerIndex, VRInputType forAxis) {                
+    public Vector2f getAxisDeltaSinceLastCall(int controllerIndex, VRInputType forAxis) {
         int axisIndex = forAxis.getValue();
         temp2Axis.set(lastCallAxis[axisIndex]);
         lastCallAxis[axisIndex].set(getAxis(controllerIndex, forAxis));
         if( (temp2Axis.x != 0f || temp2Axis.y != 0f) && (lastCallAxis[axisIndex].x != 0f || lastCallAxis[axisIndex].y != 0f) ) {
-            temp2Axis.subtractLocal(lastCallAxis[axisIndex]);        
+            temp2Axis.subtractLocal(lastCallAxis[axisIndex]);
         } else {
             // move made from rest, don't count as a delta move
             temp2Axis.x = 0f;
@@ -159,7 +157,7 @@ public class OSVRInput implements VRInputAPI {
         temp2.y = analogState[controllerIndex][forAxis.getValue()][1] * axisMultiplier;
         return temp2;
     }
-    
+
     private OSVR_ClientInterface getInterface(byte[] str) {
         PointerByReference pbr = new PointerByReference();
         OsvrClientKitLibrary.osvrClientGetInterface((OsvrClientKitLibrary.OSVR_ClientContext)environment.getVRHardware().getVRSystem(), str, pbr);
@@ -168,12 +166,11 @@ public class OSVRInput implements VRInputAPI {
 
     @Override
     public boolean init() {
-        
-    	logger.config("Initialize OSVR input.");
-    	
+        logger.config("Initialize OSVR input.");
+
         buttonHandler = new Callback() {
             @SuppressWarnings("unused")
-			public void invoke(Pointer userdata, Pointer timeval, OSVR_ButtonReport report) {
+            public void invoke(Pointer userdata, Pointer timeval, OSVR_ButtonReport report) {
                 for(int i=0;i<2;i++) {
                     for(int j=0;j<BUTTON_COUNT;j++) {
                         if( buttons[i][j] == null ) continue;
@@ -183,11 +180,11 @@ public class OSVRInput implements VRInputAPI {
                         }
                     }
                 }
-            }                
-        };  
+            }
+        };
         analogHandler = new Callback() {
             @SuppressWarnings("unused")
-			public void invoke(Pointer userdata, Pointer timeval, OSVR_AnalogReport report) {
+            public void invoke(Pointer userdata, Pointer timeval, OSVR_AnalogReport report) {
                 for(int i=0;i<2;i++) {
                     for(int j=0;j<ANALOG_COUNT;j++) {
                         for(int k=0;k<CHANNEL_COUNT;k++) {
@@ -199,9 +196,9 @@ public class OSVRInput implements VRInputAPI {
                         }
                     }
                 }
-            }                
-        };  
-        
+            }
+        };
+
         buttons = new OSVR_ClientInterface[2][BUTTON_COUNT];
         analogs = new OSVR_ClientInterface[2][ANALOG_COUNT][CHANNEL_COUNT];
         buttonState = new float[2][BUTTON_COUNT];
@@ -214,18 +211,18 @@ public class OSVRInput implements VRInputAPI {
         for(int h=0;h<2;h++) {
             for(int i=0;i<BUTTON_COUNT-2;i++) {
                 buttons[h][i] = getInterface(getButtonString(h==0, (byte)Integer.toString(i).toCharArray()[0]));
-                OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[h][i], buttonHandler, buttons[h][i].getPointer()); 
+                OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[h][i], buttonHandler, buttons[h][i].getPointer());
             }
         }
         buttons[0][BUTTON_COUNT-2] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'l', 'e', 'f', 't', '/', 'b', 'u', 'm', 'p', 'e', 'r', (byte)0 } );
-        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[0][BUTTON_COUNT-2], buttonHandler, buttons[0][BUTTON_COUNT-2].getPointer()); 
+        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[0][BUTTON_COUNT-2], buttonHandler, buttons[0][BUTTON_COUNT-2].getPointer());
         buttons[1][BUTTON_COUNT-2] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'r', 'i', 'g', 'h', 't', '/', 'b', 'u', 'm', 'p', 'e', 'r', (byte)0 } );
-        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[1][BUTTON_COUNT-2], buttonHandler, buttons[1][BUTTON_COUNT-2].getPointer()); 
+        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[1][BUTTON_COUNT-2], buttonHandler, buttons[1][BUTTON_COUNT-2].getPointer());
         buttons[0][BUTTON_COUNT-1] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'l', 'e', 'f', 't', '/', 'j', 'o', 'y', 's', 't', 'i', 'c', 'k', '/', 'b', 'u', 't', 't', 'o', 'n', (byte)0 } );
-        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[0][BUTTON_COUNT-1], buttonHandler, buttons[0][BUTTON_COUNT-1].getPointer()); 
+        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[0][BUTTON_COUNT-1], buttonHandler, buttons[0][BUTTON_COUNT-1].getPointer());
         buttons[1][BUTTON_COUNT-1] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'r', 'i', 'g', 'h', 't', '/', 'j', 'o', 'y', 's', 't', 'i', 'c', 'k', '/', 'b', 'u', 't', 't', 'o', 'n', (byte)0 } );
-        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[1][BUTTON_COUNT-1], buttonHandler, buttons[1][BUTTON_COUNT-1].getPointer()); 
-            
+        OsvrClientKitLibrary.osvrRegisterButtonCallback(buttons[1][BUTTON_COUNT-1], buttonHandler, buttons[1][BUTTON_COUNT-1].getPointer());
+
         analogs[0][0][0] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'l', 'e', 'f', 't', '/', 't', 'r', 'i', 'g', 'g', 'e', 'r', (byte)0 } );
         analogs[1][0][0] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'r', 'i', 'g', 'h', 't', '/', 't', 'r', 'i', 'g', 'g', 'e', 'r', (byte)0 } );
         OsvrClientKitLibrary.osvrRegisterAnalogCallback(analogs[0][0][0], analogHandler, analogs[0][0][0].getPointer());
@@ -238,7 +235,7 @@ public class OSVRInput implements VRInputAPI {
         analogs[1][1][1] = getInterface(new byte[] { '/', 'c', 'o', 'n', 't', 'r', 'o', 'l', 'l', 'e', 'r', '/', 'r', 'i', 'g', 'h', 't', '/', 'j', 'o', 'y', 's', 't', 'i', 'c', 'k', '/', 'y', (byte)0 } );
         OsvrClientKitLibrary.osvrRegisterAnalogCallback(analogs[1][1][0], analogHandler, analogs[1][1][0].getPointer());
         OsvrClientKitLibrary.osvrRegisterAnalogCallback(analogs[1][1][1], analogHandler, analogs[1][1][1].getPointer());
-        
+
         return true;
     }
 
@@ -249,7 +246,6 @@ public class OSVRInput implements VRInputAPI {
 
     @Override
     public void updateConnectedControllers() {
-        
     }
 
     @Override
@@ -298,7 +294,7 @@ public class OSVRInput implements VRInputAPI {
 
     @Override
     public Quaternion getFinalObserverRotation(int index) {
-    	OSVRViewManager vrvm = (OSVRViewManager)environment.getVRViewManager();
+        OSVRViewManager vrvm = (OSVRViewManager)environment.getVRViewManager();
         if( vrvm == null || isInputDeviceTracking(index) == false ) return null;
         Object obs = environment.getObserver();
         if( obs instanceof Camera ) {
@@ -308,10 +304,10 @@ public class OSVRInput implements VRInputAPI {
         }
         return tempq.multLocal(getOrientation(index));
     }
-    
+
     @Override
     public Vector3f getFinalObserverPosition(int index) {
-    	OSVRViewManager vrvm = (OSVRViewManager) environment.getVRViewManager();
+        OSVRViewManager vrvm = (OSVRViewManager) environment.getVRViewManager();
         if( vrvm == null || isInputDeviceTracking(index) == false ) return null;
         Object obs = environment.getObserver();
         Vector3f pos = getPosition(index);
@@ -322,11 +318,10 @@ public class OSVRInput implements VRInputAPI {
             ((Spatial)obs).getWorldRotation().mult(pos, pos);
             return pos.addLocal(((Spatial)obs).getWorldTranslation());
         }
-    } 
+    }
 
     @Override
     public void triggerHapticPulse(int controllerIndex, float seconds) {
-        
     }
 
     @Override
@@ -338,16 +333,15 @@ public class OSVRInput implements VRInputAPI {
     public float getAxisMultiplier() {
         return axisMultiplier;
     }
-    
+
     @Override
     public void setAxisMultiplier(float set) {
         axisMultiplier = set;
     }
 
-	@Override
-	public VRTrackedController getTrackedController(int index) {
-		// TODO Auto-generated method stub
-		return null;
-	}
-    
+    @Override
+    public VRTrackedController getTrackedController(int index) {
+        // TODO Auto-generated method stub
+        return null;
+    }
 }

+ 73 - 75
jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRMouseManager.java

@@ -11,95 +11,93 @@ import com.jme3.math.Vector2f;
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
 public class OSVRMouseManager extends AbstractVRMouseManager {
+    private final int AVERAGE_AMNT = 4;
 
-	private final int AVERAGE_AMNT = 4;
-	
     private int avgCounter;
-	
+
     private final float[] lastXmv = new float[AVERAGE_AMNT];
-    
+
     private final float[] lastYmv = new float[AVERAGE_AMNT];
-    
+
     /**
      * Create a new VR mouse manager within the given {@link VREnvironment VR environment}.
      * @param environment the VR environment of the mouse manager.
      */
     public OSVRMouseManager(VREnvironment environment){
-    	super(environment);
+        super(environment);
     }
-    
-    
+
     @Override
     public void updateAnalogAsMouse(int inputIndex, AnalogListener mouseListener, String mouseXName, String mouseYName, float tpf) {
-        
-    	if (getVREnvironment() != null){
-    		if (getVREnvironment().getApplication() != null){
-    			// got a tracked controller to use as the "mouse"
-    	        if( getVREnvironment().isInVR() == false || 
-    	        	getVREnvironment().getVRinput() == null ||
-    	        	getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
-    	        	return;
-    	        }
-    	        
-    	        Vector2f tpDelta;
-    	        // TODO option to use Touch joysticks
-    	        if( isThumbstickMode() ) {
-    	            tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
-    	        } else {
-    	            tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);            
-    	        }
-    	        
-    	        float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
-    	        
-    	        if( tpDelta.x < 0f ){
-    	        	Xamount = -Xamount;
-    	        }
-    	        
-    	        if( tpDelta.y < 0f ){
-    	        	Yamount = -Yamount;
-    	        }
-    	        
-    	        Xamount *= getMouseMoveScale(); 
-    	        Yamount *= getMouseMoveScale();
-    	        
-    	        if( mouseListener != null ) {
-    	            if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
-    	            if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);            
-    	        }
-    	        
-    	        if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
-    	            int index = (avgCounter+1) % AVERAGE_AMNT;
-    	            lastXmv[index] = Xamount * 133f;
-    	            lastYmv[index] = Yamount * 133f;
-    	            cursorPos.x -= avg(lastXmv);
-    	            cursorPos.y -= avg(lastYmv);
-    	            Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
-    	            
-    	            if( cursorPos.x > maxsize.x ){
-    	            	cursorPos.x = maxsize.x;
-    	            }
-    	            
-    	            if( cursorPos.x < 0f ){
-    	            	cursorPos.x = 0f;
-    	            }
-    	            
-    	            if( cursorPos.y > maxsize.y ){
-    	            	cursorPos.y = maxsize.y;
-    	            }
-    	            
-    	            if( cursorPos.y < 0f ){
-    	            	cursorPos.y = 0f;
-    	            }
-    	        }
-    		} else {
-    			throw new IllegalStateException("This VR environment is not attached to any application.");
-    		}
-    	} else {
+
+        if (getVREnvironment() != null){
+            if (getVREnvironment().getApplication() != null){
+                // got a tracked controller to use as the "mouse"
+                if( getVREnvironment().isInVR() == false ||
+                    getVREnvironment().getVRinput() == null ||
+                    getVREnvironment().getVRinput().isInputDeviceTracking(inputIndex) == false ){
+                    return;
+                }
+
+                Vector2f tpDelta;
+                // TODO option to use Touch joysticks
+                if( isThumbstickMode() ) {
+                    tpDelta = getVREnvironment().getVRinput().getAxis(inputIndex, VRInputType.ViveTrackpadAxis);
+                } else {
+                    tpDelta = getVREnvironment().getVRinput().getAxisDeltaSinceLastCall(inputIndex, VRInputType.ViveTrackpadAxis);
+                }
+
+                float Xamount = (float)Math.pow(Math.abs(tpDelta.x) * getSpeedSensitivity(), getSpeedAcceleration());
+                float Yamount = (float)Math.pow(Math.abs(tpDelta.y) * getSpeedSensitivity(), getSpeedAcceleration());
+
+                if( tpDelta.x < 0f ){
+                    Xamount = -Xamount;
+                }
+
+                if( tpDelta.y < 0f ){
+                    Yamount = -Yamount;
+                }
+
+                Xamount *= getMouseMoveScale();
+                Yamount *= getMouseMoveScale();
+
+                if( mouseListener != null ) {
+                    if( tpDelta.x != 0f && mouseXName != null ) mouseListener.onAnalog(mouseXName, Xamount * 0.2f, tpf);
+                    if( tpDelta.y != 0f && mouseYName != null ) mouseListener.onAnalog(mouseYName, Yamount * 0.2f, tpf);
+                }
+
+                if( getVREnvironment().getApplication().getInputManager().isCursorVisible() ) {
+                    int index = (avgCounter+1) % AVERAGE_AMNT;
+                    lastXmv[index] = Xamount * 133f;
+                    lastYmv[index] = Yamount * 133f;
+                    cursorPos.x -= avg(lastXmv);
+                    cursorPos.y -= avg(lastYmv);
+                    Vector2f maxsize = getVREnvironment().getVRGUIManager().getCanvasSize();
+
+                    if( cursorPos.x > maxsize.x ){
+                        cursorPos.x = maxsize.x;
+                    }
+
+                    if( cursorPos.x < 0f ){
+                        cursorPos.x = 0f;
+                    }
+
+                    if( cursorPos.y > maxsize.y ){
+                        cursorPos.y = maxsize.y;
+                    }
+
+                    if( cursorPos.y < 0f ){
+                        cursorPos.y = 0f;
+                    }
+                }
+            } else {
+                throw new IllegalStateException("This VR environment is not attached to any application.");
+            }
+        } else {
             throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
-      	} 
+        }
     }
-    
+
     private float avg(float[] arr) {
         float amt = 0f;
         for(float f : arr) amt += f;

File diff suppressed because it is too large
+ 407 - 425
jme3-vr/src/main/java/com/jme3/input/vr/osvr/OSVRViewManager.java


+ 32 - 34
jme3-vr/src/main/java/com/jme3/shadow/AbstractShadowRendererVR.java

@@ -97,7 +97,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
     protected boolean renderBackFacesShadows;
 
     protected AppProfiler profiler = null;
-    
+
     /**
      * true if the fallback material should be used, otherwise false
      */
@@ -125,13 +125,13 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
      * true to skip the post pass when there are no shadow casters
      */
     protected boolean skipPostPass;
-    
+
     /**
      * used for serialization
      */
-    protected AbstractShadowRendererVR(){        
-    }    
-    
+    protected AbstractShadowRendererVR(){
+    }
+
     /**
      * Create an abstract shadow renderer. Subclasses invoke this constructor.
      *
@@ -174,7 +174,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
 
             //DO NOT COMMENT THIS (It prevents the OSX incomplete read buffer crash.)
             shadowFB[i].addColorTarget(FrameBufferTarget.newTarget(dummyTex));
-            shadowMapStringCache[i] = "ShadowMap" + i; 
+            shadowMapStringCache[i] = "ShadowMap" + i;
             lightViewStringCache[i] = "LightViewProjectionMatrix" + i;
 
             postshadowMat.setTexture(shadowMapStringCache[i], shadowMaps[i]);
@@ -337,7 +337,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
             initFrustumCam();
         }
     }
-    
+
     /**
      * delegates the initialization of the frustum cam to child renderers
      */
@@ -356,7 +356,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
     /**
      * Invoked once per frame to update the shadow cams according to the light
      * view.
-     * 
+     *
      * @param viewCam the scene cam
      */
     protected abstract void updateShadowCams(Camera viewCam);
@@ -380,11 +380,11 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
      */
     protected abstract Camera getShadowCam(int shadowMapIndex);
 
-	@Override
-	public void setProfiler(AppProfiler profiler) {
-		this.profiler = profiler;
-	}
-    
+    @Override
+    public void setProfiler(AppProfiler profiler) {
+        this.profiler = profiler;
+    }
+
     /**
      * responsible for displaying the frustum of the shadow cam for debug
      * purpose
@@ -405,7 +405,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
         }
 
         updateShadowCams(viewPort.getCamera());
-        
+
         Renderer r = renderManager.getRenderer();
         renderManager.setForcedMaterial(preshadowMat);
         renderManager.setForcedTechnique("PreShadow");
@@ -426,14 +426,13 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
         renderManager.setForcedMaterial(null);
         renderManager.setForcedTechnique(null);
         renderManager.setCamera(viewPort.getCamera(), false);
-        
     }
 
     protected void renderShadowMap(int shadowMapIndex) {
         shadowMapOccluders = getOccludersToRender(shadowMapIndex, shadowMapOccluders);
         Camera shadowCam = getShadowCam(shadowMapIndex);
 
-        //saving light view projection matrix for this split            
+        //saving light view projection matrix for this split
         lightViewProjectionsMatrices[shadowMapIndex].set(shadowCam.getViewProjectionMatrix());
         renderManager.setCamera(shadowCam, false);
 
@@ -488,7 +487,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
         if (debug) {
             displayShadowMap(renderManager.getRenderer());
         }
-        
+
         getReceivers(lightReceivers);
 
         if (lightReceivers.size() != 0) {
@@ -511,26 +510,25 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
             renderManager.setForcedTechnique(null);
             renderManager.setForcedMaterial(null);
             renderManager.setCamera(cam, false);
-            
+
             //clearing the params in case there are some other shadow renderers
             clearMatParams();
         }
     }
-    
+
     /**
      * This method is called once per frame and is responsible for clearing any
      * material parameters that subclasses may need to clear on the post material.
      *
-     * @param material the material that was used for the post shadow pass     
+     * @param material the material that was used for the post shadow pass
      */
-    protected abstract void clearMaterialParameters(Material material);    
-    
+    protected abstract void clearMaterialParameters(Material material);
+
     private void clearMatParams(){
         for (Material mat : matCache) {
-         
-            //clearing only necessary params, the others may be set by other 
-            //renderers 
-            //Note that j start at 1 because other shadow renderers will have 
+            //clearing only necessary params, the others may be set by other
+            //renderers
+            //Note that j start at 1 because other shadow renderers will have
             //at least 1 shadow map and will set it on each frame anyway.
             for (int j = 1; j < nbShadowMaps; j++) {
                 mat.clearParam(lightViewStringCache[j]);
@@ -540,8 +538,8 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
             }
             mat.clearParam("FadeInfo");
             clearMaterialParameters(mat);
-        }        
-        //No need to clear the postShadowMat params as the instance is locale to each renderer       
+        }
+        //No need to clear the postShadowMat params as the instance is locale to each renderer
     }
 
     /**
@@ -618,7 +616,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
         }
         postshadowMat.setBoolean("BackfaceShadows", renderBackFacesShadows);
     }
-    
+
     /**
      * How far the shadows are rendered in the view
      *
@@ -637,7 +635,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
      * @param zFar the zFar values that override the computed one
      */
     public void setShadowZExtend(float zFar) {
-        this.zFarOverride = zFar;        
+        this.zFarOverride = zFar;
         if(zFarOverride == 0){
             fadeInfo = null;
             frustumCam = null;
@@ -650,7 +648,7 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
             }
         }
     }
-    
+
     /**
      * Define the length over which the shadow will fade out when using a
      * shadowZextend This is useful to make dynamic shadows fade into baked
@@ -686,15 +684,15 @@ public abstract class AbstractShadowRendererVR implements SceneProcessor, Savabl
         }
         return 0f;
     }
-    
+
     /**
      * returns true if the light source bounding box is in the view frustum
      * @return true if box in frustum
      */
     protected abstract boolean checkCulling(Camera viewCam);
-    
+
     @Override
-    public void preFrame(float tpf) {           
+    public void preFrame(float tpf) {
     }
 
     @Override

+ 14 - 15
jme3-vr/src/main/java/com/jme3/shadow/InstancedDirectionalShadowFilter.java

@@ -10,18 +10,17 @@ import com.jme3.renderer.Camera;
  * @author reden - phr00t - https://github.com/phr00t
  * @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
  */
-public class InstancedDirectionalShadowFilter extends DirectionalLightShadowFilterVR {    
-    
+public class InstancedDirectionalShadowFilter extends DirectionalLightShadowFilterVR {
     private final Vector4f temp4f = new Vector4f(), temp4f2 = new Vector4f();
-    
+
     private boolean instanceRendering = false;
 
     private Camera rightCamera = null;
-    
-	/**
+
+    /**
      * Create a new instanced version of the {@link DirectionalLightShadowFilterVR directional light shadow filter}.
      * @param application the application that this filter is attached to.
-     * @param camera 
+     * @param camera
      * @param shadowMapSize the size of the rendered shadowmaps (512, 1024, 2048, etc...)
      * @param nbSplits the number of shadow maps rendered (the more shadow maps the more quality, the less fps).
      * @param instancedRendering <code>true</code> if this filter has to use instance rendering and <code>false</code> otherwise.
@@ -31,9 +30,9 @@ public class InstancedDirectionalShadowFilter extends DirectionalLightShadowFilt
         super(application.getAssetManager(), shadowMapSize, nbSplits, "Common/MatDefs/VR/PostShadowFilter.j3md");
         this.instanceRendering = instancedRendering;
         this.rightCamera = rightCamera;
-    }        
-    
-    @Override    
+    }
+
+    @Override
     protected void preFrame(float tpf) {
         shadowRenderer.preFrame(tpf);
         if( instanceRendering ) {
@@ -45,22 +44,22 @@ public class InstancedDirectionalShadowFilter extends DirectionalLightShadowFilt
         Matrix4f m = viewPort.getCamera().getViewProjectionMatrix();
         material.setVector4("ViewProjectionMatrixRow2", temp4f.set(m.m20, m.m21, m.m22, m.m23));
     }
-    
+
     /**
      * Get if this filter is using instance rendering.
      * @return <code>true</code> if this filter is using instance rendering and <code>false</code> otherwise.
      * @see #setInstanceRendering(boolean)
      */
     public boolean isInstanceRendering() {
-		return instanceRendering;
-	}
+        return instanceRendering;
+    }
 
     /**
      * Set if this filter has to use instance rendering.
      * @param instanceRendering <code>true</code> if this filter has to use instance rendering and <code>false</code> otherwise.
      * @see #isInstanceRendering()
      */
-	public void setInstanceRendering(boolean instanceRendering) {
-		this.instanceRendering = instanceRendering;
-	}
+    public void setInstanceRendering(boolean instanceRendering) {
+        this.instanceRendering = instanceRendering;
+    }
 }

+ 5 - 5
jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglContextVR.java

@@ -92,9 +92,9 @@ public abstract class LwjglContextVR implements JmeContext {
 
     protected int determineMaxSamples() {
         // If we already have a valid context, determine samples using current context.
-    	logger.log(Level.SEVERE, "glfwExtensionSupported(\"GL_ARB_framebuffer_object\"): "+GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object"));
-    	logger.log(Level.SEVERE, "glfwExtensionSupported(\"GL_EXT_framebuffer_multisample\"): "+GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object"));
-    	
+        logger.log(Level.SEVERE, "glfwExtensionSupported(\"GL_ARB_framebuffer_object\"): "+GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object"));
+        logger.log(Level.SEVERE, "glfwExtensionSupported(\"GL_EXT_framebuffer_multisample\"): "+GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object"));
+
         if (GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object")) {
             return glGetInteger(ARBFramebufferObject.GL_MAX_SAMPLES);
         } else if (GLFW.glfwExtensionSupported("GL_EXT_framebuffer_multisample")) {
@@ -194,7 +194,7 @@ public abstract class LwjglContextVR implements JmeContext {
         if (capabilities.GL_ARB_debug_output && settings.getBoolean("GraphicsDebug")) {
             ARBDebugOutput.glDebugMessageCallbackARB(new LwjglGLDebugOutputHandler(), 0);
         }
-        
+
         renderer.setMainFrameBufferSrgb(settings.isGammaCorrection());
         renderer.setLinearizeSrgbImages(settings.isGammaCorrection());
 
@@ -253,7 +253,7 @@ public abstract class LwjglContextVR implements JmeContext {
     }
 
     /**
-     * 
+     *
      * @param createdVal
      */
     protected void waitFor(boolean createdVal) {

+ 7 - 10
jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglDisplayVR.java

@@ -40,18 +40,15 @@ import com.jme3.opencl.Context;
  * @author Julien Seinturier - (c) 2016 - JOrigin project - <a href="http://www.jorigin.org">http:/www.jorigin.org</a>
  */
 public class LwjglDisplayVR extends LwjglWindowVR {
-
-	/**
-	 * Create a new VR oriented LWJGL display.
-	 */
+    /**
+     * Create a new VR oriented LWJGL display.
+     */
     public LwjglDisplayVR() {
         super(Type.Display);
     }
 
-	@Override
-	public Context getOpenCLContext() {
-		return null;
-	}
-
-   
+    @Override
+    public Context getOpenCLContext() {
+        return null;
+    }
 }

+ 3 - 6
jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglOffscreenBufferVR.java

@@ -41,13 +41,10 @@ import com.jme3.system.JmeContext;
  * @author Julien Seinturier - (c) 2016 - JOrigin project - <a href="http://www.jorigin.org">http:/www.jorigin.org</a>
  */
 public class LwjglOffscreenBufferVR extends LwjglWindow {
-
-	/**
-	 * Create a new VR oriented LWJGL offscreen buffer.
-	 */
+    /**
+     * Create a new VR oriented LWJGL offscreen buffer.
+     */
     public LwjglOffscreenBufferVR() {
         super(JmeContext.Type.OffscreenSurface);
     }
-
-   
 }

+ 6 - 15
jme3-vr/src/main/java/com/jme3/system/lwjgl/LwjglWindowVR.java

@@ -206,9 +206,9 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
 
         glfwSetWindowFocusCallback(window, windowFocusCallback = new GLFWWindowFocusCallback() {
 
-			@Override
-			public void invoke(long window, boolean focused) {
-				if (wasActive != focused) {
+            @Override
+            public void invoke(long window, boolean focused) {
+                if (wasActive != focused) {
                     if (wasActive == false) {
                         listener.gainFocus();
                         timer.reset();
@@ -217,10 +217,8 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
                         listener.loseFocus();
                         wasActive = false;
                     }
-
-                    
                 }
-			}
+            }
         });
 
         // Center the window
@@ -245,7 +243,6 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
         // Make the window visible
         if (Type.Display.equals(type)) {
             glfwShowWindow(window);
-            
             glfwFocusWindow(window);
         }
 
@@ -274,20 +271,16 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
 
             if (errorCallback != null) {
                 errorCallback.free();
-            	errorCallback = null;
+                errorCallback = null;
             }
 
             if (windowSizeCallback != null) {
-
                 windowSizeCallback.free();
-                
                 windowSizeCallback = null;
             }
 
             if (windowFocusCallback != null) {
-            	
                 windowFocusCallback.free();
-                
                 windowFocusCallback = null;
             }
 
@@ -455,7 +448,6 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
                     + "Must set with JmeContext.setSystemListener().");
         }
 
- 
         LOGGER.log(Level.FINE, "Using LWJGL {0}", Version.getVersion());
 
         if (!initInThread()) {
@@ -546,8 +538,7 @@ public abstract class LwjglWindowVR extends LwjglContextVR implements Runnable {
         }
         return out;
     }
-    
-    
+
     private ByteBuffer imageToByteBuffer(BufferedImage image) {
         if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) {
             BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);

+ 6 - 6
jme3-vr/src/main/java/com/jme3/util/VRGUIPositioningMode.java

@@ -6,10 +6,10 @@ package com.jme3.util;
  *
  */
 public enum VRGUIPositioningMode {
-	MANUAL, 
-	AUTO_CAM_ALL, 
-	AUTO_CAM_ALL_SKIP_PITCH, 
-	AUTO_OBSERVER_POS_CAM_ROTATION, 
-	AUTO_OBSERVER_ALL, 
-	AUTO_OBSERVER_ALL_CAMHEIGHT
+    MANUAL,
+    AUTO_CAM_ALL,
+    AUTO_CAM_ALL_SKIP_PITCH,
+    AUTO_OBSERVER_POS_CAM_ROTATION,
+    AUTO_OBSERVER_ALL,
+    AUTO_OBSERVER_ALL_CAMHEIGHT
 }

+ 434 - 445
jme3-vr/src/main/java/com/jme3/util/VRGuiManager.java

@@ -30,449 +30,438 @@ import java.util.Iterator;
  *
  */
 public class VRGuiManager {
-
-	private Camera camLeft, camRight;
-	private float guiDistance = 1.5f;
-	private float guiScale = 1f;
-	private float guiPositioningElastic;
-
-	private VRGUIPositioningMode posMode = VRGUIPositioningMode.AUTO_CAM_ALL;
-
-	private final Matrix3f orient = new Matrix3f();
-	private Vector2f screenSize;
-	protected boolean wantsReposition;
-
-	private Vector2f ratio;
-
-	private final Vector3f EoldPos = new Vector3f();
-
-	private final Quaternion EoldDir = new Quaternion();
-
-	private final Vector3f look    = new Vector3f();
-	private final Vector3f left    = new Vector3f();
-	private final Vector3f temppos = new Vector3f();
-	private final Vector3f up      = new Vector3f();
-
-	private boolean useCurvedSurface = false;
-	private boolean overdraw = false;
-	private Geometry guiQuad;
-	private Node guiQuadNode;
-	private ViewPort offView;
-	private Texture2D guiTexture;
-
-	private final Quaternion tempq = new Quaternion();
-
-	private VREnvironment environment = null;
-
-	/**
-	 * Create a new GUI manager attached to the given app state.
-	 * @param environment the VR environment to which this manager is attached to.
-	 */
-	public VRGuiManager(VREnvironment environment){
-		this.environment = environment;
-	}
-
-	public boolean isWantsReposition() {
-		return wantsReposition;
-	}
-
-	public void setWantsReposition(boolean wantsReposition) {
-		this.wantsReposition = wantsReposition;
-	}
-	
-	/**
-	 * 
-	 * Makes auto GUI positioning happen not immediately, but like an
-	 * elastic connected to the headset. Setting to 0 disables (default)
-	 * Higher settings make it track the headset quicker.
-	 * 
-	 * @param elastic amount of elasticity
-	 */
-	public void setPositioningElasticity(float elastic) {
-		guiPositioningElastic = elastic;
-	}
-
-	public float getPositioningElasticity() {
-		return guiPositioningElastic;
-	}
-
-	/**
-	 * Get the GUI {@link VRGUIPositioningMode positioning mode}.
-	 * @return the GUI {@link VRGUIPositioningMode positioning mode}.
-	 * @see #setPositioningMode(VRGUIPositioningMode)
-	 */
-	public VRGUIPositioningMode getPositioningMode() {
-		return posMode;
-	}
-
-	/**
-	 * Set the GUI {@link VRGUIPositioningMode positioning mode}.
-	 * @param mode the GUI {@link VRGUIPositioningMode positioning mode}.
-	 * @see #getPositioningMode()
-	 */
-	public void setPositioningMode(VRGUIPositioningMode mode) {
-		posMode = mode;
-	}
-
-	/**
-	 * Get the GUI canvas size. This method return the size in pixels of the GUI available area within the VR view.
-	 * @return the GUI canvas size. This method return the size in pixels of the GUI available area within the VR view.
-	 */
-	public Vector2f getCanvasSize() {
-
-		if (environment != null){
-
-			if (environment.getApplication() != null){
-				if( screenSize == null ) {
-					if( environment.isInVR() && environment.getVRHardware() != null ) {
-						screenSize = new Vector2f();
-						environment.getVRHardware().getRenderSize(screenSize);
-						screenSize.multLocal(environment.getVRViewManager().getResolutionMuliplier());
-					} else {
-						AppSettings as = environment.getApplication().getContext().getSettings();
-						screenSize = new Vector2f(as.getWidth(), as.getHeight());
-					}
-				}
-				return screenSize;
-			} else {
-				throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		}
-
-	}   
-
-	/**
-	 * Get the ratio between the {@link #getCanvasSize() GUI canvas size} and the application main windows (if available) or the screen size.
-	 * @return the ratio between the {@link #getCanvasSize() GUI canvas size} and the application main windows (if available).
-	 * @see #getCanvasSize()
-	 */
-	public Vector2f getCanvasToWindowRatio() {
-
-		if (environment != null){
-
-			if (environment.getApplication() != null){
-				if( ratio == null ) {
-					ratio = new Vector2f();
-					Vector2f canvas = getCanvasSize();
-					int width = Integer.min(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth(),
-							environment.getApplication().getContext().getSettings().getWidth());
-					int height = Integer.min(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight(),
-							environment.getApplication().getContext().getSettings().getHeight());
-					ratio.x = Float.max(1f, canvas.x / width);
-					ratio.y = Float.max(1f, canvas.y / height);
-				}
-				return ratio;
-
-			} else {
-				throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		}
-	}          
-
-	/**
-	 * Inform this manager that it has to position the GUI.
-	 */
-	public void positionGui() {
-		wantsReposition = true;
-	}
-
-	/**
-	 * Position the GUI to the given location.
-	 * @param pos the position of the GUI.
-	 * @param dir the rotation of the GUI.
-	 * @param tpf the time per frame.
-	 */
-	private void positionTo(Vector3f pos, Quaternion dir, float tpf) {
-
-		if (environment != null){
-			Vector3f guiPos = guiQuadNode.getLocalTranslation();
-			guiPos.set(0f, 0f, guiDistance);
-			dir.mult(guiPos, guiPos);
-			guiPos.x += pos.x;
-			guiPos.y += pos.y + environment.getVRHeightAdjustment();
-			guiPos.z += pos.z;        
-			if( guiPositioningElastic > 0f && posMode != VRGUIPositioningMode.MANUAL ) {
-				// mix pos & dir with current pos & dir            
-				guiPos.interpolateLocal(EoldPos, guiPos, Float.min(1f, tpf * guiPositioningElastic));
-				EoldPos.set(guiPos);
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		}
-	}
-
-	/**
-	 * Update the GUI geometric state. This method should be called after GUI modification.
-	 */
-	public void updateGuiQuadGeometricState() {
-		guiQuadNode.updateGeometricState();
-	}
-
-	/**
-	 * Position the GUI without delay.
-	 * @param tpf the time per frame.
-	 */
-	public void positionGuiNow(float tpf) {
-
-		if (environment != null){
-			wantsReposition = false;
-			if( environment.isInVR() == false ){
-				return;
-			}
-
-			guiQuadNode.setLocalScale(guiDistance * guiScale * 4f, 4f * guiDistance * guiScale, 1f);
-
-			switch( posMode ) {
-			case MANUAL:
-			case AUTO_CAM_ALL_SKIP_PITCH:
-			case AUTO_CAM_ALL:
-				if( camLeft != null && camRight != null ) {
-					// get middle point
-					temppos.set(camLeft.getLocation()).interpolateLocal(camRight.getLocation(), 0.5f);
-					positionTo(temppos, camLeft.getRotation(), tpf);
-				}
-				rotateScreenTo(camLeft.getRotation(), tpf);
-
-				break;
-			case AUTO_OBSERVER_POS_CAM_ROTATION:
-				Object obs = environment.getObserver();
-				if( obs != null ) {
-					if( obs instanceof Camera ) {
-						positionTo(((Camera)obs).getLocation(), camLeft.getRotation(), tpf);
-					} else {
-						positionTo(((Spatial)obs).getWorldTranslation(), camLeft.getRotation(), tpf);                        
-					}
-				}
-				rotateScreenTo(camLeft.getRotation(), tpf);
-
-				break;
-			case AUTO_OBSERVER_ALL:
-			case AUTO_OBSERVER_ALL_CAMHEIGHT:
-				obs = environment.getObserver();
-				if( obs != null ) {
-					Quaternion q;
-					if( obs instanceof Camera ) {
-						q = ((Camera)obs).getRotation();                        
-						temppos.set(((Camera)obs).getLocation());
-					} else {
-						q = ((Spatial)obs).getWorldRotation();
-						temppos.set(((Spatial)obs).getWorldTranslation());
-					}
-					if( posMode == VRGUIPositioningMode.AUTO_OBSERVER_ALL_CAMHEIGHT ) {
-						temppos.y = camLeft.getLocation().y;
-					}
-					positionTo(temppos, q, tpf);
-					rotateScreenTo(q, tpf);
-
-				}                
-				break;  
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		} 
-	}
-
-	/**
-	 * Rotate the GUI to the given direction.
-	 * @param dir the direction to rotate to.
-	 * @param tpf the time per frame.
-	 */
-	private void rotateScreenTo(Quaternion dir, float tpf) {
-		dir.getRotationColumn(2, look).negateLocal();
-		dir.getRotationColumn(0, left).negateLocal();
-		orient.fromAxes(left, dir.getRotationColumn(1, up), look);        
-		Quaternion rot = tempq.fromRotationMatrix(orient);
-		if( posMode == VRGUIPositioningMode.AUTO_CAM_ALL_SKIP_PITCH ){
-			VRUtil.stripToYaw(rot);
-		}
-
-		if( guiPositioningElastic > 0f && posMode != VRGUIPositioningMode.MANUAL ) {
-			// mix pos & dir with current pos & dir            
-			EoldDir.nlerp(rot, tpf * guiPositioningElastic);
-			guiQuadNode.setLocalRotation(EoldDir);
-		} else {
-			guiQuadNode.setLocalRotation(rot);
-		}
-	}
-
-	/**
-	 * Get the GUI distance from the observer.
-	 * @return the GUI distance from the observer.
-	 * @see #setGuiDistance(float)
-	 */
-	public float getGuiDistance() {
-		return guiDistance;
-	}
-
-	/**
-	 * Set the GUI distance from the observer.
-	 * @param newGuiDistance the GUI distance from the observer.
-	 * @see #getGuiDistance()
-	 */
-	public void setGuiDistance(float newGuiDistance) {
-		guiDistance = newGuiDistance;                
-	}
-
-	/**
-	 * Get the GUI scale.
-	 * @return the GUI scale.
-	 * @see #setGuiScale(float)
-	 */
-	public float getGUIScale(){
-		return guiScale;
-	}
-
-	/**
-	 * Set the GUI scale.
-	 * @param scale the GUI scale.
-	 * @see #getGUIScale()
-	 */
-	public void setGuiScale(float scale) {
-		guiScale = scale;
-	}
-
-	/**
-	 * Adjust the GUI distance from the observer. 
-	 * This method increment / decrement the {@link #getGuiDistance() GUI distance} by the given value. 
-	 * @param adjustAmount the increment (if positive) / decrement (if negative) value of the GUI distance.
-	 */
-	public void adjustGuiDistance(float adjustAmount) {
-		guiDistance += adjustAmount;
-	}
-
-	/**
-	 * Set up the GUI.
-	 * @param leftcam the left eye camera.
-	 * @param rightcam the right eye camera.
-	 * @param left the left eye viewport.
-	 * @param right the right eye viewport.
-	 */
-	public void setupGui(Camera leftcam, Camera rightcam, ViewPort left, ViewPort right) {
-
-		if (environment != null){
-			if( environment.hasTraditionalGUIOverlay() ) {
-				camLeft = leftcam;
-				camRight = rightcam;            
-				Spatial guiScene = getGuiQuad(camLeft);
-				left.attachScene(guiScene);
-				if( right != null ) right.attachScene(guiScene);
-				setPositioningMode(posMode);
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		} 
-	}
-
-	/**
-	 * Get if the GUI has to use curved surface.
-	 * @return <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
-	 * @see #setCurvedSurface(boolean)
-	 */
-	public boolean isCurverSurface(){
-		return useCurvedSurface;
-	}
-
-	/**
-	 * Set if the GUI has to use curved surface.
-	 * @param set <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
-	 * @see #isCurverSurface()
-	 */
-	public void setCurvedSurface(boolean set) {
-		useCurvedSurface = set;
-	}
-
-	/**
-	 * Get if the GUI has to be displayed even if it is behind objects.
-	 * @return <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
-	 * @see #setGuiOverdraw(boolean)
-	 */
-	public boolean isGuiOverdraw(){
-		return overdraw;
-	}
-
-	/**
-	 * Set if the GUI has to be displayed even if it is behind objects.
-	 * @param set <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
-	 * @see #isGuiOverdraw()
-	 */
-	public void setGuiOverdraw(boolean set) {
-		overdraw = set;
-	}
-
-	/**
-	 * Create a GUI quad for the given camera.
-	 * @param sourceCam the camera
-	 * @return a GUI quad for the given camera.
-	 */
-	private Spatial getGuiQuad(Camera sourceCam){
-
-		if (environment != null){
-
-			if (environment.getApplication() != null){
-				if( guiQuadNode == null ) {
-					Vector2f guiCanvasSize = getCanvasSize();
-					Camera offCamera = sourceCam.clone();
-					offCamera.setParallelProjection(true);
-					offCamera.setLocation(Vector3f.ZERO);
-					offCamera.lookAt(Vector3f.UNIT_Z, Vector3f.UNIT_Y);
-
-					offView = environment.getApplication().getRenderManager().createPreView("GUI View", offCamera);
-					offView.setClearFlags(true, true, true);            
-					offView.setBackgroundColor(ColorRGBA.BlackNoAlpha);
-
-					// create offscreen framebuffer
-					FrameBuffer offBuffer = new FrameBuffer((int)guiCanvasSize.x, (int)guiCanvasSize.y, 1);
-
-					//setup framebuffer's texture
-					guiTexture = new Texture2D((int)guiCanvasSize.x, (int)guiCanvasSize.y, Format.RGBA8);
-					guiTexture.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
-					guiTexture.setMagFilter(Texture.MagFilter.Bilinear);
-
-					//setup framebuffer to use texture
-					offBuffer.setDepthBuffer(Format.Depth);
-					offBuffer.setColorTexture(guiTexture);
-
-					//set viewport to render to offscreen framebuffer
-					offView.setOutputFrameBuffer(offBuffer);
-
-					// setup framebuffer's scene
-					Iterator<Spatial> spatialIter = environment.getApplication().getGuiViewPort().getScenes().iterator();
-					while(spatialIter.hasNext()){
-						offView.attachScene(spatialIter.next());
-					}
-
-
-					if( useCurvedSurface ) {
-						guiQuad = (Geometry)environment.getApplication().getAssetManager().loadModel("Common/Util/gui_mesh.j3o");
-					} else {
-						guiQuad = new Geometry("guiQuad", new CenterQuad(1f, 1f));
-					}
-
-					Material mat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/GuiOverlay.j3md");            
-					mat.getAdditionalRenderState().setDepthTest(!overdraw);
-					mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
-					mat.getAdditionalRenderState().setDepthWrite(false);
-					mat.setTexture("ColorMap", guiTexture);
-					guiQuad.setQueueBucket(Bucket.Translucent);
-					guiQuad.setMaterial(mat);
-
-					guiQuadNode = new Node("gui-quad-node");
-					guiQuadNode.setQueueBucket(Bucket.Translucent);
-					guiQuadNode.attachChild(guiQuad);
-				}
-				return guiQuadNode;
-			} else {
-				throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");	
-			}
-		} else {
-			throw new IllegalStateException("VR GUI manager is not attached to any environment.");
-		}
-
-
-
-	}
+    private Camera camLeft, camRight;
+    private float guiDistance = 1.5f;
+    private float guiScale = 1f;
+    private float guiPositioningElastic;
+
+    private VRGUIPositioningMode posMode = VRGUIPositioningMode.AUTO_CAM_ALL;
+
+    private final Matrix3f orient = new Matrix3f();
+    private Vector2f screenSize;
+    protected boolean wantsReposition;
+
+    private Vector2f ratio;
+
+    private final Vector3f EoldPos = new Vector3f();
+
+    private final Quaternion EoldDir = new Quaternion();
+
+    private final Vector3f look    = new Vector3f();
+    private final Vector3f left    = new Vector3f();
+    private final Vector3f temppos = new Vector3f();
+    private final Vector3f up      = new Vector3f();
+
+    private boolean useCurvedSurface = false;
+    private boolean overdraw = false;
+    private Geometry guiQuad;
+    private Node guiQuadNode;
+    private ViewPort offView;
+    private Texture2D guiTexture;
+
+    private final Quaternion tempq = new Quaternion();
+
+    private VREnvironment environment = null;
+
+    /**
+     * Create a new GUI manager attached to the given app state.
+     * @param environment the VR environment to which this manager is attached to.
+     */
+    public VRGuiManager(VREnvironment environment){
+        this.environment = environment;
+    }
+
+    public boolean isWantsReposition() {
+        return wantsReposition;
+    }
+
+    public void setWantsReposition(boolean wantsReposition) {
+        this.wantsReposition = wantsReposition;
+    }
+
+    /**
+     *
+     * Makes auto GUI positioning happen not immediately, but like an
+     * elastic connected to the headset. Setting to 0 disables (default)
+     * Higher settings make it track the headset quicker.
+     *
+     * @param elastic amount of elasticity
+     */
+    public void setPositioningElasticity(float elastic) {
+        guiPositioningElastic = elastic;
+    }
+
+    public float getPositioningElasticity() {
+        return guiPositioningElastic;
+    }
+
+    /**
+     * Get the GUI {@link VRGUIPositioningMode positioning mode}.
+     * @return the GUI {@link VRGUIPositioningMode positioning mode}.
+     * @see #setPositioningMode(VRGUIPositioningMode)
+     */
+    public VRGUIPositioningMode getPositioningMode() {
+        return posMode;
+    }
+
+    /**
+     * Set the GUI {@link VRGUIPositioningMode positioning mode}.
+     * @param mode the GUI {@link VRGUIPositioningMode positioning mode}.
+     * @see #getPositioningMode()
+     */
+    public void setPositioningMode(VRGUIPositioningMode mode) {
+        posMode = mode;
+    }
+
+    /**
+     * Get the GUI canvas size. This method return the size in pixels of the GUI available area within the VR view.
+     * @return the GUI canvas size. This method return the size in pixels of the GUI available area within the VR view.
+     */
+    public Vector2f getCanvasSize() {
+        if (environment != null){
+
+            if (environment.getApplication() != null){
+                if( screenSize == null ) {
+                    if( environment.isInVR() && environment.getVRHardware() != null ) {
+                        screenSize = new Vector2f();
+                        environment.getVRHardware().getRenderSize(screenSize);
+                        screenSize.multLocal(environment.getVRViewManager().getResolutionMuliplier());
+                    } else {
+                        AppSettings as = environment.getApplication().getContext().getSettings();
+                        screenSize = new Vector2f(as.getWidth(), as.getHeight());
+                    }
+                }
+                return screenSize;
+            } else {
+                throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
+
+    /**
+     * Get the ratio between the {@link #getCanvasSize() GUI canvas size} and the application main windows (if available) or the screen size.
+     * @return the ratio between the {@link #getCanvasSize() GUI canvas size} and the application main windows (if available).
+     * @see #getCanvasSize()
+     */
+    public Vector2f getCanvasToWindowRatio() {
+        if (environment != null){
+
+            if (environment.getApplication() != null){
+                if( ratio == null ) {
+                    ratio = new Vector2f();
+                    Vector2f canvas = getCanvasSize();
+                    int width = Integer.min(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth(),
+                            environment.getApplication().getContext().getSettings().getWidth());
+                    int height = Integer.min(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight(),
+                            environment.getApplication().getContext().getSettings().getHeight());
+                    ratio.x = Float.max(1f, canvas.x / width);
+                    ratio.y = Float.max(1f, canvas.y / height);
+                }
+                return ratio;
+
+            } else {
+                throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
+
+    /**
+     * Inform this manager that it has to position the GUI.
+     */
+    public void positionGui() {
+        wantsReposition = true;
+    }
+
+    /**
+     * Position the GUI to the given location.
+     * @param pos the position of the GUI.
+     * @param dir the rotation of the GUI.
+     * @param tpf the time per frame.
+     */
+    private void positionTo(Vector3f pos, Quaternion dir, float tpf) {
+        if (environment != null){
+            Vector3f guiPos = guiQuadNode.getLocalTranslation();
+            guiPos.set(0f, 0f, guiDistance);
+            dir.mult(guiPos, guiPos);
+            guiPos.x += pos.x;
+            guiPos.y += pos.y + environment.getVRHeightAdjustment();
+            guiPos.z += pos.z;
+            if( guiPositioningElastic > 0f && posMode != VRGUIPositioningMode.MANUAL ) {
+                // mix pos & dir with current pos & dir
+                guiPos.interpolateLocal(EoldPos, guiPos, Float.min(1f, tpf * guiPositioningElastic));
+                EoldPos.set(guiPos);
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
+
+    /**
+     * Update the GUI geometric state. This method should be called after GUI modification.
+     */
+    public void updateGuiQuadGeometricState() {
+        guiQuadNode.updateGeometricState();
+    }
+
+    /**
+     * Position the GUI without delay.
+     * @param tpf the time per frame.
+     */
+    public void positionGuiNow(float tpf) {
+        if (environment != null){
+            wantsReposition = false;
+            if( environment.isInVR() == false ){
+                return;
+            }
+
+            guiQuadNode.setLocalScale(guiDistance * guiScale * 4f, 4f * guiDistance * guiScale, 1f);
+
+            switch( posMode ) {
+            case MANUAL:
+            case AUTO_CAM_ALL_SKIP_PITCH:
+            case AUTO_CAM_ALL:
+                if( camLeft != null && camRight != null ) {
+                    // get middle point
+                    temppos.set(camLeft.getLocation()).interpolateLocal(camRight.getLocation(), 0.5f);
+                    positionTo(temppos, camLeft.getRotation(), tpf);
+                }
+                rotateScreenTo(camLeft.getRotation(), tpf);
+
+                break;
+            case AUTO_OBSERVER_POS_CAM_ROTATION:
+                Object obs = environment.getObserver();
+                if( obs != null ) {
+                    if( obs instanceof Camera ) {
+                        positionTo(((Camera)obs).getLocation(), camLeft.getRotation(), tpf);
+                    } else {
+                        positionTo(((Spatial)obs).getWorldTranslation(), camLeft.getRotation(), tpf);
+                    }
+                }
+                rotateScreenTo(camLeft.getRotation(), tpf);
+
+                break;
+            case AUTO_OBSERVER_ALL:
+            case AUTO_OBSERVER_ALL_CAMHEIGHT:
+                obs = environment.getObserver();
+                if( obs != null ) {
+                    Quaternion q;
+                    if( obs instanceof Camera ) {
+                        q = ((Camera)obs).getRotation();
+                        temppos.set(((Camera)obs).getLocation());
+                    } else {
+                        q = ((Spatial)obs).getWorldRotation();
+                        temppos.set(((Spatial)obs).getWorldTranslation());
+                    }
+                    if( posMode == VRGUIPositioningMode.AUTO_OBSERVER_ALL_CAMHEIGHT ) {
+                        temppos.y = camLeft.getLocation().y;
+                    }
+                    positionTo(temppos, q, tpf);
+                    rotateScreenTo(q, tpf);
+
+                }
+                break;
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
+
+    /**
+     * Rotate the GUI to the given direction.
+     * @param dir the direction to rotate to.
+     * @param tpf the time per frame.
+     */
+    private void rotateScreenTo(Quaternion dir, float tpf) {
+        dir.getRotationColumn(2, look).negateLocal();
+        dir.getRotationColumn(0, left).negateLocal();
+        orient.fromAxes(left, dir.getRotationColumn(1, up), look);
+        Quaternion rot = tempq.fromRotationMatrix(orient);
+        if( posMode == VRGUIPositioningMode.AUTO_CAM_ALL_SKIP_PITCH ){
+            VRUtil.stripToYaw(rot);
+        }
+
+        if( guiPositioningElastic > 0f && posMode != VRGUIPositioningMode.MANUAL ) {
+            // mix pos & dir with current pos & dir
+            EoldDir.nlerp(rot, tpf * guiPositioningElastic);
+            guiQuadNode.setLocalRotation(EoldDir);
+        } else {
+            guiQuadNode.setLocalRotation(rot);
+        }
+    }
+
+    /**
+     * Get the GUI distance from the observer.
+     * @return the GUI distance from the observer.
+     * @see #setGuiDistance(float)
+     */
+    public float getGuiDistance() {
+        return guiDistance;
+    }
+
+    /**
+     * Set the GUI distance from the observer.
+     * @param newGuiDistance the GUI distance from the observer.
+     * @see #getGuiDistance()
+     */
+    public void setGuiDistance(float newGuiDistance) {
+        guiDistance = newGuiDistance;
+    }
+
+    /**
+     * Get the GUI scale.
+     * @return the GUI scale.
+     * @see #setGuiScale(float)
+     */
+    public float getGUIScale(){
+        return guiScale;
+    }
+
+    /**
+     * Set the GUI scale.
+     * @param scale the GUI scale.
+     * @see #getGUIScale()
+     */
+    public void setGuiScale(float scale) {
+        guiScale = scale;
+    }
+
+    /**
+     * Adjust the GUI distance from the observer.
+     * This method increment / decrement the {@link #getGuiDistance() GUI distance} by the given value.
+     * @param adjustAmount the increment (if positive) / decrement (if negative) value of the GUI distance.
+     */
+    public void adjustGuiDistance(float adjustAmount) {
+        guiDistance += adjustAmount;
+    }
+
+    /**
+     * Set up the GUI.
+     * @param leftcam the left eye camera.
+     * @param rightcam the right eye camera.
+     * @param left the left eye viewport.
+     * @param right the right eye viewport.
+     */
+    public void setupGui(Camera leftcam, Camera rightcam, ViewPort left, ViewPort right) {
+
+        if (environment != null){
+            if( environment.hasTraditionalGUIOverlay() ) {
+                camLeft = leftcam;
+                camRight = rightcam;
+                Spatial guiScene = getGuiQuad(camLeft);
+                left.attachScene(guiScene);
+                if( right != null ) right.attachScene(guiScene);
+                setPositioningMode(posMode);
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
+
+    /**
+     * Get if the GUI has to use curved surface.
+     * @return <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
+     * @see #setCurvedSurface(boolean)
+     */
+    public boolean isCurverSurface(){
+        return useCurvedSurface;
+    }
+
+    /**
+     * Set if the GUI has to use curved surface.
+     * @param set <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
+     * @see #isCurverSurface()
+     */
+    public void setCurvedSurface(boolean set) {
+        useCurvedSurface = set;
+    }
+
+    /**
+     * Get if the GUI has to be displayed even if it is behind objects.
+     * @return <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
+     * @see #setGuiOverdraw(boolean)
+     */
+    public boolean isGuiOverdraw(){
+        return overdraw;
+    }
+
+    /**
+     * Set if the GUI has to be displayed even if it is behind objects.
+     * @param set <code>true</code> if the GUI has to use curved surface and <code>false</code> otherwise.
+     * @see #isGuiOverdraw()
+     */
+    public void setGuiOverdraw(boolean set) {
+        overdraw = set;
+    }
+
+    /**
+     * Create a GUI quad for the given camera.
+     * @param sourceCam the camera
+     * @return a GUI quad for the given camera.
+     */
+    private Spatial getGuiQuad(Camera sourceCam){
+        if (environment != null){
+
+            if (environment.getApplication() != null){
+                if( guiQuadNode == null ) {
+                    Vector2f guiCanvasSize = getCanvasSize();
+                    Camera offCamera = sourceCam.clone();
+                    offCamera.setParallelProjection(true);
+                    offCamera.setLocation(Vector3f.ZERO);
+                    offCamera.lookAt(Vector3f.UNIT_Z, Vector3f.UNIT_Y);
+
+                    offView = environment.getApplication().getRenderManager().createPreView("GUI View", offCamera);
+                    offView.setClearFlags(true, true, true);
+                    offView.setBackgroundColor(ColorRGBA.BlackNoAlpha);
+
+                    // create offscreen framebuffer
+                    FrameBuffer offBuffer = new FrameBuffer((int)guiCanvasSize.x, (int)guiCanvasSize.y, 1);
+
+                    //setup framebuffer's texture
+                    guiTexture = new Texture2D((int)guiCanvasSize.x, (int)guiCanvasSize.y, Format.RGBA8);
+                    guiTexture.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
+                    guiTexture.setMagFilter(Texture.MagFilter.Bilinear);
+
+                    //setup framebuffer to use texture
+                    offBuffer.setDepthBuffer(Format.Depth);
+                    offBuffer.setColorTexture(guiTexture);
+
+                    //set viewport to render to offscreen framebuffer
+                    offView.setOutputFrameBuffer(offBuffer);
+
+                    // setup framebuffer's scene
+                    Iterator<Spatial> spatialIter = environment.getApplication().getGuiViewPort().getScenes().iterator();
+                    while(spatialIter.hasNext()){
+                        offView.attachScene(spatialIter.next());
+                    }
+
+                    if( useCurvedSurface ) {
+                        guiQuad = (Geometry)environment.getApplication().getAssetManager().loadModel("Common/Util/gui_mesh.j3o");
+                    } else {
+                        guiQuad = new Geometry("guiQuad", new CenterQuad(1f, 1f));
+                    }
+
+                    Material mat = new Material(environment.getApplication().getAssetManager(), "Common/MatDefs/VR/GuiOverlay.j3md");
+                    mat.getAdditionalRenderState().setDepthTest(!overdraw);
+                    mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
+                    mat.getAdditionalRenderState().setDepthWrite(false);
+                    mat.setTexture("ColorMap", guiTexture);
+                    guiQuad.setQueueBucket(Bucket.Translucent);
+                    guiQuad.setMaterial(mat);
+
+                    guiQuadNode = new Node("gui-quad-node");
+                    guiQuadNode.setQueueBucket(Bucket.Translucent);
+                    guiQuadNode.attachChild(guiQuad);
+                }
+                return guiQuadNode;
+            } else {
+                throw new IllegalStateException("VR GUI manager underlying environment is not attached to any application.");
+            }
+        } else {
+            throw new IllegalStateException("VR GUI manager is not attached to any environment.");
+        }
+    }
 }

Some files were not shown because too many files changed in this diff