Example usage for java.lang Math signum

List of usage examples for java.lang Math signum

Introduction

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

Prototype

public static float signum(float f) 

Source Link

Document

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

Usage

From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java

/**
* The vomma (aka volga) of an option, i.e. second order derivative of the option spot price with respect to the implied volatility.
* @param spot The spot value of the underlying
* @param strike The Strike//w  w  w .jav a2  s .  c o  m
* @param timeToExpiry The time-to-expiry
* @param lognormalVol The log-normal volatility
* @param interestRate The interest rate 
* @param costOfCarry The cost-of-carry  rate
* @return The spot vomma
*/
@ExternalFunction
public static double vomma(final double spot, final double strike, final double timeToExpiry,
        final double lognormalVol, final double interestRate, final double costOfCarry) {
    ArgumentChecker.isTrue(spot >= 0.0, "negative/NaN spot; have {}", spot);
    ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);
    ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN");
    ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN");

    final double rootT = Math.sqrt(timeToExpiry);
    double sigmaRootT = lognormalVol * rootT;
    if (Double.isNaN(sigmaRootT)) {
        sigmaRootT = 1.; //ref value is returned
    }

    if (spot > LARGE * strike || strike > LARGE * spot || rootT < SMALL) {
        return 0.;
    }

    double d1 = 0.;
    double d1d2Mod = 0.;
    if (Math.abs(spot - strike) < SMALL || (spot > LARGE && strike > LARGE) || rootT > LARGE) {
        final double costOvVol = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL)
                ? Math.signum(costOfCarry)
                : costOfCarry / lognormalVol;
        final double coefD1 = costOvVol + 0.5 * lognormalVol;
        final double coefD1D2Mod = costOvVol * costOvVol / lognormalVol - 0.25 * lognormalVol;
        final double tmpD1 = coefD1 * rootT;
        final double tmpD1d2Mod = coefD1D2Mod * rootT * timeToExpiry;
        d1 = Double.isNaN(tmpD1) ? 0. : tmpD1;
        d1d2Mod = Double.isNaN(tmpD1d2Mod) ? 1. : tmpD1d2Mod;
    } else {
        if (lognormalVol > LARGE) {
            d1 = 0.5 * sigmaRootT;
            d1d2Mod = -0.25 * sigmaRootT * timeToExpiry;
        } else {
            if (lognormalVol < SMALL) {
                final double d1Tmp = (Math.log(spot / strike) / rootT + costOfCarry * rootT) / lognormalVol;
                d1 = Double.isNaN(d1Tmp) ? 1. : d1Tmp;
                d1d2Mod = d1 * d1 * rootT / lognormalVol;
            } else {
                final double tmp = Math.log(spot / strike) / sigmaRootT + costOfCarry * rootT / lognormalVol;
                d1 = tmp + 0.5 * sigmaRootT;
                d1d2Mod = (tmp * tmp - 0.25 * sigmaRootT * sigmaRootT) * rootT / lognormalVol;
            }
        }
    }
    //    if (Double.isNaN(d1) || Double.isNaN(d1d2Mod)) {
    //      throw new IllegalArgumentException("NaN found");
    //    }

    double coef = 0.;
    if ((interestRate > LARGE && costOfCarry > LARGE) || (-interestRate > LARGE && -costOfCarry > LARGE)
            || Math.abs(costOfCarry - interestRate) < SMALL) {
        coef = 1.; //ref value is returned
    } else {
        final double rate = costOfCarry - interestRate;
        if (rate > LARGE) {
            return costOfCarry > LARGE ? 0.
                    : (d1d2Mod >= 0. ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY);
        }
        if (-rate > LARGE) {
            return 0.;
        }
        coef = Math.exp(rate * timeToExpiry);
    }

    final double norm = NORMAL.getPDF(d1);
    double tmp = d1d2Mod * spot * coef;
    if (Double.isNaN(tmp)) {
        tmp = coef;
    }

    return norm < SMALL ? 0. : norm * tmp;
}

From source file:geogebra.common.kernel.implicit.GeoImplicitPoly.java

