Guest User

GamepadJoyInput.java

a guest
Sep 5th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 26.65 KB | None | 0 0
  1. /*
  2.  * Copyright (c) 2009-2012 jMonkeyEngine
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions are
  7.  * met:
  8.  *
  9.  * * Redistributions of source code must retain the above copyright
  10.  *   notice, this list of conditions and the following disclaimer.
  11.  *
  12.  * * Redistributions in binary form must reproduce the above copyright
  13.  *   notice, this list of conditions and the following disclaimer in the
  14.  *   documentation and/or other materials provided with the distribution.
  15.  *
  16.  * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
  17.  *   may be used to endorse or promote products derived from this software
  18.  *   without specific prior written permission.
  19.  *
  20.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23.  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  */
  32.  
  33. package com.jme3.input.android;
  34.  
  35. import android.app.Activity;
  36. import android.content.Context;
  37. import android.hardware.SensorManager;
  38. import android.os.Vibrator;
  39. import android.view.InputDevice;
  40. import android.view.KeyEvent;
  41. import android.view.MotionEvent;
  42. import android.view.Surface;
  43. import android.view.View;
  44. import com.jme3.input.AbstractJoystick;
  45. import com.jme3.input.DefaultJoystickAxis;
  46. import com.jme3.input.DefaultJoystickButton;
  47. import com.jme3.input.InputManager;
  48. import com.jme3.input.JoyInput;
  49. import com.jme3.input.Joystick;
  50. import com.jme3.input.JoystickAxis;
  51. import com.jme3.input.JoystickButton;
  52. import com.jme3.input.SensorJoystickAxis;
  53. import com.jme3.input.RawInputListener;
  54. import com.jme3.input.event.JoyAxisEvent;
  55. import com.jme3.input.event.JoyButtonEvent;
  56. import com.jme3.math.FastMath;
  57. import com.jme3.system.android.JmeAndroidSystem;
  58. import com.jme3.util.IntMap;
  59. import com.jme3.util.IntMap.Entry;
  60. import java.util.ArrayList;
  61. import java.util.HashMap;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.logging.Level;
  65. import java.util.logging.Logger;
  66. import net.java.games.input.Component;
  67.  
  68. /**
  69.  * GamepadJoyInput converts the Android Sensor system into Joystick events.
  70.  * A single joystick is configured and includes data for all configured sensors
  71.  * as seperate axes of the joystick.
  72.  *
  73.  * Each axis is named accounting to the static strings in SensorJoystickAxis.
  74.  * Refer to the strings defined in SensorJoystickAxis for a list of supported
  75.  * sensors and their axis data.  Each sensor type defined in SensorJoystickAxis
  76.  * will be attempted to be configured.  If the device does not support a particular
  77.  * sensor, the axis will return null if joystick.getAxis(String name) is called.
  78.  *
  79.  * The joystick.getXAxis and getYAxis methods of the joystick are configured to
  80.  * return the device orientation values in the device's X and Y directions.
  81.  *
  82.  * This joystick also supports the joystick.rumble(rumbleAmount) method.  In this
  83.  * case, when joystick.rumble(rumbleAmount) is called, the Android device will vibrate
  84.  * if the device has a built in vibrate motor.
  85.  *
  86.  * Because Andorid does not allow for the user to define the intensity of the
  87.  * vibration, the rumble amount (ie strength) is converted into vibration pulses
  88.  * The stronger the strength amount, the shorter the delay between pulses.  If
  89.  * amount is 1, then the vibration stays on the whole time.  If amount is 0.5,
  90.  * the vibration will a pulse of equal parts vibration and delay.
  91.  * To turn off vibration, set rumble amount to 0.
  92.  *
  93.  * MainActivity needs the following line to enable Joysticks on Android platforms
  94.  *    joystickEventsEnabled = true;
  95.  * This is done to allow for battery conservation when sensor data is not required
  96.  * by the application.
  97.  *
  98.  * To use the joystick rumble feature, the following line needs to be
  99.  * added to the Android Manifest File
  100.  *     <uses-permission android:name="android.permission.VIBRATE"/>
  101.  *
  102.  * @author iwgeric
  103.  */
  104. public class GamepadJoyInput implements JoyInput, View.OnGenericMotionListener, View.OnKeyListener {
  105.     private final static Logger logger = Logger.getLogger(GamepadJoyInput.class.getName());
  106.  
  107.     private Activity activity = null;
  108.     private InputManager inputManager = null;
  109.     private InputDevice inputDevice = null;
  110.     private Vibrator vibrator = null;
  111.     private boolean vibratorActive = false;
  112.     private long maxRumbleTime = 250;  // 250ms
  113.     private RawInputListener listener = null;
  114.     private IntMap<SensorData> sensors = new IntMap<SensorData>();
  115.     private Map<InputDevice, AndroidJoystick> joystickIndex = new HashMap<InputDevice, AndroidJoystick>();
  116.     private AndroidJoystick[] joysticks;
  117.     private int lastRotation = 0;
  118.     private boolean initialized = false;
  119.     private boolean loaded = false;
  120.     private View mView = null;
  121.  
  122.     private final ArrayList<JoyAxisEvent> eventQueue = new ArrayList<JoyAxisEvent>();
  123.     private final ArrayList<JoyButtonEvent> buttoneventQueue = new ArrayList<JoyButtonEvent>();
  124.    
  125.     public void setView(View view)
  126.     {
  127.         mView = view;
  128.         if (view != null)
  129.         {
  130.             view.setOnGenericMotionListener(this);
  131.             view.setOnKeyListener(this);
  132.         }
  133.     }
  134.    
  135.     public boolean onGenericMotion(View view, MotionEvent event)
  136.     {
  137.         boolean success = false;
  138.  
  139.         SensorData sensorData = sensors.get(InputDevice.SOURCE_CLASS_JOYSTICK);
  140.        
  141.         if (!initialized || !loaded)
  142.         {
  143.             return view.onGenericMotionEvent(event);
  144.         }
  145.        
  146.         // Check that the event came from a joystick since a generic motion event
  147.         // could be almost anything.
  148.         if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0
  149.                 && event.getAction() == MotionEvent.ACTION_MOVE) {
  150.             // Cache the most recently obtained device information.
  151.             // The device information may change over time but it can be
  152.             // somewhat expensive to query.
  153.             if (inputDevice == null || inputDevice.getId() != event.getDeviceId()) {
  154.                 inputDevice = event.getDevice();
  155.                 // It's possible for the device id to be invalid.
  156.                 // In that case, getDevice() will return null.
  157.                 if (inputDevice == null) {
  158.                     return false;
  159.                 }
  160.             }
  161.  
  162.             // Process all historical movement samples in the batch.
  163.             final int historySize = event.getHistorySize();
  164.             for (int i = 0; i < historySize; i++) {
  165.                 processJoystickInput(event, i, sensorData);
  166.             }
  167.  
  168.             // Process the current movement sample in the batch.
  169.             processJoystickInput(event, -1, sensorData);
  170.             return true;
  171.         }
  172.         return true;
  173.     }
  174.    
  175.     private void processJoystickInput(MotionEvent event, int historyPos, SensorData sensorData)
  176.     {
  177.  
  178.         // Get joystick position.
  179.         // Many game pads with two joysticks report the position of the second joystick
  180.         // using the Z and RZ axes so we also handle those.
  181.         // In a real game, we would allow the user to configure the axes manually.
  182.         float x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_X, historyPos);
  183.         if (x == 0) {
  184.             x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_HAT_X, historyPos);
  185.         }
  186.         if (x == 0) {
  187.             x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_Z, historyPos);
  188.         }
  189.  
  190.         float y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_Y, historyPos);
  191.         if (y == 0) {
  192.             y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_HAT_Y, historyPos);
  193.         }
  194.         if (y == 0) {
  195.             y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_RZ, historyPos);
  196.         }    
  197.  
  198.         if (sensorData != null && sensorData.enabled)
  199.         {
  200.  
  201.             for (int i=0; i<sensorData.lastValues.length; i++)
  202.             {
  203.                 sensorData.lastValues[i] = event.getAxisValue(i);
  204.             }
  205.  
  206.             if (sensorData != null && sensorData.axes.size() > 0)
  207.             {
  208.                 AndroidJoystickAxis axis;
  209.                 for (int i=0; i<event.getHistorySize(); i++)
  210.                 {
  211.                     axis = sensorData.axes.get(i);
  212.                     if (axis != null) {
  213.                         axis.setCurRawValue(event.getAxisValue(i));
  214.                         if (!sensorData.haveData) {
  215.                             sensorData.haveData = true;
  216.                         } else {
  217.                             synchronized (eventQueue){
  218.                                 if (axis.isChanged()) {
  219.                                     eventQueue.add(new JoyAxisEvent(axis, axis.getJoystickAxisValue()));
  220.                                 }
  221.                             }
  222.                         }
  223.                     }
  224.                 }
  225.             } else if (sensorData != null)
  226.             {
  227.                 if (!sensorData.haveData) {
  228.                     sensorData.haveData = true;
  229.                 }
  230.             }
  231.  
  232.        
  233.         }
  234.     }
  235.  
  236.     private static float getCenteredAxis(MotionEvent event, InputDevice device,
  237.             int axis, int historyPos) {
  238.         final InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource());
  239.         if (range != null) {
  240.             final float flat = range.getFlat();
  241.             final float value = historyPos < 0 ? event.getAxisValue(axis)
  242.                     : event.getHistoricalAxisValue(axis, historyPos);
  243.  
  244.             // Ignore axis values that are within the 'flat' region of the joystick axis center.
  245.             // A joystick at rest does not always report an absolute position of (0,0).
  246.             if (Math.abs(value) > flat) {
  247.                 return value;
  248.             }
  249.         }
  250.         return 0;
  251.     }
  252.  
  253.     public boolean onKey(View view, int i, KeyEvent ke)
  254.     {
  255.         int firstButton = 0;
  256.         SensorData sensorData = sensors.get(InputDevice.SOURCE_CLASS_JOYSTICK);
  257.        
  258.         AndroidJoystickButton button = sensorData.buttons.get(firstButton);
  259.        
  260.         synchronized (buttoneventQueue)
  261.         {
  262.             if(ke.getAction() == KeyEvent.ACTION_DOWN)
  263.             {
  264.                 button.setPressed(true);
  265.                 buttoneventQueue.add(new JoyButtonEvent(button, button.isPressed()));
  266.             }
  267.             else if(ke.getAction() == KeyEvent.ACTION_UP)
  268.             {
  269.                 button.setPressed(false);
  270.                 buttoneventQueue.add(new JoyButtonEvent(button, button.isPressed()));
  271.             }
  272.         }
  273.  
  274.         return true;
  275.     }
  276.    
  277.     /**
  278.      * Internal class to enclose data for each sensor.
  279.      */
  280.     private class SensorData {
  281.         int androidSensorType = -1;
  282.         int androidSensorSpeed = SensorManager.SENSOR_DELAY_GAME;
  283.         InputDevice inputDevice = null;
  284.         int sensorAccuracy = 0;
  285.         float[] lastValues;
  286.         final Object valuesLock = new Object();
  287.         ArrayList<AndroidJoystickAxis> axes = new ArrayList<AndroidJoystickAxis>();
  288.         ArrayList<AndroidJoystickButton> buttons = new ArrayList<AndroidJoystickButton>();
  289.         boolean enabled = false;
  290.         boolean haveData = false;
  291.  
  292.         public SensorData(int androidSensorType, InputDevice inputDevice) {
  293.             this.androidSensorType = androidSensorType;
  294.             this.inputDevice = inputDevice;
  295.         }
  296.  
  297.     }
  298.  
  299.     private void initSensorManager() {
  300.         this.activity = JmeAndroidSystem.getActivity();
  301.         // Get instance of Vibrator from current Context
  302.         vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
  303.         if (vibrator == null) {
  304.             logger.log(Level.FINE, "Vibrator Service not found.");
  305.         }
  306.     }
  307.  
  308.     /**
  309.      * Pauses the sensors to save battery life if the sensors are not needed.
  310.      * Used to pause sensors when the activity pauses
  311.      */
  312.     public void pauseSensors()
  313.     {
  314.         if (vibrator != null && vibratorActive) {
  315.             vibrator.cancel();
  316.         }
  317.     }
  318.  
  319.     /**
  320.      * Resumes the sensors.
  321.      * Used to resume sensors when the activity comes to the top of the stack
  322.      */
  323.     public void resumeSensors()
  324.     {
  325.  
  326.     }
  327.  
  328.     /*
  329.      * Allows the orientation data to be rotated based on the current device
  330.      * rotation.  This keeps the data aligned with the game when the user
  331.      * rotates the device during game play.
  332.      *
  333.      * Android remapCoordinateSystem from the Android docs
  334.      * remapCoordinateSystem(float[] inR, int X, int Y, float[] outR)
  335.      *
  336.      * @param   inR   the rotation matrix to be transformed. Usually it is the matrix
  337.      *          returned by getRotationMatrix(float[], float[], float[], float[]).
  338.      *
  339.      * @param   outR  the transformed rotation matrix. inR and outR can be the same
  340.      *          array, but it is not recommended for performance reason.
  341.      *
  342.      * X     defines on which world (Earth) axis and direction the X axis of the device is mapped.
  343.      * Y     defines on which world (Earth) axis and direction the Y axis of the device is mapped.
  344.      *
  345.      * @return True if successful
  346.      */
  347.     private boolean remapCoordinates(float[] inR, float[] outR) {
  348.         int xDir = SensorManager.AXIS_X;
  349.         int yDir = SensorManager.AXIS_Y;
  350.         int curRotation = getScreenRotation();
  351.         if (lastRotation != curRotation) {
  352.             logger.log(Level.FINE, "Device Rotation changed to: {0}", curRotation);
  353.         }
  354.         lastRotation = curRotation;
  355.  
  356. //        logger.log(Level.FINE, "Screen Rotation: {0}", getScreenRotation());
  357.         switch (getScreenRotation()) {
  358.             // device natural position
  359.             case Surface.ROTATION_0:
  360.                 xDir = SensorManager.AXIS_X;
  361.                 yDir = SensorManager.AXIS_Y;
  362.                 break;
  363.             // device rotated 90 deg counterclockwise
  364.             case Surface.ROTATION_90:
  365.                 xDir = SensorManager.AXIS_Y;
  366.                 yDir = SensorManager.AXIS_MINUS_X;
  367.                 break;
  368.             // device rotated 180 deg counterclockwise
  369.             case Surface.ROTATION_180:
  370.                 xDir = SensorManager.AXIS_MINUS_X;
  371.                 yDir = SensorManager.AXIS_MINUS_Y;
  372.                 break;
  373.             // device rotated 270 deg counterclockwise
  374.             case Surface.ROTATION_270:
  375.                 xDir = SensorManager.AXIS_MINUS_Y;
  376.                 yDir = SensorManager.AXIS_X;
  377.                 break;
  378.             default:
  379.                 break;
  380.         }
  381.         return SensorManager.remapCoordinateSystem(inR, xDir, yDir, outR);
  382.     }
  383.  
  384.     /**
  385.      * Returns the current device rotation.
  386.      * Surface.ROTATION_0 = device in natural default rotation
  387.      * Surface.ROTATION_90 = device in rotated 90deg counterclockwise
  388.      * Surface.ROTATION_180 = device in rotated 180deg counterclockwise
  389.      * Surface.ROTATION_270 = device in rotated 270deg counterclockwise
  390.      *
  391.      * When the Manifest locks the orientation, this value will not change during
  392.      * gametime, but if the orientation of the screen is based off the sensor,
  393.      * this value will change as the device is rotated.
  394.      * @return Current device rotation amount
  395.      */
  396.     private int getScreenRotation() {
  397.         return activity.getWindowManager().getDefaultDisplay().getRotation();
  398.     }
  399.  
  400.     // Start of JoyInput methods
  401.  
  402.     public void setJoyRumble(int joyId, float amount) {
  403.         // convert amount to pulses since Android doesn't allow intensity
  404.         if (vibrator != null) {
  405.             final long rumbleOnDur = (long)(amount * maxRumbleTime); // ms to pulse vibration on
  406.             final long rumbleOffDur = maxRumbleTime - rumbleOnDur; // ms to delay between pulses
  407.             final long[] rumblePattern = {
  408.                 0, // start immediately
  409.                 rumbleOnDur, // time to leave vibration on
  410.                 rumbleOffDur // time to delay between vibrations
  411.             };
  412.             final int rumbleRepeatFrom = 0; // index into rumble pattern to repeat from
  413.  
  414.             logger.log(Level.FINE, "Rumble amount: {0}, rumbleOnDur: {1}, rumbleOffDur: {2}",
  415.                     new Object[]{amount, rumbleOnDur, rumbleOffDur});
  416.  
  417.             if (rumbleOnDur > 0) {
  418.                 vibrator.vibrate(rumblePattern, rumbleRepeatFrom);
  419.                 vibratorActive = true;
  420.             } else {
  421.                 vibrator.cancel();
  422.                 vibratorActive = false;
  423.             }
  424.         }
  425.  
  426.     }
  427.  
  428.     public Joystick[] loadJoysticks(InputManager inputManager) {
  429.         this.inputManager = inputManager;
  430.  
  431.         initSensorManager();
  432.         setView(mView);
  433.        
  434.         int myButtonNumber = 96;
  435.  
  436.         SensorData sensorData;
  437.         List<Joystick> list = new ArrayList<Joystick>();
  438.         AndroidJoystick joystick;
  439.         AndroidJoystickAxis axis;
  440.         AndroidJoystickButton button;
  441.  
  442.         joystick = new AndroidJoystick(inputManager,
  443.                                     this,
  444.                                     list.size(),
  445.                                     "AndroidSensorsJoystick");
  446.         list.add(joystick);
  447.  
  448.         // manually create orientation sensor data since orientation is not a physical sensor
  449.         sensorData = new SensorData(InputDevice.SOURCE_CLASS_JOYSTICK, null);
  450.  
  451.         sensorData.androidSensorType = InputDevice.SOURCE_CLASS_JOYSTICK;
  452.         //sensorData.sensor = sensorManager.getDefaultSensor(sensorType);
  453.         sensorData.enabled = true;
  454.  
  455.         if (sensorData != null) {
  456.             sensorData.lastValues = new float[2];
  457.             sensors.put(InputDevice.SOURCE_CLASS_JOYSTICK, sensorData);      
  458.            
  459.             axis = joystick.addAxis(SensorJoystickAxis.ORIENTATION_X, SensorJoystickAxis.ORIENTATION_X, joystick.getAxisCount(), FastMath.HALF_PI);
  460.             joystick.setYAxis(axis); // joystick y axis = rotation around device x axis
  461.             sensorData.axes.add(axis);
  462.            
  463.             button = joystick.addButton(JoystickButton.BUTTON_0, JoystickButton.BUTTON_0, myButtonNumber);
  464.             joystick.setButton(button);
  465.             sensorData.buttons.add(button);
  466.            
  467.             axis = joystick.addAxis(SensorJoystickAxis.ORIENTATION_Y, SensorJoystickAxis.ORIENTATION_Y, joystick.getAxisCount(), FastMath.HALF_PI);
  468.             joystick.setXAxis(axis); // joystick x axis = rotation around device y axis
  469.             sensorData.axes.add(axis);
  470.         }
  471.  
  472.         joysticks = list.toArray( new AndroidJoystick[list.size()] );
  473.         loaded = true;
  474.         return joysticks;
  475.     }
  476.  
  477.     public void initialize() {
  478.         initialized = true;
  479.         loaded = false;
  480.     }
  481.  
  482.     public void update() {
  483.         if (!loaded) {
  484.             return;
  485.         }
  486.         synchronized (eventQueue){
  487.             // flush events to listener
  488.             if (listener != null && eventQueue.size() > 0) {
  489.                 for (int i = 0; i < eventQueue.size(); i++){
  490.                     listener.onJoyAxisEvent(eventQueue.get(i));
  491.                 }
  492.                 eventQueue.clear();
  493.             }
  494.         }
  495.        
  496.         synchronized (buttoneventQueue)
  497.         {
  498.             // flush events to listener
  499.             if (listener != null && buttoneventQueue.size() > 0) {
  500.                 for (int i = 0; i < buttoneventQueue.size(); i++){
  501.                     listener.onJoyButtonEvent(buttoneventQueue.get(i));
  502.                 }
  503.                 buttoneventQueue.clear();
  504.             }
  505.         }
  506.     }
  507.  
  508.     public void destroy() {
  509.         logger.log(Level.FINE, "Doing Destroy.");
  510.         pauseSensors();
  511.         sensors.clear();
  512.         eventQueue.clear();
  513.         buttoneventQueue.clear();
  514.         initialized = false;
  515.         loaded = false;
  516.         joysticks = null;
  517.         vibrator = null;
  518.         activity = null;
  519.     }
  520.  
  521.     public boolean isInitialized() {
  522.         return initialized;
  523.     }
  524.  
  525.     public void setInputListener(RawInputListener listener) {
  526.         this.listener = listener;
  527.     }
  528.  
  529.     public long getInputTimeNanos() {
  530.         return System.nanoTime();
  531.     }
  532.  
  533.     // End of JoyInput methods
  534.  
  535.     protected class AndroidJoystick extends AbstractJoystick {
  536.         private JoystickAxis nullAxis;
  537.         private JoystickAxis xAxis;
  538.         private JoystickAxis yAxis;
  539.         private JoystickAxis povX;
  540.         private JoystickAxis povY;
  541.         private JoystickButton button;
  542.        
  543.         private Map<Integer, JoystickButton> buttonIndex = new HashMap<Integer, JoystickButton>();
  544.  
  545.         public AndroidJoystick( InputManager inputManager, JoyInput joyInput,
  546.                                 int joyId, String name){
  547.  
  548.             super( inputManager, joyInput, joyId, name );
  549.  
  550.             this.nullAxis = new DefaultJoystickAxis( getInputManager(), this, -1,
  551.                                                      "Null", "null", false, false, 0 );
  552.             this.xAxis = nullAxis;
  553.             this.yAxis = nullAxis;
  554.             this.povX = nullAxis;
  555.             this.povY = nullAxis;
  556.  
  557.         }
  558.  
  559.         protected AndroidJoystickAxis addAxis(String axisName, String logicalName, int axisNum, float maxRawValue) {
  560.             AndroidJoystickAxis axis;
  561.  
  562.             axis = new AndroidJoystickAxis(
  563.                     inputManager,               // InputManager (InputManager)
  564.                     this,                       // parent Joystick (Joystick)
  565.                     axisNum,                    // Axis Index (int)
  566.                     axisName,                   // Axis Name (String)
  567.                     logicalName,                // Logical ID (String)
  568.                     true,                       // isAnalog (boolean)
  569.                     false,                      // isRelative (boolean)
  570.                     0.01f,                      // Axis Deadzone (float)
  571.                     maxRawValue);               // Axis Max Raw Value (float)
  572.  
  573.             super.addAxis(axis);
  574.  
  575.             return axis;
  576.         }
  577.        
  578.         protected AndroidJoystickButton addButton(String buttonName, String logicalName, int buttonNum) {
  579.             AndroidJoystickButton mybutton;
  580.  
  581.             mybutton = new AndroidJoystickButton(
  582.                     inputManager,               // InputManager (InputManager)
  583.                     this,                       // parent Joystick (Joystick)
  584.                     buttonNum,                    // Axis Index (int)
  585.                     buttonName,                   // Axis Name (String)
  586.                     logicalName);                // Logical ID (String)
  587.  
  588.             super.addButton(mybutton);
  589.  
  590.             return mybutton;
  591.         }
  592.        
  593.         protected void setButton(JoystickButton bttn)
  594.         {
  595.             button = bttn;            
  596.         }        
  597.  
  598.         protected void setXAxis(JoystickAxis axis) {
  599.             xAxis = axis;
  600.         }
  601.         protected void setYAxis(JoystickAxis axis) {
  602.             yAxis = axis;
  603.         }
  604.  
  605.         @Override
  606.         public JoystickAxis getXAxis() {
  607.             return xAxis;
  608.         }
  609.  
  610.         @Override
  611.         public JoystickAxis getYAxis() {
  612.             return yAxis;
  613.         }
  614.  
  615.         @Override
  616.         public JoystickAxis getPovXAxis() {
  617.             return povX;
  618.         }
  619.  
  620.         @Override
  621.         public JoystickAxis getPovYAxis() {
  622.             return povY;
  623.         }
  624.  
  625.     }
  626.  
  627.     public class AndroidJoystickAxis extends DefaultJoystickAxis implements SensorJoystickAxis {
  628.         float zeroRawValue = 0f;
  629.         float curRawValue = 0f;
  630.         float lastRawValue = 0f;
  631.         boolean hasChanged = false;
  632.         float maxRawValue = FastMath.HALF_PI;
  633.         boolean enabled = true;
  634.  
  635.         public AndroidJoystickAxis(InputManager inputManager, Joystick parent,
  636.                            int axisIndex, String name, String logicalId,
  637.                            boolean isAnalog, boolean isRelative, float deadZone,
  638.                            float maxRawValue) {
  639.             super(inputManager, parent, axisIndex, name, logicalId, isAnalog, isRelative, deadZone);
  640.  
  641.             this.maxRawValue = maxRawValue;
  642.         }
  643.  
  644.         public float getMaxRawValue() {
  645.             return maxRawValue;
  646.         }
  647.  
  648.         public void setMaxRawValue(float maxRawValue) {
  649.             this.maxRawValue = maxRawValue;
  650.         }
  651.  
  652.         protected float getLastRawValue() {
  653.             return lastRawValue;
  654.         }
  655.         protected void setCurRawValue(float rawValue) {
  656.             this.curRawValue = rawValue;
  657.             if (Math.abs(curRawValue - lastRawValue) > getDeadZone()) {
  658.                 hasChanged = true;
  659.                 lastRawValue = curRawValue;
  660.             } else {
  661.                 hasChanged = false;
  662.             }
  663.         }
  664.  
  665.         protected float getJoystickAxisValue() {
  666.             return (lastRawValue-zeroRawValue) / maxRawValue;
  667.         }
  668.  
  669.         protected boolean isChanged() {
  670.             return hasChanged;
  671.         }
  672.  
  673.         public void calibrateCenter() {
  674.             zeroRawValue = lastRawValue;
  675.             logger.log(Level.FINE, "Calibrating axis {0} to {1}",
  676.                     new Object[]{getName(), zeroRawValue});
  677.         }
  678.  
  679.     }
  680.    
  681.     public class AndroidJoystickButton extends DefaultJoystickButton
  682.     {
  683.         int keyCode = -1;
  684.         boolean pressed = false;
  685.         boolean hasChanged = false;
  686.  
  687.         public AndroidJoystickButton(InputManager inputManager, Joystick parent,
  688.                 int buttonIndex, String name, String logicalId)
  689.         {
  690.             super(inputManager, parent, buttonIndex, name, logicalId);
  691.         }        
  692.  
  693.         protected boolean isChanged() {
  694.             return hasChanged;
  695.         }
  696.        
  697.         protected void setPressed (boolean pr)
  698.         {
  699.             pressed = pr;
  700.         }        
  701.        
  702.         protected boolean isPressed()
  703.         {
  704.             return pressed;
  705.         }        
  706.        
  707.         protected int getKeyCode()
  708.         {
  709.             return keyCode;
  710.         }      
  711.        
  712.         protected void setKeyCode(int kc)
  713.         {
  714.             keyCode = kc;
  715.         }  
  716.     }
  717. }
Advertisement
Add Comment
Please, Sign In to add comment