Example usage for java.lang Math toDegrees

List of usage examples for java.lang Math toDegrees

Introduction

In this page you can find the example usage for java.lang Math toDegrees.

Prototype

public static double toDegrees(double angrad) 

Source Link

Document

Converts an angle measured in radians to an approximately equivalent angle measured in degrees.

Usage

From source file:fr.cs.examples.propagation.DSSTPropagation.java

/** Print the results in the output file
 *
 *  @param handler orbit handler//from   ww w  .ja v  a 2 s.  c o  m
 *  @param output output file
 *  @param sart start date of propagation
 *  @throws OrekitException 
 *  @throws IOException 
 */
private void printOutput(final File output, final OrbitHandler handler, final AbsoluteDate start)
        throws OrekitException, IOException {
    // Output format:
    // time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
    final String format = new String(
            " %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
    final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
    buffer.write(
            "##   time_from_start(s)            a(km)                      e                      i(deg)         ");
    buffer.write(
            "         raan(deg)                pa(deg)              mean_anomaly(deg)              ey/h          ");
    buffer.write(
            "           ex/k                    hy/p                     hx/q             mean_longitude_arg(deg)");
    buffer.write(
            "       Xposition(km)           Yposition(km)             Zposition(km)           Xvelocity(km/s)    ");
    buffer.write("      Yvelocity(km/s)         Zvelocity(km/s)");
    buffer.newLine();
    for (Orbit o : handler.getOrbits()) {
        final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
        // Time from start (s)
        final double time = o.getDate().durationFrom(start);
        // Semi-major axis (km)
        final double a = o.getA() / 1000.;
        // Keplerian elements
        // Eccentricity
        final double e = o.getE();
        // Inclination (degrees)
        final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
        // Right Ascension of Ascending Node (degrees)
        KeplerianOrbit ko = new KeplerianOrbit(o);
        final double ra = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
        // Perigee Argument (degrees)
        final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
        // Mean Anomaly (degrees)
        final double am = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
        // Equinoctial elements
        // ey/h component of eccentricity vector
        final double h = o.getEquinoctialEy();
        // ex/k component of eccentricity vector
        final double k = o.getEquinoctialEx();
        // hy/p component of inclination vector
        final double p = o.getHy();
        // hx/q component of inclination vector
        final double q = o.getHx();
        // Mean Longitude Argument (degrees)
        final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
        // Cartesian elements
        // Position along X in inertial frame (km)
        final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
        // Position along Y in inertial frame (km)
        final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
        // Position along Z in inertial frame (km)
        final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
        // Velocity along X in inertial frame (km/s)
        final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
        // Velocity along Y in inertial frame (km/s)
        final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
        // Velocity along Z in inertial frame (km/s)
        final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
        buffer.write(
                f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
        buffer.newLine();
        f.close();
    }
    buffer.close();
}

From source file:app.akexorcist.gdaplibrary.GoogleDirection.java

private float getBearing(LatLng begin, LatLng end) {
    double lat = Math.abs(begin.latitude - end.latitude);
    double lng = Math.abs(begin.longitude - end.longitude);
    if (begin.latitude < end.latitude && begin.longitude < end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)));
    else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
    else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
    else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
    return -1;//w  w  w  .j  a va  2  s.c o m
}

From source file:com.achep.acdisplay.ui.fragments.AcDisplayFragment.java

private void populateStdAnimation(float progress) {
    float height = getSceneView().getHeight();
    float y = height * progress;
    double degrees = Math.toDegrees(Math.acos((height - y) / height));

    mSceneContainer.setAlpha(1f - progress);
    mSceneContainer.setTranslationY(y);// w  w  w .j  a v  a  2 s  .  c  om
    mSceneContainer.setRotationX((float) (-degrees / 2f));
}

From source file:com.larvalabs.svgandroid.SVGParser.java

/**
 * Elliptical arc implementation based on the SVG specification notes
 * Adapted from the Batik library (Apache-2 license) by SAU
 *///from   w  w  w .  j  av a2s.c o  m