private void startPath(int width, int height, double x, double y, GeoLocus loc1) {
    int w = width;
    int h = height;
    double sx = x;
    double sy = y;
    double lx = Double.NaN; //no previous point
    double ly = Double.NaN;
    boolean first = true;

    double stepSize = START_STEP_SIZE * Math.max(scaleX, scaleY);
    double startX = x;
    double startY = y;

    ArrayList<MyPoint> firstDirPoints = new ArrayList<MyPoint>();
    firstDirPoints.add(new MyPoint(x, y, true));

    int s = 0;//from ww  w . j av a 2  s  .c  o  m
    int lastW = w;
    int lastH = h;
    int startW = w;
    int startH = h;

    boolean nearSing = false;
    double lastGradX = Double.POSITIVE_INFINITY;
    double lastGradY = Double.POSITIVE_INFINITY;
    while (s < MAX_STEPS) {
        s++;
        boolean reachedSingularity = false;
        boolean reachedEnd = false;
        if (!Double.isNaN(lx) && !Double.isNaN(ly)) {
            if ((scaledNormSquared(startX - sx, startY - sy) < MAX_STEP_SIZE * MAX_STEP_SIZE)
                    && (scaledNormSquared(startX - sx, startY - sy) < scaledNormSquared(startX - lx,
                            startY - ly))) {
                /* loop found */
                if (firstDirPoints != null) {

                    MyPoint firstPoint = firstDirPoints.get(0);
                    firstPoint.lineTo = false;
                    loc1.getPoints().addAll(firstDirPoints);
                }
                loc1.insertPoint(x, y, true);
                return;
            }
        }
        if (w > grid.length || h > grid[w].length || grid[w][h] == null) {
            if (w > grid.length || h > grid[w].length) {
                App.printStacktrace("GRID" + grid.length + "," + w + "," + h);
            } else {
                App.printStacktrace(
                        "GRID NULL" + grid.length + "," + w + "," + h + "," + gridWidth + "," + gridHeight);
            }
        }
        while (sx < grid[w][h].x) {
            if (w > 0)
                w--;
            else {
                reachedEnd = true;
                break;
            }
        }
        while (sx > grid[w][h].x + grid[w][h].width) {
            if (w < grid.length - 1)
                w++;
            else {
                reachedEnd = true;
                break;
            }
        }
        while (sy < grid[w][h].y) {
            if (h > 0)
                h--;
            else {
                reachedEnd = true;
                break;
            }
        }
        while (sy > grid[w][h].y + grid[w][h].height) {
            if (h < grid[w].length - 1)
                h++;
            else {
                reachedEnd = true;
                break;
            }
        }
        if (reachedEnd) { //we reached the boundary
            boundaryIntersectCollection.add(new double[] { sx, sy });
        }
        if (lastW != w || lastH != h) {
            int dw = (int) Math.signum(lastW - w);
            int dh = (int) Math.signum(lastH - h);
            for (int i = 0; i <= Math.abs(lastW - w); i++) {
                for (int j = 0; j <= Math.abs(lastH - h); j++) {
                    remember[lastW - dw * i][lastH - dh * j] = false;
                }
            }
        }
        lastW = w;
        lastH = h;

        double gradX = 0;
        double gradY = 0;
        if (!reachedEnd) {
            gradX = evalDiffXPolyAt(sx, sy, true);
            gradY = evalDiffYPolyAt(sx, sy, true);

            /*
             * Dealing with singularities: tries to reach the singularity but stops there.
             * Assuming that the singularity is on or at least near the curve. (Since first
             * derivative is zero this can be assumed for 'nice' 2nd derivative)
             */

            if (nearSing || (Math.abs(gradX) < NEAR_SING && Math.abs(gradY) < NEAR_SING)) {
                for (double[] pair : singularitiesCollection) { //check if this singularity is already known
                    if ((scaledNormSquared(pair[0] - sx, pair[1] - sy) < SING_RADIUS * SING_RADIUS)) {
                        sx = pair[0];
                        sy = pair[1];
                        reachedSingularity = true;
                        reachedEnd = true;
                        break;
                    }
                }
                if (!reachedEnd) {
                    if (gradX * gradX + gradY * gradY > lastGradX * lastGradX + lastGradY * lastGradY) { //going away from the singularity, stop here
                        singularitiesCollection.add(new double[] { sx, sy });
                        reachedEnd = true;
                        reachedSingularity = true;
                    } else if (Math.abs(gradX) < MIN_GRAD && Math.abs(gradY) < MIN_GRAD) { //singularity
                        singularitiesCollection.add(new double[] { sx, sy });
                        reachedEnd = true;
                        reachedSingularity = true;
                    }
                    lastGradX = gradX;
                    lastGradY = gradY;
                    nearSing = true;
                }
            }
        }
        double a = 0, nX = 0, nY = 0;
        if (!reachedEnd) {
            a = 1 / (Math.abs(gradX) + Math.abs(gradY)); //trying to increase numerical stability
            gradX = a * gradX;
            gradY = a * gradY;
            a = Math.sqrt(gradX * gradX + gradY * gradY);
            gradX = gradX / a; //scale vector
            gradY = gradY / a;
            nX = -gradY;
            nY = gradX;
            if (!Double.isNaN(lx) && !Double.isNaN(ly)) {
                double c = (lx - sx) * nX + (ly - sy) * nY;
                if (c > 0) {
                    nX = -nX;
                    nY = -nY;
                }
            } else {
                if (!first) { //other dir now
                    nX = -nX;
                    nY -= nY;
                }
            }
            lx = sx;
            ly = sy;
        }
        while (!reachedEnd) {
            sx = lx + nX * stepSize; //go in "best" direction
            sy = ly + nY * stepSize;
            int e = epsSignum(evalPolyAt(sx, sy, true));
            if (e == 0) {
                if (stepSize * 2 <= MAX_STEP_SIZE * Math.max(scaleX, scaleY))
                    stepSize *= 2;
                break;
            }
            gradX = evalDiffXPolyAt(sx, sy, true);
            gradY = evalDiffYPolyAt(sx, sy, true);
            if (Math.abs(gradX) < MIN_GRAD && Math.abs(gradY) < MIN_GRAD) { //singularity
                stepSize /= 2;
                if (stepSize > MIN_STEP_SIZE * Math.max(scaleX, scaleY))
                    continue;
                singularitiesCollection.add(new double[] { sx, sy });
                reachedEnd = true;
                break;
            }
            a = Math.sqrt(gradX * gradX + gradY * gradY);
            gradX *= stepSize / a;
            gradY *= stepSize / a;
            if (e > 0) {
                gradX = -gradX;
                gradY = -gradY;
            }
            int e1 = epsSignum(evalPolyAt(sx + gradX, sy + gradY, true));
            if (e1 == 0) {
                sx = sx + gradX;
                sy = sy + gradY;
                break;
            }
            if (e1 != e) {
                a = bisec(sx, sy, sx + gradX, sy + gradY);
                sx += a * gradX;
                sy += a * gradY;
                break;
            }
            stepSize /= 2;
            if (stepSize > MIN_STEP_SIZE * Math.max(scaleX, scaleY))
                continue;
            reachedEnd = true;
            break;
        }
        if (!reachedEnd || reachedSingularity) {
            if (reachedSingularity || ((lx - sx) * (lx - sx) + (ly - sy) * (ly - sy) > minGap * minGap)) {
                if (firstDirPoints != null) {
                    firstDirPoints.add(new MyPoint(sx, sy, true));
                } else {
                    loc1.insertPoint(sx, sy, true);
                }
            }
        }
        if (reachedEnd) {
            if (!first) {
                return; //reached the end two times
            }
            lastGradX = Double.POSITIVE_INFINITY;
            lastGradY = Double.POSITIVE_INFINITY;

            /* we reached end for the first time and now save the points into the locus */
            ArrayList<MyPoint> pointList = loc1.getPoints();
            if (firstDirPoints.size() > 0) {
                MyPoint lastPoint = firstDirPoints.get(firstDirPoints.size() - 1);
                lastPoint.lineTo = false;
                pointList.ensureCapacity(pointList.size() + firstDirPoints.size());
                for (int i = firstDirPoints.size() - 1; i >= 0; i--) {
                    pointList.add(firstDirPoints.get(i));
                }
            }
            firstDirPoints = null;
            sx = startX;
            sy = startY;
            lx = Double.NaN;
            ly = Double.NaN;
            w = startW;
            h = startH;
            lastW = w;
            lastH = h;
            first = false;//start again with other direction
            reachedEnd = false;
            reachedSingularity = false;
            nearSing = false;
        }
    }
}

