Example usage for java.lang Math sin

List of usage examples for java.lang Math sin

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double sin(double a) 

Source Link

Document

Returns the trigonometric sine of an angle.

Usage

From source file:dnimp.Statistics.java

/**
 *Returns the linear distance between 2 geographical coordinates; for sQTBA
 *@param x Latitude/*  w w w  .j a v a 2s  . c o m*/
 *@param y Longitude
 *@param xR receptor site latitude
 *@param yR receptor site longitude
 */
public double haversineV(double x, double y, double xR, double yR) {
    double re = 6378.1369; //equatorial earth's radius
    double pi360 = Math.PI / 360.0;
    double pi180 = Math.PI / 180.0;

    double term1 = Math.sin(pi360 * (x - xR));
    double term2 = Math.cos(pi180 * xR);
    double term3 = Math.cos(pi180 * x);
    double term4 = Math.sin(pi360 * (y - yR));
    double sqrtauxV = 2 * re
            * Math.asin(Math.sqrt(Math.pow(term1, 2.0) + (term2 * term3 * Math.pow(term4, 2.0))));

    return sqrtauxV;
}

From source file:edu.ucsf.valelab.saim.calculations.SaimFunction.java

/**
 * Calculates the Saim function using established wavelength, angle, 
 * refractive index of the sample, and thickness of the oxide layer
 * @param h - height above the oxide layer in nm
 * @return - Field Strength (arbitrary units)
 *//*from  w ww .  j  av a 2s  .co m*/
@Override
public double value(double h) {
    counter++;

    Complex rTE = getFresnelTE(angle_);
    double phaseDiff = SaimCalc.PhaseDiff(sd_.wavelength_, angle_, sd_.nSample_, h);
    double c = rTE.getReal();
    double d = rTE.getImaginary();
    double val = 1 + 2 * c * Math.cos(phaseDiff) - 2 * d * Math.sin(phaseDiff) + c * c + d * d;

    // The following is more literal, but about 10 times slower:
    /**
     * Complex tmp = new Complex(Math.cos(phaseDiff), Math.sin(phaseDiff));
     * Complex fieldStrength = rTE.multiply(tmp);
     * fieldStrength = fieldStrength.add(1.0);
     * double val =  fieldStrength.getReal() * fieldStrength.getReal() + 
     *         fieldStrength.getImaginary() * fieldStrength.getImaginary() ;
     */

    if (!sd_.useBAngle_)
        return sd_.A_ * val + sd_.B_;

    return sd_.A_ * val + sd_.B_ * angle_;
}

From source file:maxSumController.continuous.linear.delaunay.DelaunayFast.java

/**
 * construct an approximate Delaunay triangulation of the points in the
 * samples array using Curtis Rueden's algorithm
 * //from w w w.j a v  a  2s. com
 * @param samples
 *            locations of points for topology - dimensioned
 *            float[dimension][number_of_points]
 * @throws VisADException
 *             a VisAD error occurred
 */