private static void drawArc(Path path, double x0, double y0, double x, double y, double rx, double ry,
        double angle, boolean largeArcFlag, boolean sweepFlag) {
    double dx2 = (x0 - x) / 2.0;
    double dy2 = (y0 - y) / 2.0;
    angle = Math.toRadians(angle % 360.0);
    double cosAngle = Math.cos(angle);
    double sinAngle = Math.sin(angle);

    double x1 = (cosAngle * dx2 + sinAngle * dy2);
    double y1 = (-sinAngle * dx2 + cosAngle * dy2);
    rx = Math.abs(rx);
    ry = Math.abs(ry);

    double Prx = rx * rx;
    double Pry = ry * ry;
    double Px1 = x1 * x1;
    double Py1 = y1 * y1;

    // check that radii are large enough
    double radiiCheck = Px1 / Prx + Py1 / Pry;
    if (radiiCheck > 1) {
        rx = Math.sqrt(radiiCheck) * rx;
        ry = Math.sqrt(radiiCheck) * ry;
        Prx = rx * rx;
        Pry = ry * ry;
    }

    // Step 2 : Compute (cx1, cy1)
    double sign = (largeArcFlag == sweepFlag) ? -1 : 1;
    double sq = ((Prx * Pry) - (Prx * Py1) - (Pry * Px1)) / ((Prx * Py1) + (Pry * Px1));
    sq = (sq < 0) ? 0 : sq;
    double coef = (sign * Math.sqrt(sq));
    double cx1 = coef * ((rx * y1) / ry);
    double cy1 = coef * -((ry * x1) / rx);

    double sx2 = (x0 + x) / 2.0;
    double sy2 = (y0 + y) / 2.0;
    double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1);
    double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1);

    // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
    double ux = (x1 - cx1) / rx;
    double uy = (y1 - cy1) / ry;
    double vx = (-x1 - cx1) / rx;
    double vy = (-y1 - cy1) / ry;
    double p, n;

    // Compute the angle start
    n = Math.sqrt((ux * ux) + (uy * uy));
    p = ux; // (1 * ux) + (0 * uy)
    sign = (uy < 0) ? -1.0 : 1.0;
    double angleStart = Math.toDegrees(sign * Math.acos(p / n));

    // Compute the angle extent
    n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
    p = ux * vx + uy * vy;
    sign = (ux * vy - uy * vx < 0) ? -1.0 : 1.0;
    double angleExtent = Math.toDegrees(sign * Math.acos(p / n));
    if (!sweepFlag && angleExtent > 0) {
        angleExtent -= 360f;
    } else if (sweepFlag && angleExtent < 0) {
        angleExtent += 360f;
    }
    angleExtent %= 360f;
    angleStart %= 360f;

    RectF oval = new RectF((float) (cx - rx), (float) (cy - ry), (float) (cx + rx), (float) (cy + ry));
    path.addArc(oval, (float) angleStart, (float) angleExtent);
}