From source file:edu.cmu.tetrad.search.Lofs2.java

private double[] correctSkews(double[] data) {
    double skewness = StatUtils.skewness(data);
    double[] data2 = new double[data.length];
    for (int i = 0; i < data.length; i++)
        data2[i] = data[i] * Math.signum(skewness);
    return data2;
}

From source file:edu.cmu.tetrad.search.Lofs2.java

private List<double[]> prepareData(DataSet concatData, Node _x, Node _y, boolean skewCorrection,
        boolean coefCorrection) {
    int xIndex = concatData.getColumn(_x);
    int yIndex = concatData.getColumn(_y);

    double[] xData = concatData.getDoubleData().getColumn(xIndex).toArray();
    double[] yData = concatData.getDoubleData().getColumn(yIndex).toArray();

    List<Double> xValues = new ArrayList<Double>();
    List<Double> yValues = new ArrayList<Double>();

    for (int i = 0; i < concatData.getNumRows(); i++) {
        if (!Double.isNaN(xData[i]) && !Double.isNaN(yData[i])) {
            xValues.add(xData[i]);/*from ww  w. j  ava 2 s.  c o m*/
            yValues.add(yData[i]);
        }
    }

    xData = new double[xValues.size()];
    yData = new double[yValues.size()];

    for (int i = 0; i < xValues.size(); i++) {
        xData[i] = xValues.get(i);
        yData[i] = yValues.get(i);
    }

    if (skewCorrection) {
        double xSkew = StatUtils.skewness(xData);
        double ySkew = StatUtils.skewness(yData);

        for (int i = 0; i < xData.length; i++)
            xData[i] *= Math.signum(xSkew);
        for (int i = 0; i < yData.length; i++)
            yData[i] *= Math.signum(ySkew);
    }

    if (coefCorrection) {
        double coefX;
        try {
            coefX = regressionCoef(xData, yData);
        } catch (Exception e) {
            coefX = Double.NaN;
        }

        double coefY;

        try {
            coefY = regressionCoef(yData, xData);
        } catch (Exception e) {
            coefY = Double.NaN;
        }

        for (int i = 0; i < xData.length; i++)
            xData[i] *= Math.signum(coefX);
        for (int i = 0; i < yData.length; i++)
            yData[i] *= Math.signum(coefY);

    }

    List<double[]> ret = new ArrayList<double[]>();
    ret.add(xData);
    ret.add(yData);

    return ret;
}