public DelaunayFast(double[][] samples) {
    if (samples.length < 2 || samples.length > 3) {
        throw new IllegalArgumentException("DelaunayFast: dimension must be 2 or 3");
    }
    if (samples.length == 3) {
        throw new NotImplementedException("DelaunayFast: " + "only two dimensions for now");
    }
    int numpts = Math.min(samples[0].length, samples[1].length);
    if (numpts < 3) {
        throw new IllegalArgumentException(
                "DelaunayFast: triangulation is " + "futile with less than 3 samples");
    }
    double[][] samp = new double[2][numpts];
    System.arraycopy(samples[0], 0, samp[0], 0, numpts);
    System.arraycopy(samples[1], 0, samp[1], 0, numpts);
    double[] samp0 = samp[0];
    double[] samp1 = samp[1];

    // rotate samples by ROTATE radians to avoid colinear axis-parallel
    // points
    double cosrot = Math.cos(ROTATE);
    double sinrot = Math.sin(ROTATE);
    for (int i = 0; i < numpts; i++) {
        double x = samp0[i];
        double y = samp1[i];
        samp0[i] = (float) (x * cosrot - y * sinrot);
        samp1[i] = (float) (y * cosrot + x * sinrot);
    }

    // misc. variables
    int ntris = 0;
    int tsize = (int) (2f / 3f * numpts) + 10;
    int[][][] tris = new int[tsize][3][];
    int tp = 0;
    int[] nverts = new int[numpts];
    for (int i = 0; i < numpts; i++)
        nverts[i] = 0;

    // set up the stack
    int ssize = 20; // "stack size"
    int[] ss = new int[ssize + 2]; // "stack start"
    int[] se = new int[ssize + 2]; // "stack end"
    boolean[] vh = new boolean[ssize + 2]; // "vertical/horizontal"
    boolean[] mp = new boolean[ssize + 2]; // "merge points"
    int sp = 0; // "stack pointer"
    int hsize = 10; // "hull stack size"
    int[][] hs = new int[hsize + 2][]; // "hull stack"
    int hsp = 0; // "hull stack pointer"

    // set up initial conditions
    int[] indices = new int[numpts];
    for (int i = 0; i < numpts; i++)
        indices[i] = i;

    // add initial conditions to stack
    sp++;
    ss[0] = 0;
    se[0] = numpts - 1;
    vh[0] = false;
    mp[0] = false;

    // stack loop variables
    int css;
    int cse;
    boolean cvh;
    boolean cmp;

    // stack loop
    while (sp != 0) {
        if (hsp > hsize) {
            // expand hull stack if necessary
            hsize += hsize;
            int newhs[][] = new int[hsize + 2][];
            System.arraycopy(hs, 0, newhs, 0, hs.length);
            hs = newhs;
        }
        if (sp > ssize) {
            // expand stack if necessary
            ssize += ssize;
            int[] newss = new int[ssize + 2];
            int[] newse = new int[ssize + 2];
            boolean[] newvh = new boolean[ssize + 2];
            boolean[] newmp = new boolean[ssize + 2];
            System.arraycopy(ss, 0, newss, 0, ss.length);
            System.arraycopy(se, 0, newse, 0, se.length);
            System.arraycopy(vh, 0, newvh, 0, vh.length);
            System.arraycopy(mp, 0, newmp, 0, mp.length);
            ss = newss;
            se = newse;
            vh = newvh;
            mp = newmp;
        }

        // pop action from stack
        sp--;
        css = ss[sp];
        cse = se[sp];
        cvh = vh[sp];
        cmp = mp[sp];

        if (!cmp) {
            // division step
            if (cse - css >= 3) {
                // sort step
                qsort(indices, samp, cvh ? 0 : 1, css, cse);

                // push merge action onto stack
                ss[sp] = css;
                se[sp] = cse;
                vh[sp] = cvh;
                mp[sp] = true;
                sp++;

                // divide, and push two halves onto stack
                int mid = (css + cse) / 2;
                ss[sp] = css;
                se[sp] = mid;
                vh[sp] = !cvh;
                mp[sp] = false;
                sp++;
                ss[sp] = mid + 1;
                se[sp] = cse;
                vh[sp] = !cvh;
                mp[sp] = false;
                sp++;
            } else {
                // connect step, also push hulls onto hull stack
                int[] hull;
                if (cse - css + 1 == 3) {
                    hull = new int[3];
                    hull[0] = indices[css];
                    hull[1] = indices[css + 1];
                    hull[2] = indices[cse];
                    double a0x = samp0[hull[0]];
                    double a0y = samp1[hull[0]];
                    if ((samp0[hull[1]] - a0x) * (samp1[hull[2]] - a0y)
                            - (samp1[hull[1]] - a0y) * (samp0[hull[2]] - a0x) > 0) {
                        // adjust step, hull must remain clockwise
                        hull[1] = indices[cse];
                        hull[2] = indices[css + 1];
                    }
                    tris[tp][0] = new int[1];
                    tris[tp][1] = new int[1];
                    tris[tp][2] = new int[1];
                    tris[tp][0][0] = hull[0];
                    tris[tp][1][0] = hull[1];
                    tris[tp][2][0] = hull[2];
                    tp++;
                    ntris++;
                    nverts[indices[css]]++;
                    nverts[indices[cse]]++;
                    nverts[indices[css + 1]]++;
                } else {
                    hull = new int[2];
                    hull[0] = indices[css];
                    hull[1] = indices[cse];
                }
                hs[hsp++] = hull;
            }
        } else {
            // merge step
            int coord = cvh ? 1 : 0;

            // pop hull arrays from stack
            int[] hull1, hull2;
            hsp -= 2;
            hull2 = cvh ? hs[hsp + 1] : hs[hsp];
            hull1 = cvh ? hs[hsp] : hs[hsp + 1];
            hs[hsp + 1] = null;
            hs[hsp] = null;

            // find upper and lower convex hull additions
            int upp1 = 0;
            int upp2 = 0;
            int low1 = 0;
            int low2 = 0;

            // find initial upper and lower hull indices for later
            // optimization
            for (int i = 1; i < hull1.length; i++) {
                if (samp[coord][hull1[i]] > samp[coord][hull1[upp1]])
                    upp1 = i;
                if (samp[coord][hull1[i]] < samp[coord][hull1[low1]])
                    low1 = i;
            }
            for (int i = 1; i < hull2.length; i++) {
                if (samp[coord][hull2[i]] > samp[coord][hull2[upp2]])
                    upp2 = i;
                if (samp[coord][hull2[i]] < samp[coord][hull2[low2]])
                    low2 = i;
            }

            // hull sweep must be performed thrice to ensure correctness
            for (int t = 0; t < 3; t++) {
                // optimize upp1
                int bob = (upp1 + 1) % hull1.length;
                double ax = samp0[hull2[upp2]];
                double ay = samp1[hull2[upp2]];
                double bamx = samp0[hull1[bob]] - ax;
                double bamy = samp1[hull1[bob]] - ay;
                double camx = samp0[hull1[upp1]] - ax;
                double camy = samp1[hull1[upp1]] - ay;
                float u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                        : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                float v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                        : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                boolean plus_dir = (u < v);
                if (!plus_dir) {
                    bob = upp1;
                    u = 0;
                    v = 1;
                }
                while (u < v) {
                    upp1 = bob;
                    bob = plus_dir ? (upp1 + 1) % hull1.length : (upp1 + hull1.length - 1) % hull1.length;
                    bamx = samp0[hull1[bob]] - ax;
                    bamy = samp1[hull1[bob]] - ay;
                    camx = samp0[hull1[upp1]] - ax;
                    camy = samp1[hull1[upp1]] - ay;
                    u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                            : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                    v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                            : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                }

                // optimize upp2
                bob = (upp2 + 1) % hull2.length;
                ax = samp0[hull1[upp1]];
                ay = samp1[hull1[upp1]];
                bamx = samp0[hull2[bob]] - ax;
                bamy = samp1[hull2[bob]] - ay;
                camx = samp0[hull2[upp2]] - ax;
                camy = samp1[hull2[upp2]] - ay;
                u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                        : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                        : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                plus_dir = (u < v);
                if (!plus_dir) {
                    bob = upp2;
                    u = 0;
                    v = 1;
                }
                while (u < v) {
                    upp2 = bob;
                    bob = plus_dir ? (upp2 + 1) % hull2.length : (upp2 + hull2.length - 1) % hull2.length;
                    bamx = samp0[hull2[bob]] - ax;
                    bamy = samp1[hull2[bob]] - ay;
                    camx = samp0[hull2[upp2]] - ax;
                    camy = samp1[hull2[upp2]] - ay;
                    u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                            : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                    v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                            : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                }

                // optimize low1
                bob = (low1 + 1) % hull1.length;
                ax = samp0[hull2[low2]];
                ay = samp1[hull2[low2]];
                bamx = samp0[hull1[bob]] - ax;
                bamy = samp1[hull1[bob]] - ay;
                camx = samp0[hull1[low1]] - ax;
                camy = samp1[hull1[low1]] - ay;
                u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                        : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                        : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                plus_dir = (u > v);
                if (!plus_dir) {
                    bob = low1;
                    u = 1;
                    v = 0;
                }
                while (u > v) {
                    low1 = bob;
                    bob = plus_dir ? (low1 + 1) % hull1.length : (low1 + hull1.length - 1) % hull1.length;
                    bamx = samp0[hull1[bob]] - ax;
                    bamy = samp1[hull1[bob]] - ay;
                    camx = samp0[hull1[low1]] - ax;
                    camy = samp1[hull1[low1]] - ay;
                    u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                            : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                    v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                            : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                }

                // optimize low2
                bob = (low2 + 1) % hull2.length;
                ax = samp0[hull1[low1]];
                ay = samp1[hull1[low1]];
                bamx = samp0[hull2[bob]] - ax;
                bamy = samp1[hull2[bob]] - ay;
                camx = samp0[hull2[low2]] - ax;
                camy = samp1[hull2[low2]] - ay;
                u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                        : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                        : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                plus_dir = (u > v);
                if (!plus_dir) {
                    bob = low2;
                    u = 1;
                    v = 0;
                }
                while (u > v) {
                    low2 = bob;
                    bob = plus_dir ? (low2 + 1) % hull2.length : (low2 + hull2.length - 1) % hull2.length;
                    bamx = samp0[hull2[bob]] - ax;
                    bamy = samp1[hull2[bob]] - ay;
                    camx = samp0[hull2[low2]] - ax;
                    camy = samp1[hull2[low2]] - ay;
                    u = (cvh) ? (float) (bamy / Math.sqrt(bamx * bamx + bamy * bamy))
                            : (float) (bamx / Math.sqrt(bamx * bamx + bamy * bamy));
                    v = (cvh) ? (float) (camy / Math.sqrt(camx * camx + camy * camy))
                            : (float) (camx / Math.sqrt(camx * camx + camy * camy));
                }
            }

            // calculate number of points in inner hull
            int nih1, nih2;
            int noh1, noh2;
            int h1ups, h2ups;
            if (low1 == upp1) {
                nih1 = hull1.length;
                noh1 = 1;
                h1ups = 0;
            } else {
                nih1 = low1 - upp1 + 1;
                if (nih1 <= 0)
                    nih1 += hull1.length;
                noh1 = hull1.length - nih1 + 2;
                h1ups = 1;
            }
            if (low2 == upp2) {
                nih2 = hull2.length;
                noh2 = 1;
                h2ups = 0;
            } else {
                nih2 = upp2 - low2 + 1;
                if (nih2 <= 0)
                    nih2 += hull2.length;
                noh2 = hull2.length - nih2 + 2;
                h2ups = 1;
            }

            // copy hull1 & hull2 info into merged hull array
            int[] hull = new int[noh1 + noh2];
            int hullnum = 0;
            int spot;

            // go clockwise until upp1 is reached
            for (spot = low1; spot != upp1; hullnum++, spot = (spot + 1) % hull1.length) {
                hull[hullnum] = hull1[spot];
            }

            // append upp1
            hull[hullnum++] = hull1[upp1];

            // go clockwise until low2 is reached
            for (spot = upp2; spot != low2; hullnum++, spot = (spot + 1) % hull2.length) {
                hull[hullnum] = hull2[spot];
            }

            // append low2
            hull[hullnum++] = hull2[low2];

            // now push the new, completed hull onto the hull stack
            hs[hsp++] = hull;

            // stitch a connection between the two triangulations
            int base1 = low1;
            int base2 = low2;
            int oneUp1 = (base1 + hull1.length - 1) % hull1.length;
            int oneUp2 = (base2 + 1) % hull2.length;

            // when both sides reach the top the merge is complete
            int ntd = (noh1 == 1 || noh2 == 1) ? nih1 + nih2 - 1 : nih1 + nih2 - 2;
            tris[tp][0] = new int[ntd];
            tris[tp][1] = new int[ntd];
            tris[tp][2] = new int[ntd];
            for (int t = 0; t < ntd; t++) {

                // special case if side 1 has reached the top
                if (h1ups == nih1) {
                    oneUp2 = (base2 + 1) % hull2.length;
                    tris[tp][0][t] = hull2[base2];
                    tris[tp][1][t] = hull1[base1];
                    tris[tp][2][t] = hull2[oneUp2];
                    ntris++;
                    nverts[hull1[base1]]++;
                    nverts[hull2[base2]]++;
                    nverts[hull2[oneUp2]]++;
                    base2 = oneUp2;
                    h2ups++;
                }

                // special case if side 2 has reached the top
                else if (h2ups == nih2) {
                    oneUp1 = (base1 + hull1.length - 1) % hull1.length;
                    tris[tp][0][t] = hull2[base2];
                    tris[tp][1][t] = hull1[base1];
                    tris[tp][2][t] = hull1[oneUp1];
                    ntris++;
                    nverts[hull1[base1]]++;
                    nverts[hull2[base2]]++;
                    nverts[hull1[oneUp1]]++;
                    base1 = oneUp1;
                    h1ups++;
                }

                // neither side has reached the top yet
                else {
                    boolean d;
                    int hb1 = hull1[base1];
                    int ho1 = hull1[oneUp1];
                    int hb2 = hull2[base2];
                    int ho2 = hull2[oneUp2];
                    double ax = samp0[ho2];
                    double ay = samp1[ho2];
                    double bx = samp0[hb2];
                    double by = samp1[hb2];
                    double cx = samp0[ho1];
                    double cy = samp1[ho1];
                    double dx = samp0[hb1];
                    double dy = samp1[hb1];
                    double abx = ax - bx;
                    double aby = ay - by;
                    double acx = ax - cx;
                    double acy = ay - cy;
                    double dbx = dx - bx;
                    double dby = dy - by;
                    double dcx = dx - cx;
                    double dcy = dy - cy;
                    double Q = abx * acx + aby * acy;
                    double R = dbx * abx + dby * aby;
                    double S = acx * dcx + acy * dcy;
                    double T = dbx * dcx + dby * dcy;
                    boolean QD = abx * acy - aby * acx >= 0;
                    boolean RD = dbx * aby - dby * abx >= 0;
                    boolean SD = acx * dcy - acy * dcx >= 0;
                    boolean TD = dcx * dby - dcy * dbx >= 0;
                    boolean sig = (QD ? 1 : 0) + (RD ? 1 : 0) + (SD ? 1 : 0) + (TD ? 1 : 0) < 2;
                    if (QD == sig)
                        d = true;
                    else if (RD == sig)
                        d = false;
                    else if (SD == sig)
                        d = false;
                    else if (TD == sig)
                        d = true;
                    else if (Q < 0 && T < 0 || R > 0 && S > 0)
                        d = true;
                    else if (R < 0 && S < 0 || Q > 0 && T > 0)
                        d = false;
                    else if ((Q < 0 ? Q : T) < (R < 0 ? R : S))
                        d = true;
                    else
                        d = false;
                    if (d) {
                        tris[tp][0][t] = hull2[base2];
                        tris[tp][1][t] = hull1[base1];
                        tris[tp][2][t] = hull2[oneUp2];
                        ntris++;
                        nverts[hull1[base1]]++;
                        nverts[hull2[base2]]++;
                        nverts[hull2[oneUp2]]++;

                        // use diagonal (base1, oneUp2) as new base
                        base2 = oneUp2;
                        h2ups++;
                        oneUp2 = (base2 + 1) % hull2.length;
                    } else {
                        tris[tp][0][t] = hull2[base2];
                        tris[tp][1][t] = hull1[base1];
                        tris[tp][2][t] = hull1[oneUp1];
                        ntris++;
                        nverts[hull1[base1]]++;
                        nverts[hull2[base2]]++;
                        nverts[hull1[oneUp1]]++;

                        // use diagonal (base2, oneUp1) as new base
                        base1 = oneUp1;
                        h1ups++;
                        oneUp1 = (base1 + hull1.length - 1) % hull1.length;
                    }
                }
            }
            tp++;
        }
    }

    // build Tri component
    Tri = new int[ntris][3];
    int tr = 0;
    for (int i = 0; i < tp; i++) {
        for (int j = 0; j < tris[i][0].length; j++) {
            Tri[tr][0] = tris[i][0][j];
            Tri[tr][1] = tris[i][1][j];
            Tri[tr][2] = tris[i][2][j];
            tr++;
        }
    }

    // build Vertices component
    Vertices = new int[numpts][];
    for (int i = 0; i < numpts; i++) {
        Vertices[i] = new int[nverts[i]];
        nverts[i] = 0;
    }
    int a, b, c;
    for (int i = 0; i < ntris; i++) {
        a = Tri[i][0];
        b = Tri[i][1];
        c = Tri[i][2];
        Vertices[a][nverts[a]++] = i;
        Vertices[b][nverts[b]++] = i;
        Vertices[c][nverts[c]++] = i;
    }

    // call more generic method for constructing Walk and Edges arrays
    finish_triang(samples);
}