From source file:com.mbientlab.metawear.tutorial.starter.DeviceSetupActivityFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Grab Date//  w w  w.  j a va  2 s .  c  o m
    year = Calendar.getInstance().get(Calendar.YEAR);
    month = Calendar.getInstance().get(Calendar.MONTH) + 1;
    day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

    // Initialize variables used for trial name
    SubjectCode = (EditText) view.findViewById(R.id.SubjectCode);
    TrialNumber = (EditText) view.findViewById(R.id.TrialNumber);
    TrialType = (EditText) view.findViewById(R.id.TrialType);
    FileName_text = (TextView) view.findViewById(R.id.FileName_text);

    // Initialize buttons for device behavior
    ProgramState_text = (TextView) view.findViewById(R.id.ProgramState_text);
    ProgramState_switch = (Switch) view.findViewById(R.id.ProgramState);

    // Initialize thresholds and feedback toggles
    Threshold_L = (EditText) view.findViewById(R.id.Threshold_L);
    MotorToggle_switch = (Switch) view.findViewById(R.id.MotorToggle_switch);

    Threshold_L.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Threshold_L_string = Threshold_L.getText().toString();
            if (Threshold_L_string.length() > 0) {
                threshold_L = Double.parseDouble(Threshold_L_string);
            } else {

            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    SubjectCode.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            SubjectCode_string = SubjectCode.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialType.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialType_string = TrialType.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialNumber.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialNumber_string = TrialNumber.getText().toString();
            if (TrialNumber_string.length() > 0) {
                TrialNumber_int = Integer.parseInt(TrialNumber_string);
                TrialNumber_string_final = String.format("%03d", TrialNumber_int);
            } else {
            }

            /*if (TrialNumber_string.length() == 1){
            TrialNumber_string_final = "00"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 2){
            TrialNumber_string_final = "0"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 3){
            TrialNumber_string_final = TrialNumber_string;
            }*/
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    MotorToggle_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (MotorToggle_state == false) {
                MotorToggle_state = true;
            } else {
                MotorToggle_state = false;
            }
        }
    });

    ProgramState_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (ProgramState_status == false) {
                ProgramState_status = true;
                accelerometer.acceleration().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Accel and Prepare for writing to CSV
                                accel_raw_x = data.value(Acceleration.class).x();
                                accel_raw_y = data.value(Acceleration.class).y();
                                accel_raw_z = data.value(Acceleration.class).z();
                                accel_string_x = Double.toString(accel_raw_x);
                                accel_string_y = Double.toString(accel_raw_y);
                                accel_string_z = Double.toString(accel_raw_z);

                                if (initial_accel_loop == 1) {
                                    double vertical_sensor_norm_init = Math.sqrt(accel_raw_x * accel_raw_x
                                            + accel_raw_y * accel_raw_y + accel_raw_z * accel_raw_z);
                                    vertical_sensor_0 = accel_raw_x * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_1 = accel_raw_y * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_2 = accel_raw_z * 1 / vertical_sensor_norm_init;

                                    initial_accel_loop = 0;
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {

                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        accelerometer.acceleration().start();
                        accelerometer.start();
                        Log.i("MainActivity", "Running!");

                        initial_accel_loop = 1;

                        ProgramState_text.setText("Collecting");
                        return null;
                    }
                });
                gyroscope.angularVelocity().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Gyro and Prepare for writing to CSV
                                gyro_raw_x = data.value(AngularVelocity.class).x();
                                gyro_raw_y = data.value(AngularVelocity.class).y();
                                gyro_raw_z = data.value(AngularVelocity.class).z();
                                gyro_raw_x = Math.toRadians(gyro_raw_x);
                                gyro_raw_y = Math.toRadians(gyro_raw_y);
                                gyro_raw_z = Math.toRadians(gyro_raw_z);

                                gyro_string_x = Double.toString(gyro_raw_x);
                                gyro_string_y = Double.toString(gyro_raw_y);
                                gyro_string_z = Double.toString(gyro_raw_z);

                                if (initial_accel_loop == 0) {
                                    // Get Timestamp
                                    currentTime = System.currentTimeMillis();
                                    deltaTime = (currentTime - previousTime) / 1000;

                                    if (gyro_raw_x != previous_gyro_raw_x) {
                                        previous_gyro_raw_x = gyro_raw_x;

                                        totalTime = totalTime + deltaTime;
                                        time_stamp = Double.toString(totalTime);
                                        previousTime = currentTime;

                                        //// CALCULATE INCLINATION ANGLE /////
                                        vertical_sensor_from_accel_0 = accel_raw_x;
                                        vertical_sensor_from_accel_1 = accel_raw_y;
                                        vertical_sensor_from_accel_2 = accel_raw_z;

                                        // normalize accelerometer estimate
                                        vertical_sensor_from_accel_norm = Math.sqrt(
                                                vertical_sensor_from_accel_0 * vertical_sensor_from_accel_0
                                                        + vertical_sensor_from_accel_1
                                                                * vertical_sensor_from_accel_1
                                                        + vertical_sensor_from_accel_2
                                                                * vertical_sensor_from_accel_2);

                                        vertical_sensor_from_accel_0 = vertical_sensor_from_accel_0
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_1 = vertical_sensor_from_accel_1
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_2 = vertical_sensor_from_accel_2
                                                / vertical_sensor_from_accel_norm;

                                        // GYROSCOPE INCLINATION ANGLE
                                        angular_velocity_body_matrix_0_0 = 0;
                                        angular_velocity_body_matrix_0_1 = -gyro_raw_z;
                                        angular_velocity_body_matrix_0_2 = gyro_raw_y;
                                        angular_velocity_body_matrix_1_0 = gyro_raw_z;
                                        angular_velocity_body_matrix_1_1 = 0;
                                        angular_velocity_body_matrix_1_2 = -gyro_raw_x;
                                        angular_velocity_body_matrix_2_0 = -gyro_raw_y;
                                        angular_velocity_body_matrix_2_1 = gyro_raw_x;
                                        angular_velocity_body_matrix_2_2 = 0;

                                        // rotational velocity based on gyroscope readings
                                        vertical_sensor_dot_from_gyro_0 = -(angular_velocity_body_matrix_0_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_0_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_0_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_1 = -(angular_velocity_body_matrix_1_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_1_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_1_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_2 = -(angular_velocity_body_matrix_2_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_2_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_2_2 * vertical_sensor_2);

                                        // rotational velocity based on difference to accelerometer estimate
                                        vertical_sensor_dot_from_accel_0 = -alpha
                                                * (vertical_sensor_0 - vertical_sensor_from_accel_0);
                                        vertical_sensor_dot_from_accel_1 = -alpha
                                                * (vertical_sensor_1 - vertical_sensor_from_accel_1);
                                        vertical_sensor_dot_from_accel_2 = -alpha
                                                * (vertical_sensor_2 - vertical_sensor_from_accel_2);

                                        // combine the two estimates
                                        vertical_sensor_dot_0 = vertical_sensor_dot_from_gyro_0
                                                + vertical_sensor_dot_from_accel_0;
                                        vertical_sensor_dot_1 = vertical_sensor_dot_from_gyro_1
                                                + vertical_sensor_dot_from_accel_1;
                                        vertical_sensor_dot_2 = vertical_sensor_dot_from_gyro_2
                                                + vertical_sensor_dot_from_accel_2;

                                        // integrate rotational velocity
                                        vertical_sensor_0 = vertical_sensor_0
                                                + deltaTime * vertical_sensor_dot_0;
                                        vertical_sensor_1 = vertical_sensor_1
                                                + deltaTime * vertical_sensor_dot_1;
                                        vertical_sensor_2 = vertical_sensor_2
                                                + deltaTime * vertical_sensor_dot_2;

                                        // normalize after integration
                                        vertical_sensor_norm = Math.sqrt(vertical_sensor_0 * vertical_sensor_0
                                                + vertical_sensor_1 * vertical_sensor_1
                                                + vertical_sensor_2 * vertical_sensor_2);
                                        vertical_sensor_0 = vertical_sensor_0 / vertical_sensor_norm;
                                        vertical_sensor_1 = vertical_sensor_1 / vertical_sensor_norm;
                                        vertical_sensor_2 = vertical_sensor_2 / vertical_sensor_norm;

                                        // calculate inclination angles
                                        inclination_angle = Math.acos(vertical_sensor_0 * sensor_axis_sensor_0
                                                + vertical_sensor_1 * sensor_axis_sensor_1
                                                + vertical_sensor_2 * sensor_axis_sensor_2);
                                        inclination_angle_from_accel = Math
                                                .acos(vertical_sensor_from_accel_0 * sensor_axis_sensor_0
                                                        + vertical_sensor_from_accel_1 * sensor_axis_sensor_1
                                                        + vertical_sensor_from_accel_2 * sensor_axis_sensor_2);
                                        // convert to degrees
                                        inclination_angle = Math.toDegrees(inclination_angle);
                                        inclination_angle_from_accel = Math
                                                .toDegrees(inclination_angle_from_accel);

                                        if (inclination_angle > threshold_L && MotorToggle_state == true) {
                                            motor_status = 1;
                                            //board.getModule(Haptic.class).startBuzzer;
                                            metawear.getModule(Haptic.class).startBuzzer((short) 40);
                                        } else {
                                            motor_status = 0;
                                        }

                                        Log.i("MainActivity", Integer.toString(motor_status));
                                        Log.i("MainActivity", Double.toString(inclination_angle));
                                        csv_entry = csv_entry + time_stamp + "," + inclination_angle + ","
                                                + MotorToggle_state + "," + motor_status + ","
                                                + inclination_angle_from_accel + "," + threshold_L + "," + alpha
                                                + "," + accel_string_x + "," + accel_string_y + ","
                                                + accel_string_z + "," + gyro_string_x + "," + gyro_string_y
                                                + "," + gyro_string_z + "\n";
                                    }
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {
                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        gyroscope.angularVelocity().start();
                        gyroscope.start();

                        currentTime = System.currentTimeMillis();
                        previousTime = currentTime;
                        totalTime = 0;
                        return null;
                    }
                });
            } else {
                // Stop all activity
                Log.i("MainActivity", "Stopped");
                ProgramState_status = false;
                accelerometer.stop();
                accelerometer.acceleration().stop();
                gyroscope.stop();
                gyroscope.angularVelocity().stop();
                ProgramState_text.setText("Saved previous data, Ready to Start");

                filename = FileName_text.getText().toString();

                file = new File(ctx.getExternalFilesDir(null), filename);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(csv_entry.getBytes());
                    os.close();
                    Log.i("MainActivity", "File is created as..." + filename);
                } catch (IOException e) {
                    Log.i("MainActivity", "File NOT created ...!");
                    e.printStackTrace();
                }

                // Reinitialize CSV Entry
                csv_entry = "time" + "," + "inclination angle" + "," + "feedback toggle" + "," + "motor status"
                        + "," + "inclination angle from accelerometers" + "," + "threshold" + "," + "alpha"
                        + "," + "accelerometer_x" + "," + "accelerometer_y" + "," + "acceleromter_z" + ","
                        + "gyroscope_x" + "," + "gyroscope_y" + "," + "gyroscope_z" + "\n" + "sec" + "," + "deg"
                        + "," + "binary" + "," + "binary" + "," + "deg" + "," + "deg" + "," + " " + "," + "g"
                        + "," + "g" + "," + "g" + "," + "deg/sec" + "," + "deg/sec" + "," + "deg/sec" + "\n";
                ProgramState_text.setText("Data Saved and Cleared");

                // Ensure the first loop of next trial goes thru accel first
                initial_accel_loop = 1;

                // Next Trial Increment
                TrialNumber_int = TrialNumber_int + 1;
                TrialNumber.setText(TrialNumber_int.toString());
            }
        }
    });
}