From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java

/**
* The vega bleed of an option, i.e. second order derivative of the option spot price, once to the volatility and once to the time.
* @param spot The spot value of the underlying
* @param strike The Strike// w  ww  . ja  va  2  s  . c  o  m
* @param timeToExpiry The time-to-expiry
* @param lognormalVol The log-normal volatility
* @param interestRate The interest rate 
* @param costOfCarry The cost-of-carry  rate
* @return The spot vomma
*/
@ExternalFunction
public static double vegaBleed(final double spot, final double strike, final double timeToExpiry,
        final double lognormalVol, final double interestRate, final double costOfCarry) {
    ArgumentChecker.isTrue(spot >= 0.0, "negative/NaN spot; have {}", spot);
    ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);
    ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN");
    ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN");

    final double rootT = Math.sqrt(timeToExpiry);
    double sigmaRootT = lognormalVol * rootT;
    if (Double.isNaN(sigmaRootT)) {
        sigmaRootT = 1.; //ref value is returned
    }
    if (spot > LARGE * strike || strike > LARGE * spot || rootT < SMALL) {
        return 0.;
    }

    double d1 = 0.;
    double extra = 0.;
    if (Math.abs(spot - strike) < SMALL || (spot > LARGE && strike > LARGE) || rootT > LARGE) {
        final double costOvVol = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL)
                ? Math.signum(costOfCarry)
                : costOfCarry / lognormalVol;
        final double coefD1 = costOvVol + 0.5 * lognormalVol;
        final double tmpD1 = coefD1 * rootT;
        d1 = Double.isNaN(tmpD1) ? 0. : tmpD1;
        final double coefExtra = interestRate - 0.5 * costOfCarry + 0.5 * costOvVol * costOvVol
                + 0.125 * lognormalVol * lognormalVol;
        final double tmpExtra = Double.isNaN(coefExtra) ? rootT : coefExtra * rootT;
        extra = Double.isNaN(tmpExtra) ? 1. - 0.5 / rootT : tmpExtra - 0.5 / rootT;
    } else {
        if (lognormalVol > LARGE) {
            d1 = 0.5 * sigmaRootT;
            extra = 0.125 * lognormalVol * sigmaRootT;
        } else {
            if (lognormalVol < SMALL) {
                final double resLogRatio = Math.log(spot / strike) / rootT;
                final double d1Tmp = (resLogRatio + costOfCarry * rootT) / lognormalVol;
                d1 = Double.isNaN(d1Tmp) ? 1. : d1Tmp;
                final double tmpExtra = (-0.5 * resLogRatio * resLogRatio / rootT
                        + 0.5 * costOfCarry * costOfCarry * rootT) / lognormalVol / lognormalVol;
                extra = Double.isNaN(tmpExtra) ? 1. : extra;
            } else {
                final double resLogRatio = Math.log(spot / strike) / sigmaRootT;
                final double tmp = resLogRatio + costOfCarry * rootT / lognormalVol;
                d1 = tmp + 0.5 * sigmaRootT;
                double pDivTmp = interestRate
                        - 0.5 * costOfCarry * (1. - costOfCarry / lognormalVol / lognormalVol);
                double pDiv = Double.isNaN(pDivTmp) ? rootT : pDivTmp * rootT;
                extra = pDiv - 0.5 / rootT - 0.5 * resLogRatio * resLogRatio / rootT
                        + 0.125 * lognormalVol * sigmaRootT;
            }
        }
    }
    //    if (Double.isNaN(d1) || Double.isNaN(extra)) {
    //      throw new IllegalArgumentException("NaN found");
    //    }
    double coef = 0.;
    if ((interestRate > LARGE && costOfCarry > LARGE) || (-interestRate > LARGE && -costOfCarry > LARGE)
            || Math.abs(costOfCarry - interestRate) < SMALL) {
        coef = 1.; //ref value is returned
    } else {
        final double rate = costOfCarry - interestRate;
        if (rate > LARGE) {
            return costOfCarry > LARGE ? 0.
                    : (extra >= 0. ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY);
        }
        if (-rate > LARGE) {
            return 0.;
        }
        coef = Math.exp(rate * timeToExpiry);
    }

    final double norm = NORMAL.getPDF(d1);
    double tmp = spot * coef * extra;
    if (Double.isNaN(tmp)) {
        tmp = coef;
    }

    return norm < SMALL ? 0. : tmp * norm;
}