From source file:com.alvermont.terraj.planet.project.StereographicProjection.java

/**
 * Carry out the projection/*from  w  w w. j  ava  2  s  . c  o  m*/
 */
public void project() {
    setcolours();

    final int width = getParameters().getProjectionParameters().getWidth();
    final int height = getParameters().getProjectionParameters().getHeight();

    final double lat = getParameters().getProjectionParameters().getLatitudeRadians();
    final double lon = getParameters().getProjectionParameters().getLongitudeRadians();

    final double scale = getParameters().getProjectionParameters().getScale();

    final double hgrid = getParameters().getProjectionParameters().getHgrid();
    final double vgrid = getParameters().getProjectionParameters().getVgrid();

    final boolean doShade = getParameters().getProjectionParameters().isDoShade();

    depth = (3 * ((int) (log2(scale * height)))) + 6;

    cacheParameters();

    colours = new short[width][height];
    shades = new short[width][height];

    double x;
    double y;
    double z;
    double x1;
    double y1;
    double z1;
    double ymin;
    double ymax;
    double theta1;
    double theta2;
    double zz;
    int i;
    int j;

    ymin = 2.0;
    ymax = -2.0;

    final double sla = Math.sin(lat);
    final double cla = Math.cos(lat);
    final double slo = Math.sin(lon);
    final double clo = Math.cos(lon);

    progress.progressStart(height, "Generating Terrain");

    for (j = 0; j < height; ++j) {
        progress.progressStep(j);

        for (i = 0; i < width; ++i) {
            x = ((2.0 * i) - width) / height / scale;
            y = ((2.0 * j) - height) / height / scale;
            z = (x * x) + (y * y);
            zz = 0.25 * (4.0 + z);

            x = x / zz;
            y = y / zz;
            z = (1.0 - (0.25 * z)) / zz;

            x1 = (clo * x) + (slo * sla * y) + (slo * cla * z);
            y1 = (cla * y) - (sla * z);
            z1 = (-slo * x) + (clo * sla * y) + (clo * cla * z);

            if (y1 < ymin) {
                ymin = y1;
            }

            if (y1 > ymax) {
                ymax = y1;
            }

            colours[i][j] = (short) planet0(x1, y1, z1);

            if (doShade) {
                shades[i][j] = shade;
            }
        }
    }

    progress.progressComplete("Terrain Generated");

    if (hgrid != 0.0) {
        /* draw horizontal gridlines */
        for (theta1 = 0.0; theta1 > -90.0; theta1 -= hgrid)
            ;

        for (theta1 = theta1; theta1 < 90.0; theta1 += hgrid) {
            y = Math.sin(Math.toRadians(theta1));

            if ((ymin <= y) && (y <= ymax)) {
                zz = Math.sqrt(1 - (y * y));

                for (theta2 = -Math.PI; theta2 < Math.PI; theta2 += (0.5 / width / scale)) {
                    x = Math.sin(theta2) * zz;
                    z = Math.cos(theta2) * zz;
                    x1 = (clo * x) + (slo * z);
                    y1 = ((slo * sla * x) + (cla * y)) - (clo * sla * z);
                    z1 = (-slo * cla * x) + (sla * y) + (clo * cla * z);

                    if (Math.abs(z1) < 1.0) {
                        i = (int) (0.5
                                * (((height * scale * 2.0 * x1 * (1 + z1)) / (1.0 - (z1 * z1))) + width));
                        j = (int) (0.5
                                * (((height * scale * 2.0 * y1 * (1 + z1)) / (1.0 - (z1 * z1))) + height));

                        if ((0 <= i) && (i < width) && (0 <= j) && (j < height)) {
                            colours[i][j] = BLACK;
                        }
                    }
                }
            }
        }
    }

    if (vgrid != 0.0) {
        /* draw vertical gridlines */
        for (theta2 = -Math.PI; theta2 < Math.PI; theta2 += (0.5 / width / scale)) {
            y = Math.sin(theta2);

            if ((ymin <= y) && (y <= ymax)) {
                for (theta1 = 0.0; theta1 < 360.0; theta1 += vgrid) {
                    x = Math.sin(Math.toRadians(theta1)) * Math.cos(theta2);
                    z = Math.cos(Math.toRadians(theta1)) * Math.cos(theta2);

                    x1 = (clo * x) + (slo * z);
                    y1 = ((slo * sla * x) + (cla * y)) - (clo * sla * z);
                    z1 = (-slo * cla * x) + (sla * y) + (clo * cla * z);

                    if (Math.abs(z1) < 1.0) {
                        i = (int) (0.5 * (((height * scale * 2.0 * x1 * (1 + z1)) / (1 - (z1 * z1))) + width));
                        j = (int) (0.5 * (((height * scale * 2.0 * y1 * (1 + z1)) / (1 - (z1 * z1))) + height));

                        if ((0 <= i) && (i < width) && (0 <= j) && (j < height)) {
                            colours[i][j] = BLACK;
                        }
                    }
                }
            }
        }
    }

    if (doShade) {
        smoothshades();
    }

    doOutlining();
}