From source file:com.example.zoetablet.BasicFragmentActivity.java

public float[] calculateOrientation() {
    float[] values = new float[3];
    float[] R = new float[9];
    float[] outR = new float[9];

    SensorManager.getRotationMatrix(R, null, aValues, mValues);
    SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Y, outR);

    SensorManager.getOrientation(outR, values);

    // Convert from Radians to Degrees.
    values[0] = (float) Math.toDegrees(values[0]);
    values[1] = (float) Math.toDegrees(values[1]);
    values[2] = (float) Math.toDegrees(values[2]);

    // System.out.println("Compass " + values[0] + " " + values[1] + " " + values[2]);
    if (values[0] != 0.0 && values[1] != 0.0) {
        compassV0 = values[0];/*from w  w  w .j  a v a2  s.  c o m*/
        compassV1 = values[1];
        compassV2 = values[2];
    }

    if (values[0] == 0.0 && values[1] == 0.0) {
        //If data is spitting out zeros, keep last good value
        values[0] = compassV0;
        values[1] = compassV1;
        values[2] = compassV2;
    }
    return values;
}

From source file:com.android.gpstest.GpsTestActivity.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override/*from w w  w  .  j  a v a  2  s.  c  om*/
public void onSensorChanged(SensorEvent event) {

    double orientation = Double.NaN;
    double tilt = Double.NaN;

    switch (event.sensor.getType()) {
    case Sensor.TYPE_ROTATION_VECTOR:
        // Modern rotation vector sensors
        if (!mTruncateVector) {
            try {
                SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
            } catch (IllegalArgumentException e) {
                // On some Samsung devices, an exception is thrown if this vector > 4 (see #39)
                // Truncate the array, since we can deal with only the first four values
                Log.e(TAG, "Samsung device error? Will truncate vectors - " + e);
                mTruncateVector = true;
                // Do the truncation here the first time the exception occurs
                getRotationMatrixFromTruncatedVector(event.values);
            }
        } else {
            // Truncate the array to avoid the exception on some devices (see #39)
            getRotationMatrixFromTruncatedVector(event.values);
        }

        int rot = getWindowManager().getDefaultDisplay().getRotation();
        switch (rot) {
        case Surface.ROTATION_0:
            // No orientation change, use default coordinate system
            SensorManager.getOrientation(mRotationMatrix, mValues);
            // Log.d(TAG, "Rotation-0");
            break;
        case Surface.ROTATION_90:
            // Log.d(TAG, "Rotation-90");
            SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_Y,
                    SensorManager.AXIS_MINUS_X, mRemappedMatrix);
            SensorManager.getOrientation(mRemappedMatrix, mValues);
            break;
        case Surface.ROTATION_180:
            // Log.d(TAG, "Rotation-180");
            SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X,
                    SensorManager.AXIS_MINUS_Y, mRemappedMatrix);
            SensorManager.getOrientation(mRemappedMatrix, mValues);
            break;
        case Surface.ROTATION_270:
            // Log.d(TAG, "Rotation-270");
            SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_Y,
                    SensorManager.AXIS_X, mRemappedMatrix);
            SensorManager.getOrientation(mRemappedMatrix, mValues);
            break;
        default:
            // This shouldn't happen - assume default orientation
            SensorManager.getOrientation(mRotationMatrix, mValues);
            // Log.d(TAG, "Rotation-Unknown");
            break;
        }
        orientation = Math.toDegrees(mValues[0]); // azimuth
        tilt = Math.toDegrees(mValues[1]);
        break;
    case Sensor.TYPE_ORIENTATION:
        // Legacy orientation sensors
        orientation = event.values[0];
        break;
    default:
        // A sensor we're not using, so return
        return;
    }

    // Correct for true north, if preference is set
    if (mFaceTrueNorth && mGeomagneticField != null) {
        orientation += mGeomagneticField.getDeclination();
        // Make sure value is between 0-360
        orientation = MathUtils.mod((float) orientation, 360.0f);
    }

    for (GpsTestListener listener : mGpsTestListeners) {
        listener.onOrientationChanged(orientation, tilt);
    }
}