From source file:org.videolan.vlc.gui.video.VideoPlayerActivity.java

/**
 * show/hide the overlay//from   ww  w .ja  v  a 2s.  c  o  m
 */

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (mIsLocked) {
//            showOverlay();
//            return false;
//        }
//        
//        DisplayMetrics screen = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(screen);
//
//        if (mSurfaceYDisplayRange == 0)
//            mSurfaceYDisplayRange = Math.min(screen.widthPixels, screen.heightPixels);
//
//        float y_changed = event.getRawY() - mTouchY;
//        float x_changed = event.getRawX() - mTouchX;
//
//        // coef is the gradient's move to determine a neutral zone
//        float coef = Math.abs (y_changed / x_changed);
//        float xgesturesize = ((x_changed / screen.xdpi) * 2.54f);
//
//        switch (event.getAction()) {
//
//        case MotionEvent.ACTION_DOWN:
//            // Audio
//            mTouchY = event.getRawY();
//            mVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//            mIsAudioOrBrightnessChanged = false;
//            // Seek
//            mTouchX = event.getRawX();
//            break;
//
//        case MotionEvent.ACTION_MOVE:
//            // No volume/brightness action if coef < 2
//            if (coef > 2) {
//                // Volume (Up or Down - Right side)
//                if (!mEnableBrightnessGesture || mTouchX > (screen.widthPixels / 2)){
//                    doVolumeTouch(y_changed);
//                }
//                // Brightness (Up or Down - Left side)
//                if (mEnableBrightnessGesture && mTouchX < (screen.widthPixels / 2)){
//                    doBrightnessTouch(y_changed);
//                }
//                // Extend the overlay for a little while, so that it doesn't
//                // disappear on the user if more adjustment is needed. This
//                // is because on devices with soft navigation (e.g. Galaxy
//                // Nexus), gestures can't be made without activating the UI.
//                if(Util.hasNavBar())
//                    showOverlay();
//            }
//            // Seek (Right or Left move)
//            doSeekTouch(coef, xgesturesize, false);
//            break;
//
//        case MotionEvent.ACTION_UP:
//            // Audio or Brightness
//            if (!mIsAudioOrBrightnessChanged) {
//                if (!mShowing) {
//                    showOverlay();
//                } else {
//                    hideOverlay(true);
//                }
//            }
//            // Seek
//            doSeekTouch(coef, xgesturesize, true);
//            break;
//        }
//        return mIsAudioOrBrightnessChanged;
//    }

private void doSeekTouch(float coef, float gesturesize, boolean seek) {
    // No seek action if coef > 0.5 and gesturesize < 1cm
    if (mEnableWheelbar || coef > 0.5 || Math.abs(gesturesize) < 1)
        return;

    // Always show seekbar when searching
    if (!mShowing)
        showOverlay();

    long length = mLibVLC.getLength();
    long time = mLibVLC.getTime();

    // Size of the jump, 10 minutes max (600000), with a bi-cubic progression, for a 8cm gesture
    int jump = (int) (Math.signum(gesturesize) * ((600000 * Math.pow((gesturesize / 8), 4)) + 3000));

    // Adjust the jump
    if ((jump > 0) && ((time + jump) > length))
        jump = (int) (length - time);
    if ((jump < 0) && ((time + jump) < 0))
        jump = (int) -time;

    //Jump !
    if (seek)
        mPlayerControlListener.onSeekTo(time + jump);

    //Show the jump's size
    showInfo(String.format("%s%s (%s)", jump >= 0 ? "+" : "", Util.millisToString(jump),
            Util.millisToString(time + jump)), 1000);
}

From source file:org.micromanager.asidispim.AcquisitionPanel.java

private int updateGridXCount() {
    double range = ((Double) gridXStartField_.getValue()) - ((Double) gridXStopField_.getValue());
    double delta = ((Double) gridXDeltaField_.getValue());
    if (Math.signum(range) != Math.signum(delta)) {
        delta *= -1;//from  www  .j  ava2 s  . c  o m
        gridXDeltaField_.setValue(delta);
    }
    Integer count = (Integer) ((int) Math.ceil(range / delta)) + 1;
    gridXCount_.setText(count.toString());
    return count;
}

From source file:org.micromanager.asidispim.AcquisitionPanel.java

private int updateGridYCount() {
    double range = ((Double) gridYStartField_.getValue()) - ((Double) gridYStopField_.getValue());
    double delta = ((Double) gridYDeltaField_.getValue());
    if (Math.signum(range) != Math.signum(delta)) {
        delta *= -1;//from   w w  w  . j  a  v  a 2s.c  o m
        gridYDeltaField_.setValue(delta);
    }
    Integer count = (Integer) ((int) Math.ceil(range / delta)) + 1;
    gridYCount_.setText(count.toString());
    return count;
}

From source file:org.micromanager.asidispim.AcquisitionPanel.java

private int updateGridZCount() {
    double range = ((Double) gridZStartField_.getValue()) - ((Double) gridZStopField_.getValue());
    double delta = ((Double) gridZDeltaField_.getValue());
    if (Math.signum(range) != Math.signum(delta)) {
        delta *= -1;/*from ww  w  .  j a va 2s.c  o m*/
        gridZDeltaField_.setValue(delta);
    }
    Integer count = (Integer) ((int) Math.ceil(range / delta)) + 1;
    gridZCount_.setText(count.toString());
    return count;
}

From source file:blusunrize.immersiveengineering.client.ClientEventHandler.java

@SubscribeEvent()
public void renderAdditionalBlockBounds(DrawBlockHighlightEvent event) {
    if (event.getSubID() == 0 && event.getTarget().typeOfHit == Type.BLOCK) {
        float f1 = 0.002F;
        double px = -TileEntityRendererDispatcher.staticPlayerX;
        double py = -TileEntityRendererDispatcher.staticPlayerY;
        double pz = -TileEntityRendererDispatcher.staticPlayerZ;
        TileEntity tile = event.getPlayer().world.getTileEntity(event.getTarget().getBlockPos());
        ItemStack stack = event.getPlayer().getHeldItem(EnumHand.MAIN_HAND);
        //         if(event.getPlayer().world.getBlockState(event.getTarget().getBlockPos()).getBlock() instanceof IEBlockInterfaces.ICustomBoundingboxes)
        if (tile instanceof IAdvancedSelectionBounds) {
            //            IEBlockInterfaces.ICustomBoundingboxes block = (IEBlockInterfaces.ICustomBoundingboxes) event.getPlayer().world.getBlockState(event.getTarget().getBlockPos()).getBlock();
            IAdvancedSelectionBounds iasb = (IAdvancedSelectionBounds) tile;
            List<AxisAlignedBB> boxes = iasb.getAdvancedSelectionBounds();
            if (boxes != null && !boxes.isEmpty()) {
                GlStateManager.enableBlend();
                GlStateManager.tryBlendFuncSeparate(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA,
                        SourceFactor.ONE, DestFactor.ZERO);
                GlStateManager.glLineWidth(2.0F);
                GlStateManager.disableTexture2D();
                GlStateManager.depthMask(false);
                ArrayList<AxisAlignedBB> additionalBoxes = new ArrayList<AxisAlignedBB>();
                AxisAlignedBB overrideBox = null;
                for (AxisAlignedBB aabb : boxes)
                    if (aabb != null) {
                        if (iasb.isOverrideBox(aabb, event.getPlayer(), event.getTarget(), additionalBoxes))
                            overrideBox = aabb;
                    }/*from w  ww  .  ja  v  a  2 s.com*/

                if (overrideBox != null)
                    RenderGlobal.drawSelectionBoundingBox(overrideBox.grow(f1).offset(px, py, pz), 0, 0, 0,
                            0.4f);
                else
                    for (AxisAlignedBB aabb : additionalBoxes.isEmpty() ? boxes : additionalBoxes)
                        RenderGlobal.drawSelectionBoundingBox(aabb.grow(f1).offset(px, py, pz), 0, 0, 0, 0.4f);
                GlStateManager.depthMask(true);
                GlStateManager.enableTexture2D();
                GlStateManager.disableBlend();
                event.setCanceled(true);
            }
        }

        if (Utils.isHammer(stack) && tile instanceof TileEntityTurntable) {
            BlockPos pos = event.getTarget().getBlockPos();

            GlStateManager.enableBlend();
            GlStateManager.tryBlendFuncSeparate(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA,
                    SourceFactor.ONE, DestFactor.ZERO);
            GlStateManager.glLineWidth(2.0F);
            GlStateManager.disableTexture2D();
            GlStateManager.depthMask(false);

            Tessellator tessellator = Tessellator.getInstance();
            BufferBuilder BufferBuilder = tessellator.getBuffer();

            EnumFacing f = ((TileEntityTurntable) tile).getFacing();
            double tx = pos.getX() + .5;
            double ty = pos.getY() + .5;
            double tz = pos.getZ() + .5;
            if (!event.getPlayer().world.isAirBlock(pos.offset(f))) {
                tx += f.getXOffset();
                ty += f.getYOffset();
                tz += f.getZOffset();
            }
            BufferBuilder.setTranslation(tx + px, ty + py, tz + pz);

            double angle = -event.getPlayer().ticksExisted % 80 / 40d * Math.PI;
            drawRotationArrows(tessellator, BufferBuilder, f, angle, ((TileEntityTurntable) tile).invert);

            BufferBuilder.setTranslation(0, 0, 0);

            GlStateManager.depthMask(true);
            GlStateManager.enableTexture2D();
            GlStateManager.disableBlend();
        }

        World world = event.getPlayer().world;
        if (!stack.isEmpty() && IEContent.blockConveyor.equals(Block.getBlockFromItem(stack.getItem()))
                && event.getTarget().sideHit.getAxis() == Axis.Y) {
            EnumFacing side = event.getTarget().sideHit;
            BlockPos pos = event.getTarget().getBlockPos();
            AxisAlignedBB targetedBB = world.getBlockState(pos).getSelectedBoundingBox(world, pos);
            if (targetedBB != null)
                targetedBB = targetedBB.offset(-pos.getX(), -pos.getY(), -pos.getZ());
            GlStateManager.enableBlend();
            GlStateManager.tryBlendFuncSeparate(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA,
                    SourceFactor.ONE, DestFactor.ZERO);
            GlStateManager.glLineWidth(2.0F);
            GlStateManager.disableTexture2D();
            GlStateManager.depthMask(false);

            Tessellator tessellator = Tessellator.getInstance();
            BufferBuilder BufferBuilder = tessellator.getBuffer();
            BufferBuilder.setTranslation(pos.getX() + px, pos.getY() + py, pos.getZ() + pz);
            double[][] points = new double[4][];

            if (side.getAxis() == Axis.Y) {
                points[0] = new double[] { 0 - f1,
                        side == EnumFacing.DOWN ? ((targetedBB != null ? targetedBB.minY : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxY : 1) + f1),
                        0 - f1 };
                points[1] = new double[] { 1 + f1,
                        side == EnumFacing.DOWN ? ((targetedBB != null ? targetedBB.minY : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxY : 1) + f1),
                        1 + f1 };
                points[2] = new double[] { 0 - f1,
                        side == EnumFacing.DOWN ? ((targetedBB != null ? targetedBB.minY : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxY : 1) + f1),
                        1 + f1 };
                points[3] = new double[] { 1 + f1,
                        side == EnumFacing.DOWN ? ((targetedBB != null ? targetedBB.minY : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxY : 1) + f1),
                        0 - f1 };
            } else if (side.getAxis() == Axis.Z) {
                points[0] = new double[] { 1 + f1, 1 + f1,
                        side == EnumFacing.NORTH ? ((targetedBB != null ? targetedBB.minZ : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxZ : 1) + f1) };
                points[1] = new double[] { 0 - f1, 0 - f1,
                        side == EnumFacing.NORTH ? ((targetedBB != null ? targetedBB.minZ : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxZ : 1) + f1) };
                points[2] = new double[] { 0 - f1, 1 + f1,
                        side == EnumFacing.NORTH ? ((targetedBB != null ? targetedBB.minZ : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxZ : 1) + f1) };
                points[3] = new double[] { 1 + f1, 0 - f1,
                        side == EnumFacing.NORTH ? ((targetedBB != null ? targetedBB.minZ : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxZ : 1) + f1) };
            } else {
                points[0] = new double[] {
                        side == EnumFacing.WEST ? ((targetedBB != null ? targetedBB.minX : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxX : 1) + f1),
                        1 + f1, 1 + f1 };
                points[1] = new double[] {
                        side == EnumFacing.WEST ? ((targetedBB != null ? targetedBB.minX : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxX : 1) + f1),
                        0 - f1, 0 - f1 };
                points[2] = new double[] {
                        side == EnumFacing.WEST ? ((targetedBB != null ? targetedBB.minX : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxX : 1) + f1),
                        1 + f1, 0 - f1 };
                points[3] = new double[] {
                        side == EnumFacing.WEST ? ((targetedBB != null ? targetedBB.minX : 0) - f1)
                                : ((targetedBB != null ? targetedBB.maxX : 1) + f1),
                        0 - f1, 1 + f1 };
            }
            BufferBuilder.begin(1, DefaultVertexFormats.POSITION_COLOR);
            for (double[] point : points)
                BufferBuilder.pos(point[0], point[1], point[2]).color(0, 0, 0, 0.4F).endVertex();
            tessellator.draw();

            BufferBuilder.begin(2, DefaultVertexFormats.POSITION_COLOR);
            BufferBuilder.pos(points[0][0], points[0][1], points[0][2]).color(0, 0, 0, 0.4F).endVertex();
            BufferBuilder.pos(points[2][0], points[2][1], points[2][2]).color(0, 0, 0, 0.4F).endVertex();
            BufferBuilder.pos(points[1][0], points[1][1], points[1][2]).color(0, 0, 0, 0.4F).endVertex();
            BufferBuilder.pos(points[3][0], points[3][1], points[3][2]).color(0, 0, 0, 0.4F).endVertex();
            tessellator.draw();

            float xFromMid = side.getAxis() == Axis.X ? 0
                    : (float) event.getTarget().hitVec.x - pos.getX() - .5f;
            float yFromMid = side.getAxis() == Axis.Y ? 0
                    : (float) event.getTarget().hitVec.y - pos.getY() - .5f;
            float zFromMid = side.getAxis() == Axis.Z ? 0
                    : (float) event.getTarget().hitVec.z - pos.getZ() - .5f;
            float max = Math.max(Math.abs(yFromMid), Math.max(Math.abs(xFromMid), Math.abs(zFromMid)));
            Vec3d dir = new Vec3d(max == Math.abs(xFromMid) ? Math.signum(xFromMid) : 0,
                    max == Math.abs(yFromMid) ? Math.signum(yFromMid) : 0,
                    max == Math.abs(zFromMid) ? Math.signum(zFromMid) : 0);
            if (dir != null)
                drawBlockOverlayArrow(tessellator, BufferBuilder, dir, side, targetedBB);
            BufferBuilder.setTranslation(0, 0, 0);

            GlStateManager.depthMask(true);
            GlStateManager.enableTexture2D();
            GlStateManager.disableBlend();
        }

        if (!stack.isEmpty() && stack.getItem() instanceof ItemDrill && ((ItemDrill) stack.getItem())
                .isEffective(world.getBlockState(event.getTarget().getBlockPos()).getMaterial())) {
            ItemStack head = ((ItemDrill) stack.getItem()).getHead(stack);
            if (!head.isEmpty()) {
                ImmutableList<BlockPos> blocks = ((IDrillHead) head.getItem()).getExtraBlocksDug(head, world,
                        event.getPlayer(), event.getTarget());
                drawAdditionalBlockbreak(event.getContext(), event.getPlayer(), event.getPartialTicks(),
                        blocks);
            }
        }
    }
}