From source file:org.jfree.chart.demo.MultiShapesXYDemo.java

/**
 * A demonstration application showing a series with different shape attributes per item.
 *
 * @param title  the frame title.//w  w  w  .j a v a 2s. c o  m
 */
public MultiShapesXYDemo(final String title) {

    super(title);

    System.out.println("About to get images...");
    final URL url1 = getClass().getClassLoader().getResource("org/jfree/chart/demo/redball.png");
    final URL url2 = getClass().getClassLoader().getResource("org/jfree/chart/demo/arrow.png");
    if (url1 != null && url2 != null) {
        this.ballImage = new javax.swing.ImageIcon(url1).getImage();
        this.arrowImage = new javax.swing.ImageIcon(url2).getImage();
        final MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(this.ballImage, 0);
        tracker.addImage(this.arrowImage, 1);
        try {
            tracker.waitForID(0);
            tracker.waitForID(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Images loaded");
    } else {
        System.err.println("Can't find images");
    }
    System.out.println("Images done.");
    this.series = new XYSeries("Some Data");
    for (int i = 0; i < NUMBER_OF_POINTS; i++) {
        final double x = INCREMENT * i;
        final double y = Math.sin(x);
        this.series.add(x, y);
    }
    final XYSeriesCollection data = new XYSeriesCollection(this.series);
    final NumberAxis domainAxis = new NumberAxis("x");
    final NumberAxis rangeAxis = new NumberAxis("sin(x)");
    final DemoRenderer renderer = new DemoRenderer();
    final Plot plot = new XYPlot(data, domainAxis, rangeAxis, renderer);
    final JFreeChart chart = new JFreeChart(plot);
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(600, 380));
    setContentPane(chartPanel);

}

From source file:com.luthfihm.virtualtour.ar.GyroscopeOrientation.java

private void getRotationVectorFromAccelMag() {
    // Assuming the angles are in radians.

    // getOrientation() values:
    // values[0]: azimuth, rotation around the Z axis.
    // values[1]: pitch, rotation around the X axis.
    // values[2]: roll, rotation around the Y axis.

    // Heading, Azimuth, Yaw
    double c1 = Math.cos(vOrientationAccelMag[0] / 2);
    double s1 = Math.sin(vOrientationAccelMag[0] / 2);

    // Pitch, Attitude
    // The equation assumes the pitch is pointed in the opposite direction
    // of the orientation vector provided by Android, so we invert it.
    double c2 = Math.cos(-vOrientationAccelMag[1] / 2);
    double s2 = Math.sin(-vOrientationAccelMag[1] / 2);

    // Roll, Bank
    double c3 = Math.cos(vOrientationAccelMag[2] / 2);
    double s3 = Math.sin(vOrientationAccelMag[2] / 2);

    double c1c2 = c1 * c2;
    double s1s2 = s1 * s2;

    double w = c1c2 * c3 - s1s2 * s3;
    double x = c1c2 * s3 + s1s2 * c3;
    double y = s1 * c2 * c3 + c1 * s2 * s3;
    double z = c1 * s2 * c3 - s1 * c2 * s3;

    // The quaternion in the equation does not share the same coordinate
    // system as the Android gyroscope quaternion we are using. We reorder
    // it here.//from ww  w  .  j  a v  a2 s.  c  o  m

    // Android X (pitch) = Equation Z (pitch)
    // Android Y (roll) = Equation X (roll)
    // Android Z (azimuth) = Equation Y (azimuth)

    qGyroscope = new Quaternion(w, z, x, y);

}

From source file:CircleLayoutTest.java

public void layoutContainer(Container parent) {
    setSizes(parent);//  w w w.  j  a  v a 2  s. com

    // compute center of the circle

    Insets insets = parent.getInsets();
    int containerWidth = parent.getSize().width - insets.left - insets.right;
    int containerHeight = parent.getSize().height - insets.top - insets.bottom;

    int xcenter = insets.left + containerWidth / 2;
    int ycenter = insets.top + containerHeight / 2;

    // compute radius of the circle

    int xradius = (containerWidth - maxComponentWidth) / 2;
    int yradius = (containerHeight - maxComponentHeight) / 2;
    int radius = Math.min(xradius, yradius);

    // lay out components along the circle

    int n = parent.getComponentCount();
    for (int i = 0; i < n; i++) {
        Component c = parent.getComponent(i);
        if (c.isVisible()) {
            double angle = 2 * Math.PI * i / n;

            // center point of component
            int x = xcenter + (int) (Math.cos(angle) * radius);
            int y = ycenter + (int) (Math.sin(angle) * radius);

            // move component so that its center is (x, y)
            // and its size is its preferred size
            Dimension d = c.getPreferredSize();
            c.setBounds(x - d.width / 2, y - d.height / 2, d.width, d.height);
        }
    }
}

From source file:edu.uci.ics.jung.visualization.util.VertexShapeFactory.java

/**
 * Returns a regular <code>num_sides</code>-sided 
 * <code>Polygon</code> whose bounding 
 * box's width and height are defined by this instance's size and
 * aspect ratio functions for this vertex.
 * @param num_sides the number of sides of the polygon; must be >= 3.
 *///w  ww .j av  a  2s .co m
public Shape getRegularPolygon(V v, int num_sides) {
    if (num_sides < 3)
        throw new IllegalArgumentException("Number of sides must be >= 3");
    Rectangle2D frame = getRectangle(v);
    float width = (float) frame.getWidth();
    float height = (float) frame.getHeight();

    // generate coordinates
    double angle = 0;
    thePolygon.reset();
    thePolygon.moveTo(0, 0);
    thePolygon.lineTo(width, 0);
    double theta = (2 * Math.PI) / num_sides;
    for (int i = 2; i < num_sides; i++) {
        angle -= theta;
        float delta_x = (float) (width * Math.cos(angle));
        float delta_y = (float) (width * Math.sin(angle));
        Point2D prev = thePolygon.getCurrentPoint();
        thePolygon.lineTo((float) prev.getX() + delta_x, (float) prev.getY() + delta_y);
    }
    thePolygon.closePath();

    // scale polygon to be right size, translate to center at (0,0)
    Rectangle2D r = thePolygon.getBounds2D();
    double scale_x = width / r.getWidth();
    double scale_y = height / r.getHeight();
    float translationX = (float) (r.getMinX() + r.getWidth() / 2);
    float translationY = (float) (r.getMinY() + r.getHeight() / 2);

    AffineTransform at = AffineTransform.getScaleInstance(scale_x, scale_y);
    at.translate(-translationX, -translationY);

    Shape shape = at.createTransformedShape(thePolygon);
    return shape;
}

From source file:edu.snu.leader.hidden.builder.AbstractIndividualBuilder.java

/**
 * Create a valid location for an individual
 *
 * @param index The index of the individual
 * @return The valid location// ww w. j  a  v a 2 s .c  o m
 */
protected Vector2D createValidLocation(int index) {
    Vector2D location = null;

    // If we have a location, use it
    if (index < _locations.size()) {
        location = _locations.get(index);
    }
    // Otherwise, generate it
    else {
        // Generate a radius
        float radius = _simState.getRandom().nextFloat() * _maxRadius;

        // Generate an angle
        double angle = (_simState.getRandom().nextDouble() * Math.PI * 2.0) - Math.PI;

        // Convert to cartesian
        float x = radius * (float) Math.cos(angle);
        float y = radius * (float) Math.sin(angle);

        location = new Vector2D(x, y);
    }

    return location;
}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;//w w  w.j av a2 s . c o  m
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}