From source file:code.Servlet.java

private void createSteps(String idEvent, Statement stmt) throws IOException, SQLException {

    String query = "SELECT * FROM event join city where event.city_name=city.name and event.idEvent=" + idEvent
            + "'"; // TODO && event.idEvent=idEvent
    ResultSet res = stmt.executeQuery(query);

    if (!res.next()) {
        System.out.println("Nessun evento");
    }/*from w w  w  .ja va  2  s .  c  om*/

    Location start = new Location(Double.parseDouble(res.getString("start_lat")),
            Double.parseDouble(res.getString("start_lon")));
    Location center = new Location(Double.parseDouble(res.getString("latitude")),
            Double.parseDouble(res.getString("longitude")));
    double d = Double.parseDouble(res.getString("diameter"));

    double randLat = (start.lat - center.lat) / kmToLat;
    double randLon = (start.lon - center.lon) / kmToLon;

    System.out.println("center: " + Double.parseDouble(res.getString("latitude")) + ", "
            + Double.parseDouble(res.getString("longitude")));
    System.out.println("randLat: " + randLat + "   randLon: " + randLon);
    System.out
            .println("randLat*kmToLat: " + (randLat * kmToLat) + "   randLon*kmToLon: " + (randLon * kmToLon));

    double a = -randLon, b = -randLat;
    double teta = 0;
    if (a == 0 && b == 0)
        ; // error, recalculate randLat and randLon
    if (b > 0) {
        teta = Math.toDegrees(Math.atan(a / b));
    }
    if (a >= 0 && b < 0) {
        teta = 180 + Math.toDegrees(Math.atan(a / b));
    }
    if (a < 0 && b < 0) {
        teta = -180 + Math.toDegrees(Math.atan(a / b));
    }
    if (a > 0 && b == 0) {
        teta = 90;
    }
    if (a < 0 && b == 0) {
        teta = -90;
    }
    if (teta < 0) {
        teta += 360;
    }

    double offset = (teta + 90 < 360) ? (teta + 90) : (teta + 90 - 360);
    System.out.println("teta: " + teta + "   offset: " + offset);

    query = "select number_step from event where idEvent=" + idEvent + "'";
    res = stmt.executeQuery(query);
    if (!res.next()) {
        System.out.println("vuoto numero step nell'evento");
    }

    // at the beginning of the game
    int N = Integer.parseInt(res.getString("number_step")); //numero utenti fare limite damiano
    double passo = 180 / N;

    // get rsndom id question
    query = "SELECT idQuestion FROM mydb_treasure.question where idQuestion<>6 order by rand()";
    res = stmt.executeQuery(query);
    if (!res.next()) {
        System.out.println("Nessuna domanda nel db");
    }
    List<String> questionsId = new ArrayList<String>();
    do {
        questionsId.add(res.getString("idQuestion"));
    } while (res.next());

    double[] tete = new double[N + 1];
    for (int i = 0; i < N + 1; i++) { //FORSE PROBLME SE STEP> QUESTION ****************
        tete[i] = (offset - i * passo < 0.0) ? ((offset - i * passo) + 360) : (offset - i * passo);
        query = "INSERT INTO `mydb_treasure`.`step`(`angle`, `len_step`, `Question_idQuestion`, `event_idEvent`) VALUES ('"
                + tete[i] + "', '" + lenPasso + "', '" + questionsId.get(i % questionsId.size()) + "', "
                + idEvent + "')";
        stmt.executeUpdate(query);
    }
}

From source file:com.android.screenspeak.contextmenu.RadialMenuView.java

private boolean getClosestTouchedWedge(float dX, float dY, float touchDistSq, TouchedMenuItem result) {
    if (touchDistSq <= mInnerRadiusSq) {
        // The user is touching the center dot.
        return false;
    }/*from  www .ja v a 2 s. co m*/

    final RadialMenu menu = (mSubMenu != null) ? mSubMenu : mRootMenu;
    int menuSize = menu.size();
    if (menuSize == 0)
        return false;
    final float offset = (mSubMenu != null) ? mSubMenuOffset : mRootMenuOffset;

    // Which wedge is the user touching?
    final double angle = Math.atan2(dX, dY);
    final double wedgeArc = (360.0 / menuSize);
    final double offsetArc = (wedgeArc / 2.0) - offset;

    double touchArc = (((180.0 - Math.toDegrees(angle)) + offsetArc) % 360);

    if (touchArc < 0) {
        touchArc += 360;
    }

    final int wedgeNum = (int) (touchArc / wedgeArc);
    if ((wedgeNum < 0) || (wedgeNum >= menuSize)) {
        LogUtils.log(this, Log.ERROR, "Invalid wedge index: %d", wedgeNum);
        return false;
    }

    result.item = menu.getItem(wedgeNum);
    result.isDirectTouch = (touchDistSq < mExtremeRadiusSq);
    return true;
}

From source file:com.googlecode.eyesfree.widget.RadialMenuView.java

private boolean getClosestTouchedWedge(float dX, float dY, float touchDistSq, TouchedMenuItem result) {
    if (touchDistSq <= mInnerRadiusSq) {
        // The user is touching the center dot.
        return false;
    }//from ww  w  .j  av  a  2  s  .  co m

    final RadialMenu menu = (mSubMenu != null) ? mSubMenu : mRootMenu;
    final float offset = (mSubMenu != null) ? mSubMenuOffset : mRootMenuOffset;

    // Which wedge is the user touching?
    final double angle = Math.atan2(dX, dY);
    final double wedgeArc = (360.0 / menu.size());
    final double offsetArc = (wedgeArc / 2.0) - offset;

    double touchArc = (((180.0 - Math.toDegrees(angle)) + offsetArc) % 360);

    if (touchArc < 0) {
        touchArc += 360;
    }

    final int wedgeNum = (int) (touchArc / wedgeArc);
    if ((wedgeNum < 0) || (wedgeNum > menu.size())) {
        LogUtils.log(this, Log.ERROR, "Invalid wedge index: %d", wedgeNum);
        return false;
    }

    result.item = menu.getItem(wedgeNum);
    result.isDirectTouch = (touchDistSq < mExtremeRadiusSq);
    return true;
}