Ejemplo n.º 1
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
Ejemplo n.º 2
0
    private void populate() {
      // set up for a new population
      Vector oldPop = this.positions;
      this.positions = new Vector(50, 50);

      // first browse the old population and make changes
      for (int i = 0; i < oldPop.size(); i++) {
        Position a = (Position) oldPop.get(i);
        if (a.symPosNo < this.symPos.length) {
          Point3d sPos = this.symPos[a.symPosNo];
          if (sPos != null) {
            Point3d newPos = new Point3d(sPos);
            newPos.add(a.expandTranslation);
            if (this.isPosInBounds(newPos)
                && Model3d.this.getAtomHere(this.positions, newPos) == null) {
              a.changePos(newPos);
              this.positions.add(a);
              // System.out.println("move "+a);
              continue;
            }
          }
        }
        // invalid, duplicate or out of bounds, remove
        // System.out.println("del "+a);
        a.del();
      }

      // now add potentially new appeared atoms
      for (double i = -Math.ceil(Model3d.this.exm - 1);
          i <= Math.floor(Model3d.this.exp + 1) + 1;
          i++)
        for (double j = -Math.ceil(Model3d.this.eym - 1);
            j <= Math.floor(Model3d.this.eyp + 1) + 1;
            j++)
          for (double k = -Math.ceil(Model3d.this.ezm - 1);
              k <= Math.floor(Model3d.this.ezp + 1) + 1;
              k++) {
            Vector3d v = new Vector3d(i, j, k);
            for (int l = 0; l < this.symPos.length; l++) {
              if (this.symPos[l] == null) continue;
              Point3d p = new Point3d(this.symPos[l]);
              p.add(v);
              // TODO
              if (this.isPosInBounds(p) && Model3d.this.getAtomHere(this.positions, p) == null) {
                // if (isPosInBounds(round(p)) &&
                // getAtomHere(positions, p)==null) {
                Position a =
                    new Position(this.root, this, p, v, this.radius, this.color, l, !this.hidden);
                this.positions.add(a);
                // if (!isPosInBounds(p))System.out.println("xx
                // "+p);
              }
            }
          }
    }
Ejemplo n.º 3
0
  public void setImage(BufferedImage image, String format) {
    ImageDocument document = imageComponent.getDocument();
    BufferedImage previousImage = document.getValue();
    document.setValue(image);
    if (image == null) return;
    document.setFormat(format);
    ImageZoomModel zoomModel = getZoomModel();
    if (previousImage == null || !zoomModel.isZoomLevelChanged()) {
      // Set smart zooming behaviour on open
      Options options = OptionsManager.getInstance().getOptions();
      ZoomOptions zoomOptions = options.getEditorOptions().getZoomOptions();
      // Open as actual size
      zoomModel.setZoomFactor(1.0d);

      if (zoomOptions.isSmartZooming()) {
        Dimension prefferedSize = zoomOptions.getPrefferedSize();
        if (prefferedSize.width > image.getWidth() && prefferedSize.height > image.getHeight()) {
          // Resize to preffered size
          // Calculate zoom factor

          double factor =
              (prefferedSize.getWidth() / (double) image.getWidth()
                      + prefferedSize.getHeight() / (double) image.getHeight())
                  / 2.0d;
          zoomModel.setZoomFactor(Math.ceil(factor));
        }
      }
    }
  }
Ejemplo n.º 4
0
  private int[][] apply(boolean preview) {
    int[][] heightmap = new int[128][128];
    int step = 1;

    if (!preview) {
      parent.setProgressBar(sldIterations.getValue());
      heightmap = parent.cloneArray(parent.getHeightMap());
    } else {
      heightmap = parent.getPreviewMap();
      step =
          (int)
              Math.ceil(
                  (double) parent.getHeightMap().length / (double) parent.getPreviewMap().length);
    }

    for (int i = 0; i < sldIterations.getValue() / step; i++) {
      heightmap = applyThermal(heightmap);

      if (!preview) parent.increaseProgressBar();
    }

    if (!preview) parent.resetProgressBar();

    return heightmap;
  }
Ejemplo n.º 5
0
  /** Precompute number of ticks */
  public static int calculateTicNumber(
      double ticMinVal, double ticMaxVal, double xStep, boolean isLog) {

    int n = 0;

    // System.out.println("\n-- calculateTicNumber=");
    // System.out.println("Min="+Double.toString(ticMinVal));
    // System.out.println("Max="+Double.toString(ticMaxVal));
    // System.out.println("Max="+Double.toString(xStep));

    if (isLog == false) {
      double xStart = xStep * Math.ceil(ticMinVal / xStep);
      for (double xpos = xStart; xpos <= ticMaxVal; xpos += xStep) n++;
    } else {
      int t1 = 0;
      int t2 = 0;
      if (ticMinVal > 0) t1 = (int) Math.floor(log10(ticMinVal) - 0.5);
      if (ticMinVal < 0) t1 = -1 * (int) Math.floor(log10(-1 * ticMinVal) - 0.5);
      if (ticMaxVal > 0) t2 = (int) Math.floor(log10(ticMaxVal) + 1.0);
      if (ticMaxVal < 0) t2 = -1 * (int) Math.floor(log10(-1 * ticMaxVal) + 1.0);
      for (int i = t1; i < t2 + 1; i++) n++;
    }

    // System.out.println("Nr of ticks="+Integer.toString(n));

    return n;
  }
Ejemplo n.º 6
0
  public QualityChartDialog(Frame owner, String title, ITimeStatsProvider statsProvider) {
    super(owner, title);
    this.title = title;
    this.statsProvider = statsProvider;

    int rows = 0;
    int columns = (int) Math.sqrt(chartDescriptions.length);
    if (columns > 1) {
      rows = (int) Math.ceil(chartDescriptions.length / (double) columns);
    }

    setLayout(new GridLayout(rows, columns));

    for (ChartDescription chartDescription : chartDescriptions) {
      JFreeChart lineChart =
          ChartFactory.createLineChart(
              chartDescription.title,
              "时间单元",
              chartDescription.title + (chartDescription.useRate ? "(%)" : ""),
              chartDescription.dataset,
              PlotOrientation.VERTICAL,
              false,
              true,
              false);

      add(new ChartPanel(lineChart));
    }

    setSize(1200, 730);

    updateStats();
  }
Ejemplo n.º 7
0
  /** Creates new form IndexCreatorDialog */
  public IndexCreatorDialog(java.awt.Frame parent, boolean modal, File file, File idxFile) {
    super(parent, modal);
    initComponents();
    jLabel1.setVisible(false);

    this.file = file;
    this.idxFile = idxFile;
    this.determineFileType(file);
    if (this.fileType == null)
      throw new IllegalArgumentException(
          "Cannot determine file type for " + file.getAbsolutePath());

    int timeEst = 1 + (int) Math.ceil(file.length() / 1000000000.0);

    String txt =
        introText
            .replace("@filename", file.getName())
            .replace("@time", String.valueOf(timeEst))
            .replace("@filetype", this.fileType.name());

    this.introTextPane.setText(txt);

    this.introTextPane.setBorder(BorderFactory.createEmptyBorder());

    switch (this.fileType) {
      case SAM:
        worker = new SamIndexWorker();
        break;
      case VCF:
        worker = new VCFIndexWorker();
        break;
    }
  }
Ejemplo n.º 8
0
    public boolean canZoomOut() {
      double factor = getZoomFactor();
      double minFactor = getMinimumZoomFactor();
      double stepSize = (1.0 - minFactor) / MICRO_ZOOM_LIMIT;
      double step = Math.ceil((1.0 - factor) / stepSize);

      return step < MICRO_ZOOM_LIMIT;
    }
Ejemplo n.º 9
0
    @NotNull
    private String getBranchesText() {
      if (myBranches == null) {
        return "<i>In branches: loading...</i>";
      }
      if (myBranches.isEmpty()) return "<i>Not in any branch</i>";
      if (myExpanded) {
        int rowCount = (int) Math.ceil((double) myBranches.size() / BRANCHES_TABLE_COLUMN_COUNT);
        HtmlTableBuilder builder = new HtmlTableBuilder();

        for (int i = 0; i < rowCount; i++) {
          builder.startRow();
          if (i == 0) {
            builder.append(
                "<i>In "
                    + myBranches.size()
                    + " branches, </i><a href=\""
                    + SHOW_OR_HIDE_BRANCHES
                    + "\"><i>hide</i></a>: ");
          } else {
            builder.append("");
          }

          for (int j = 0; j < BRANCHES_TABLE_COLUMN_COUNT; j++) {
            int index = rowCount * j + i;
            if (index >= myBranches.size()) {
              builder.append("");
            } else if (index != myBranches.size() - 1) {
              builder.append(
                  myBranches.get(index) + "," + StringUtil.repeat("&nbsp;", 20), LEFT_ALIGN);
            } else {
              builder.append(myBranches.get(index), LEFT_ALIGN);
            }
          }

          builder.endRow();
        }

        return builder.build();
      } else {
        String branchText;
        if (myBranches.size() <= BRANCHES_LIMIT) {
          branchText = StringUtil.join(myBranches, ", ");
        } else {
          branchText =
              StringUtil.join(ContainerUtil.getFirstItems(myBranches, BRANCHES_LIMIT), ", ")
                  + ", ... <a href=\""
                  + SHOW_OR_HIDE_BRANCHES
                  + "\"><i>Show All</i></a>";
        }
        return "<i>In "
            + myBranches.size()
            + StringUtil.pluralize(" branch", myBranches.size())
            + ":</i> "
            + branchText;
      }
    }
Ejemplo n.º 10
0
 /**
  * This deals with a bug/peculiarity for the default Mac font: several pixels of the ascent are
  * actually empty. This screws up certain measurements which assume the font is actually a few
  * pixels taller than it really is.
  */
 private static int getUnusedAscent(FontMetrics fm, Font font) {
   Integer value = ascentTable.get(font);
   if (value == null) {
     int recordedAscent = fm.getAscent();
     FontRenderContext frc = new FontRenderContext(new AffineTransform(), false, false);
     GlyphVector gv = font.createGlyphVector(frc, "XYZ");
     Rectangle2D bounds = ShapeBounds.getBounds(gv.getOutline());
     int observedAscent = (int) (Math.ceil(bounds.getHeight()) + .5);
     value = new Integer(recordedAscent - observedAscent);
     ascentTable.put(font, value);
   }
   return value.intValue();
 }
Ejemplo n.º 11
0
 private ArrayList<Integer> findRanges() {
   int rowsPerRange = (int) Math.ceil((grid.size()) / (double) threads);
   ArrayList<Integer> ranges = new ArrayList<Integer>();
   int startRow = 0, endRow = rowsPerRange;
   for (int i = 0; i < threads; i++) {
     ranges.add(startRow);
     ranges.add(endRow);
     startRow = endRow;
     ;
     endRow += rowsPerRange;
   }
   ranges.set(ranges.size() - 1, Math.min(grid.size(), ranges.get(ranges.size() - 1)));
   System.out.println(ranges);
   return ranges;
 }
Ejemplo n.º 12
0
    public void zoomOut() {
      double factor = getZoomFactor();
      if (factor > 1.0d) {
        // Macro
        setZoomFactor(factor / 2.0d);
      } else {
        // Micro
        double minFactor = getMinimumZoomFactor();
        double stepSize = (1.0d - minFactor) / MICRO_ZOOM_LIMIT;
        int step = (int) Math.ceil((1.0d - factor) / stepSize);

        setZoomFactor(1.0d - stepSize * (step + 1));
      }
      myZoomLevelChanged = true;
    }
  /** Initialize cycleTime, repaintInterval, numFrames, animationIndex. */
  private void initIndeterminateDefaults() {
    initRepaintInterval(); // initialize repaint interval
    initCycleTime(); // initialize cycle length

    // Make sure repaintInterval is reasonable.
    if (repaintInterval <= 0) {
      repaintInterval = 100;
    }

    // Make sure cycleTime is reasonable.
    if (repaintInterval > cycleTime) {
      cycleTime = repaintInterval * 20;
    } else {
      // Force cycleTime to be a even multiple of repaintInterval.
      int factor = (int) Math.ceil(((double) cycleTime) / ((double) repaintInterval * 2));
      cycleTime = repaintInterval * factor * 2;
    }
  }
Ejemplo n.º 14
0
  /**
   * Draws a single arrow head
   *
   * @param aG the canvas to draw on;
   * @param aXpos the X position of the arrow head;
   * @param aYpos the (center) Y position of the arrow head;
   * @param aFactor +1 to have a left-facing arrow head, -1 to have a right-facing arrow head;
   * @param aArrowWidth the total width of the arrow head;
   * @param aArrowHeight the total height of the arrow head.
   */
  public static final void drawArrowHead(
      final Graphics2D aG,
      final int aXpos,
      final int aYpos,
      final int aFactor,
      final int aArrowWidth,
      final int aArrowHeight) {
    final double halfHeight = aArrowHeight / 2.0;
    final int x1 = aXpos + (aFactor * aArrowWidth);
    final int y1 = (int) Math.ceil(aYpos - halfHeight);
    final int y2 = (int) Math.floor(aYpos + halfHeight);

    final Polygon arrowHead = new Polygon();
    arrowHead.addPoint(aXpos, aYpos);
    arrowHead.addPoint(x1, y1);
    arrowHead.addPoint(x1, y2);

    aG.fill(arrowHead);
  }
Ejemplo n.º 15
0
  /**
   * Calculation of the separation length between tics. Some smart rounding algorithms are needed to
   * get the scaling properly in case of data going to 10.3 or so... Useful stuff stolen from the
   * Gnuplot sources, thank you guys!!
   */
  public static double calculateTicSep(double min, double max, int maxNumberOfTicks) {
    double xnorm, tic, posns;
    double lrange = log10(Math.abs(min - max));
    double fl = Math.floor(lrange);
    xnorm = Math.pow(10.0, lrange - fl);
    posns = maxNumberOfTicks / xnorm;

    if (posns > 40) tic = 0.05; // eg 0, .05, .10, ...
    else if (posns > 20) tic = 0.1; // eg 0, .1, .2, ...
    else if (posns > 10) tic = 0.2; // eg 0,0.2,0.4,...
    else if (posns > 4) tic = 0.5; // 0,0.5,1,
    else if (posns > 1) tic = 1; // 0,1,2,....
    else if (posns > 0.5) tic = 2; // 0, 2, 4, 6
    else if (posns > 0.2) tic = 10; // 0, 10, 100, 6
    else tic = Math.ceil(xnorm);

    tic *= Math.pow(10.0, fl);

    return tic;
  }
Ejemplo n.º 16
0
  /**
   * this is the central method of this class. takes axis range parameters and produces a list of
   * string representations of nicely rounded numbers within the given range. these strings are
   * intended for use as axis tic labels. note: to find out where to plot each tic label simply use
   * <br>
   * <code>float ticval = Float.parseFloat(ticstring);</code>
   *
   * @param ticMinVal no tics will be created for less than this value.
   * @param ticMaxVal no tics will be created for greater than this value.
   * @param maxTics returned vector will contain no more labels than this number.
   * @param isLog set to true in case of log10 numbers
   * @return a Vector containing formatted label strings which should also be parsable into floating
   *     point numbers (in order to plot them).
   */
  public static Vector<String> computeTicks(
      double ticMinVal, double ticMaxVal, int maxTicks, boolean isLog) {
    // double xStep = roundUp((ticMaxVal-ticMinVal)/maxTicks);

    double xStep = calculateTicSep(ticMinVal, ticMaxVal, maxTicks);

    int numfracdigits = numFracDigits(xStep);

    // Compute x starting point so it is a multiple of xStep.
    double xStart = xStep * Math.ceil(ticMinVal / xStep);
    Vector xgrid = null;
    Vector<String> labels = new Vector<String>();
    // Label the axis. The labels are quantized so that
    // they don't have excess resolution.

    if (!isLog) {
      for (double xpos = xStart; xpos <= ticMaxVal; xpos += xStep) {
        String snum = formatNum(xpos, numfracdigits);
        labels.addElement(snum);
      }
      // log scale: special case
    } else {

      int t1 = 0;
      int t2 = 0;
      if (ticMinVal > 0) t1 = (int) Math.floor(log10(ticMinVal) - 0.5);
      if (ticMinVal < 0) t1 = -1 * (int) Math.floor(log10(-1 * ticMinVal) - 0.5);
      if (ticMaxVal > 0) t2 = (int) Math.floor(log10(ticMaxVal) + 1.0);
      if (ticMaxVal < 0) t2 = -1 * (int) Math.floor(log10(-1 * ticMaxVal) + 1.0);

      // System.out.println("min = " + xmin + ", max = " + xmax);
      for (int i = t1; i < t2 + 1; i++) {
        double pp = Math.pow(10.0, i);
        // System.out.println(pp);
        labels.addElement(Double.toString(pp));
      }
    }

    return labels;
  }
Ejemplo n.º 17
0
  public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    // Component printMe = getPrintComponent();

    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.black); // set default foreground color to black

    // for faster printing, turn off double buffering
    // RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);

    Dimension d = printComponent.getSize(); // get size of document
    double panelWidth = d.width; // width in pixels
    double panelHeight = d.height; // height in pixels
    double pageHeight = pf.getImageableHeight(); // height of printer page
    double pageWidth = pf.getImageableWidth(); // width of printer page
    double scale = pageWidth / panelWidth;
    int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);

    // make sure we don't print empty pages
    if (pageIndex >= totalNumPages) {
      return Printable.NO_SUCH_PAGE;
    }

    // shift Graphic to line up with beginning of print-imageable region
    g2.translate(pf.getImageableX(), pf.getImageableY());

    // shift Graphic to line up with beginning of next page to print
    g2.translate(0f, -pageIndex * pageHeight);

    // scale the page so the width fits...
    g2.scale(scale, scale);

    // PRINT IT!
    printComponent.paint(g2);

    return Printable.PAGE_EXISTS;
  }
Ejemplo n.º 18
0
  public int print(Graphics g, PageFormat pf, int pageIndex) {
    int response = NO_SUCH_PAGE;

    Graphics2D g2 = (Graphics2D) g;
    disableDoubleBuffering(componentToBePrinted);
    Dimension d = componentToBePrinted.getSize();
    double panelWidth = d.width;
    double panelHeight = d.height;
    double pageHeight = pf.getImageableHeight();
    double pageWidth = pf.getImageableWidth();
    double scale = pageWidth / panelWidth;
    int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    if (pageIndex >= totalNumPages) {
      response = NO_SUCH_PAGE;
    } else {
      g2.translate(pf.getImageableX(), pf.getImageableY());
      g2.translate(0f, -pageIndex * pageHeight);
      g2.scale(scale, scale);
      componentToBePrinted.paint(g2);
      enableDoubleBuffering(componentToBePrinted);
      response = Printable.PAGE_EXISTS;
    }
    return response;
  }
Ejemplo n.º 19
0
  void setupPanel(JabRefFrame frame, BasePanel bPanel, boolean addKeyField, String title) {

    InputMap im = panel.getInputMap(JComponent.WHEN_FOCUSED);
    ActionMap am = panel.getActionMap();

    im.put(Globals.prefs.getKey("Entry editor, previous entry"), "prev");
    am.put("prev", parent.prevEntryAction);
    im.put(Globals.prefs.getKey("Entry editor, next entry"), "next");
    am.put("next", parent.nextEntryAction);

    im.put(Globals.prefs.getKey("Entry editor, store field"), "store");
    am.put("store", parent.storeFieldAction);
    im.put(Globals.prefs.getKey("Entry editor, next panel"), "right");
    im.put(Globals.prefs.getKey("Entry editor, next panel 2"), "right");
    am.put("left", parent.switchLeftAction);
    im.put(Globals.prefs.getKey("Entry editor, previous panel"), "left");
    im.put(Globals.prefs.getKey("Entry editor, previous panel 2"), "left");
    am.put("right", parent.switchRightAction);
    im.put(Globals.prefs.getKey("Help"), "help");
    am.put("help", parent.helpAction);
    im.put(Globals.prefs.getKey("Save database"), "save");
    am.put("save", parent.saveDatabaseAction);
    im.put(Globals.prefs.getKey("Next tab"), "nexttab");
    am.put("nexttab", parent.frame.nextTab);
    im.put(Globals.prefs.getKey("Previous tab"), "prevtab");
    am.put("prevtab", parent.frame.prevTab);

    panel.setName(title);
    // String rowSpec = "left:pref, 4dlu, fill:pref:grow, 4dlu, fill:pref";
    String colSpec =
        "fill:pref, 1dlu, fill:10dlu:grow, 1dlu, fill:pref, "
            + "8dlu, fill:pref, 1dlu, fill:10dlu:grow, 1dlu, fill:pref";
    StringBuffer sb = new StringBuffer();
    int rows = (int) Math.ceil((double) fields.length / 2.0);
    for (int i = 0; i < rows; i++) {
      sb.append("fill:pref:grow, ");
    }
    if (addKeyField) sb.append("4dlu, fill:pref");
    else if (sb.length() >= 2) sb.delete(sb.length() - 2, sb.length());
    String rowSpec = sb.toString();

    DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(colSpec, rowSpec), panel);

    for (int i = 0; i < fields.length; i++) {
      // Create the text area:
      int editorType = BibtexFields.getEditorType(fields[i]);

      final FieldEditor ta;
      if (editorType == GUIGlobals.FILE_LIST_EDITOR)
        ta = new FileListEditor(frame, bPanel.metaData(), fields[i], null, parent);
      else ta = new FieldTextArea(fields[i], null);
      // ta.addUndoableEditListener(bPanel.undoListener);

      JComponent ex = parent.getExtra(fields[i], ta);

      // Add autocompleter listener, if required for this field:
      AbstractAutoCompleter autoComp = bPanel.getAutoCompleter(fields[i]);
      AutoCompleteListener acl = null;
      if (autoComp != null) {
        acl = new AutoCompleteListener(autoComp);
      }
      setupJTextComponent(ta.getTextComponent(), acl);
      ta.setAutoCompleteListener(acl);

      // Store the editor for later reference:
      editors.put(fields[i], ta);
      if (i == 0) activeField = ta;
      // System.out.println(fields[i]+": "+BibtexFields.getFieldWeight(fields[i]));
      // ta.getPane().setPreferredSize(new Dimension(100,
      //        (int)(50.0*BibtexFields.getFieldWeight(fields[i]))));
      builder.append(ta.getLabel());
      if (ex == null) builder.append(ta.getPane(), 3);
      else {
        builder.append(ta.getPane());
        JPanel pan = new JPanel();
        pan.setLayout(new BorderLayout());
        pan.add(ex, BorderLayout.NORTH);
        builder.append(pan);
      }
      if (i % 2 == 1) builder.nextLine();
    }

    // Add the edit field for Bibtex-key.
    if (addKeyField) {
      final FieldTextField tf =
          new FieldTextField(
              BibtexFields.KEY_FIELD, parent.getEntry().getField(BibtexFields.KEY_FIELD), true);
      // tf.addUndoableEditListener(bPanel.undoListener);
      setupJTextComponent(tf, null);

      editors.put("bibtexkey", tf);
      /*
       * If the key field is the only field, we should have only one
       * editor, and this one should be set as active initially:
       */
      if (editors.size() == 1) activeField = tf;
      builder.nextLine();
      builder.append(tf.getLabel());
      builder.append(tf, 3);
    }
  }
Ejemplo n.º 20
0
  @Override
  public void initialize(URL location, ResourceBundle resources) {
    AppController.instance = this;
    this.res = resources;

    ObservableList<String> modeItems =
        FXCollections.observableArrayList(
            Settings.MODE_NEXT, Settings.MODE_RANDOM, Settings.MODE_SAME);
    modeList.setItems(modeItems);
    modeList.getSelectionModel().select(Settings.currentMode);
    modeList
        .valueProperty()
        .addListener(
            (ObservableValue ov, Object oldVal, Object newVal) -> {
              Settings.currentMode = (String) newVal;
            });

    setupPlaylistsView();
    setupPlaylistsContextMenu();

    setupTracksView();

    tracksView.setContextMenu(tracksContextMenu);
    tracksView.setOnContextMenuRequested(
        (ContextMenuEvent evt) -> {
          setupTracksContextMenu();
          evt.consume();
        });
    tracksView
        .getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (ObservableValue observable, Object oldValue, Object newValue) -> {
              Settings.lastTrackId = newValue != null ? ((Track) newValue).getId() : null;
            });

    playlistsView
        .getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (ObservableValue observable, Object oldValue, Object newValue) -> {
              loadSelectedPlaylist();
              Settings.lastPlaylistId = newValue != null ? ((Playlist) newValue).getId() : null;
              searching = false;
              searchText.setText(StringUtils.EMPTY);
            });

    volumeSlider.setCursor(Cursor.HAND);
    volumeSlider
        .valueProperty()
        .addListener(
            (ObservableValue<? extends Number> ov, Number oldVal, Number newVal) -> {
              if (player != null) {
                player.setVolume(newVal.doubleValue());
              }
              Settings.currentVolume = newVal.doubleValue();
              volumeLabel.setText(
                  String.valueOf((int) Math.ceil(newVal.doubleValue() * 100)) + "%");
            });
    volumeSlider.setValue(Settings.currentVolume);

    imagePlay = new ImageView(new Image(getClass().getResourceAsStream("/images/button_play.png")));
    imagePlay.setScaleX(0.40);
    imagePlay.setScaleY(0.40);
    imagePause =
        new ImageView(new Image(getClass().getResourceAsStream("/images/button_pause.png")));
    imagePause.setScaleX(0.5);
    imagePause.setScaleY(0.5);
    imageSettings =
        new ImageView(new Image(getClass().getResourceAsStream("/images/settings.png")));
    imageSettings.setScaleX(0.5);
    imageSettings.setScaleY(0.5);
    imageUpdate = new ImageView(new Image(getClass().getResourceAsStream("/images/refresh.png")));
    imageUpdate.setScaleX(0.5);
    imageUpdate.setScaleY(0.5);
    imageAdd = new ImageView(new Image(getClass().getResourceAsStream("/images/add.png")));
    imageAdd.setScaleX(0.5);
    imageAdd.setScaleY(0.5);
    imageRename = new ImageView(new Image(getClass().getResourceAsStream("/images/rename.png")));
    imageRename.setScaleX(0.5);
    imageRename.setScaleY(0.5);
    imageDelete = new ImageView(new Image(getClass().getResourceAsStream("/images/delete.png")));
    imageDelete.setScaleX(0.5);
    imageDelete.setScaleY(0.5);

    stateButton.setGraphic(imagePlay);
    settingsButton.setGraphic(imageSettings);
    refreshButton.setGraphic(imageUpdate);
    refreshButton.setTooltip(new Tooltip(res.getString("tooltip_sync")));

    addButton.setGraphic(imageAdd);
    addButton.setOnAction((evt) -> createOfflinePlaylist());
    addButton.setTooltip(new Tooltip(res.getString("tooltip_add_offline")));
    renameButton.setGraphic(imageRename);
    renameButton.setOnAction(evt -> renamePlaylist());
    renameButton.setTooltip(new Tooltip(res.getString("rename_playlist")));
    deleteButton.setGraphic(imageDelete);
    deleteButton.setOnAction(evt -> deletePlaylist());
    deleteButton.setTooltip(new Tooltip(res.getString("delete_playlist")));

    loadProgressBar.setCursor(Cursor.HAND);
    volumeSlider.setCursor(Cursor.HAND);
    updatePlaylists();
    if (Settings.lastPlaylistId != null) {
      currentPlaylist =
          ((ObservableList<Playlist>) playlistsView.getItems())
              .stream()
              .filter((playlist) -> playlist.getId().equals(Settings.lastPlaylistId))
              .findFirst()
              .orElse(null);
      playlistsView.getSelectionModel().select(currentPlaylist);
      playlistsView.scrollTo(currentPlaylist);
      Platform.runLater(
          () -> {
            if (Settings.lastTrackId != null) {
              currentTrack =
                  ((ObservableList<Track>) tracksView.getItems())
                      .stream()
                      .filter((track) -> track.getId().equals(Settings.lastTrackId))
                      .findFirst()
                      .orElse(null);
              tracksView.getSelectionModel().select(currentTrack);
              tracksView.scrollTo(currentTrack);
            }
          });
    }
    new Timer()
        .scheduleAtFixedRate(
            new TimerTask() {
              @Override
              public void run() {
                updatePlayProgress();
              }
            },
            100,
            100);
    setupTracksContextMenu();

    setupShortcuts();

    Platform.runLater(
        () -> {
          tracksView.requestFocus();
        });
  }
Ejemplo n.º 21
0
  @SuppressWarnings("SuspiciousNameCombination")
  // so we don't get warned about using 'WallWidth' in conjunction with height
  @Override
  protected void paintComponent(Graphics g) {

    double width = this.getWidth();
    double height = this.getHeight();

    Graphics2D graphics2D = (Graphics2D) g;

    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2D.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    Board board = _gameState.board;

    double ratio = (double) board.width / board.height;

    width = Math.min(width, (height * ratio));
    height = Math.min(height, (width / ratio));

    double startX = this.getWidth() / 2 - width / 2;
    double startY = this.getHeight() / 2 - height / 2;

    g.setColor(Color.yellow);
    g.fillRect(round(startX), round(startY), round(width), round(height));

    // Draw the grid.

    g.setColor(Color.black);

    double step = width / board.width;

    for (double x = startX + step; x < startX + width; x += step) {
      g.drawLine(round(x), round(startY), round(x), round(startY + height));
    }
    for (double y = startY + step; y < startY + height; y += step) {
      g.drawLine(round(startX), round(y), round(startX + width), round(y));
    }

    // Draw the room tiles.

    int x = 0;
    for (Board.Tile[] column : board.tiles) {
      int y = 0;
      for (Board.Tile tile : column) {
        boolean hasRoom = tile.room.isPresent();
        boolean isUnaccessibleSpace = tile.connectedLocations.isEmpty();
        if (hasRoom || isUnaccessibleSpace) {
          g.setColor(hasRoom ? Color.lightGray : Color.cyan);
          g.fillRect(
              round(x * step + startX - 0.5),
              round(y * step + startY - 0.5),
              round(step + 1),
              round(step + 1));

          if (tile.isPassageway(board)) {
            g.setColor(Color.darkGray);
            for (int i = 0; i < step; i += 2) {
              g.fillRect(
                  round(x * step + startX - 0.5),
                  round(y * step + startY - 0.5 + i),
                  round(step + 1),
                  1);
            }
          }
        }

        y++;
      }

      x++;
    }

    // Draw the walls.
    // Loop again to draw over what we already have.

    g.setColor(Color.black);
    x = 0;
    for (Board.Tile[] column : board.tiles) {
      int y = 0;
      for (Board.Tile tile : column) {
        Location<Integer> location = new Location<>(x, y);

        if (board.hasWallBetween(location, new Location<>(x + 1, y))) {
          g.fillRect(
              round(startX + step * (x + 1) - WallWidth / 2),
              round(startY + step * y - 0.5),
              WallWidth,
              round(step + 1));
        }

        if (board.hasWallBetween(location, new Location<>(x, y + 1))) {
          g.fillRect(
              round(startX + step * x - 0.5),
              round(startY + step * (y + 1) - WallWidth / 2),
              round(step + 1),
              WallWidth);
        }

        y++;
      }

      x++;
    }

    // Draw the outer walls.

    g.fillRect(round(startX), round(startY), WallWidth, round(height));
    g.fillRect(round(startX), round(startY), round(width), WallWidth);
    g.fillRect(round(startX + width - WallWidth), round(startY), WallWidth, round(height));
    g.fillRect(round(startX), round(startY + height - WallWidth), round(width), WallWidth);

    // Draw the names for the rooms.

    g.setFont(GameFont);
    g.setColor(Color.black);
    FontMetrics fontMetrics = g.getFontMetrics(GameFont);

    for (Room room : Room.values()) {
      Location<Float> centre = board.centreLocationForRoom(room);
      double centreX = (centre.x + 0.5f) * step + startX;
      double centreY = (centre.y + 0.5f) * step + startY;

      String name = room.shortName().toUpperCase();

      Rectangle2D bounds = fontMetrics.getStringBounds(name, g);

      g.drawString(
          name, (int) (centreX - bounds.getCenterX()), (int) (centreY - bounds.getCenterY()));

      double stringBottom = bounds.getCenterY() + centreY;

      this.drawWeaponTokenForRoom(g, board, room, centreX, stringBottom, step);
    }

    // Draw the players.

    boolean shouldPlayMoveSequence = this.shouldPlayMoveSequence();
    for (Player player : _gameState.allPlayers) {
      boolean drawTransparent = false;
      Location<Float> playerLocation;
      if (shouldPlayMoveSequence
          && // We haven't finished animating the move
          player.character == _lastPlayerMoveCharacter) { // and the move is for this character
        // then we need to lerp between two values in the move sequence for the character's
        // position.

        int lowIndex = (int) Math.floor(_moveSequencePosition);
        int highIndex = (int) Math.ceil(_moveSequencePosition);
        double lerpValue = _moveSequencePosition - lowIndex;

        Location<Float> startLocation =
            this.centreForTileAtLocation(
                _lastPlayerMove.locations[lowIndex], board, startX, startY, step);
        Location<Float> endLocation =
            this.centreForTileAtLocation(
                _lastPlayerMove.locations[highIndex], board, startX, startY, step);
        if (Location.distance(startLocation, endLocation)
            > step * 1.5) { // if the tiles aren't adjacent, allowing for some error.
          drawTransparent = true;
        }
        playerLocation = Location.lerp(startLocation, endLocation, (float) lerpValue);
      } else {
        playerLocation =
            this.centreForTileAtLocation(player.location(), board, startX, startY, step);
      }

      this.drawPlayer(g, playerLocation, player.character, step, drawTransparent);
    }

    // If we're supposed to draw the overlay for the paths, do so. Don't draw the overlay while
    // we're animating.
    if (_accessibleTilePaths != null && !shouldPlayMoveSequence) {
      this.drawAccessibleTilesOverlay(g, _accessibleTilePaths, startX, startY, step);
    }
  }
Ejemplo n.º 22
0
  /** Class constructor - make the JFrame ready */
  public TestProgram() {
    // Set screen size
    Toolkit tk = Toolkit.getDefaultToolkit();
    int x = (int) tk.getScreenSize().getWidth() - 150;
    int y = (int) tk.getScreenSize().getHeight() - 100;
    this.setSize(x, y);

    // Some settings
    this.setTitle("Friends With Benefits - Test program");
    field = new Field();
    random = new Random(System.currentTimeMillis());

    // Set the panel
    c = this.getContentPane();
    c.setLayout(new BorderLayout());

    contentpanel = new ContentPanel();
    contentpanel.setField(field);
    c.add(contentpanel, BorderLayout.CENTER);

    // Menupanel
    menupanel = new JPanel();
    layout = new GroupLayout(menupanel);
    menupanel.setLayout(layout);
    c.add(menupanel, BorderLayout.EAST);

    progress = new JProgressBar(0, 99);
    progress.setValue(99);

    open = new JButton("Open");
    open.setFocusPainted(false);
    save = new JButton("Save");
    save.setFocusPainted(false);
    open.addActionListener(this);
    save.addActionListener(this);

    everywhere = new JRadioButton("Everywhere");
    everywhere.setFocusPainted(false);
    inRectangle = new JRadioButton("In bounding rectangle");
    inRectangle.setFocusPainted(false);
    inRectangle.setSelected(true);

    placeOfCluster = new ButtonGroup();
    placeOfCluster.add(everywhere);
    placeOfCluster.add(inRectangle);

    addnoise = new JButton("Add noise");
    addnoise.setFocusPainted(false);
    addnoise.addActionListener(this);

    circle = new JRadioButton("Circle");
    circle.setFocusPainted(false);
    square = new JRadioButton("Square");
    square.setFocusPainted(false);
    circle.setSelected(true);

    squarecircle = new ButtonGroup();
    squarecircle.add(circle);
    squarecircle.add(square);

    fillFactor = new JSlider();
    fillFactor.setMajorTickSpacing(20);
    fillFactor.setMinorTickSpacing(5);
    fillFactor.setPaintTicks(true);

    addacluster = new JButton("Add simple cluster");
    addacluster.setFocusPainted(false);
    addacluster.addActionListener(this);

    clear = new JButton("Clear field");
    clear.addActionListener(this);
    clear.setFocusPainted(false);

    center = new JButton("Center field");
    center.addActionListener(this);
    center.setFocusPainted(false);

    minAlgo = new JTextField();
    minAlgo.setText("0");
    maxAlgo = new JTextField();
    maxAlgo.setText("10");
    run = new JButton("Run algo");
    run.addActionListener(this);
    run.setFocusPainted(false);

    empty = new JPanel();
    empty.setLayout(new BorderLayout());

    JSeparator sep1 = new JSeparator();
    JSeparator sep2 = new JSeparator();
    JSeparator sep3 = new JSeparator();
    JSeparator sep4 = new JSeparator();
    JLabel runalgo = new JLabel("Run algorithm"), addcluster = new JLabel("Add simple cluster");
    JLabel addNoise = new JLabel("Add noise"), fillf = new JLabel("Fill factor:");
    JLabel minalgo = new JLabel("Min:"), maxalgo = new JLabel("Max:");
    addcluster.setFont(f);
    addNoise.setFont(f);
    runalgo.setFont(f);

    fillFactor.setPreferredSize(
        new Dimension(
            menupanel.getPreferredSize().width / 2, fillFactor.getPreferredSize().height));

    layout.setHorizontalGroup(
        layout
            .createParallelGroup(GroupLayout.Alignment.CENTER)
            .addGroup(
                layout.createSequentialGroup().addComponent(open).addGap(2).addComponent(save))
            .addComponent(sep1)
            .addComponent(addNoise)
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(everywhere)
                    .addComponent(inRectangle))
            .addComponent(addnoise)
            .addComponent(sep2)
            .addComponent(addcluster)
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(circle)
                    .addComponent(square))
            .addComponent(fillf)
            .addComponent(fillFactor)
            .addComponent(addacluster)
            .addComponent(sep3)
            .addComponent(center)
            .addComponent(clear)
            .addComponent(sep4)
            .addComponent(runalgo)
            .addGroup(
                layout
                    .createSequentialGroup()
                    .addComponent(minalgo)
                    .addGap(2)
                    .addComponent(minAlgo)
                    .addGap(10)
                    .addComponent(maxalgo)
                    .addGap(2)
                    .addComponent(maxAlgo))
            .addComponent(run)
            .addComponent(empty)
            .addComponent(progress));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(open)
                    .addComponent(save))
            .addGap(5)
            .addComponent(sep1)
            .addGap(5)
            .addComponent(addNoise)
            .addComponent(everywhere)
            .addComponent(inRectangle)
            .addGap(3)
            .addComponent(addnoise)
            .addGap(5)
            .addComponent(sep2)
            .addGap(5)
            .addComponent(addcluster)
            .addComponent(circle)
            .addComponent(square)
            .addGap(3)
            .addComponent(fillf)
            .addGap(3)
            .addComponent(fillFactor)
            .addGap(3)
            .addComponent(addacluster)
            .addGap(5)
            .addComponent(sep3)
            .addGap(5)
            .addComponent(center)
            .addGap(3)
            .addComponent(clear)
            .addGap(5)
            .addComponent(sep4)
            .addGap(5)
            .addComponent(runalgo)
            .addGap(3)
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(minalgo)
                    .addComponent(minAlgo)
                    .addComponent(maxalgo)
                    .addComponent(maxAlgo))
            .addComponent(run)
            .addComponent(empty)
            .addComponent(progress));

    int width = menupanel.getPreferredSize().width;

    setSize(addNoise, width - 10);
    setSize(everywhere, width - 20);
    setSize(inRectangle, width - 20);
    setSize(addnoise, width);

    setSize(addcluster, width - 10);
    setSize(circle, width - 20);
    setSize(square, width - 20);
    setSize(addacluster, width);

    setSize(center, width);
    setSize(clear, width);

    setSize(runalgo, width - 10);
    setSize(minalgo, (int) Math.floor(width / 4) - 20);
    setMaxSize(minAlgo, (int) Math.ceil(width / 4));
    setSize(maxalgo, (int) Math.floor(width / 4) - 20);
    setMaxSize(maxAlgo, (int) Math.ceil(width / 4));
    setSize(run, width);

    empty.setPreferredSize(new Dimension(width, 1000));

    menupanel.setBorder(
        BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(Color.BLACK),
            "Menu",
            TitledBorder.CENTER,
            TitledBorder.DEFAULT_POSITION,
            f));
  }
Ejemplo n.º 23
0
  public void init(final Function function) {
    xAxis.clear();
    yAxis.clear();

    if (function != lastFunction) { // need to reset
      Slot.CIRCLE.clearList();
      Slot.CROSS.clearList();
      Slot.SQUARE.clearList();
      Slot.TRIANGLE.clearList();
    }

    data = new GridPointData(resolution, resolution, 1);
    plot = new InterpolatedPlot(data);

    useSlot.clearList();
    final List<List<ValuePointColored>> points = useSlot.getPoints();
    for (Slot slot : Slot.values()) {
      if (slot.isShow()) {
        for (List<ValuePointColored> valuePoints : slot.getPoints()) {
          for (ValuePointColored valuePoint : valuePoints) {
            xAxis.add(valuePoint);
            yAxis.add(valuePoint);
          }
        }
      }
    }

    // clean drawing panel
    drawablePanel.removeDrawables(InterpolatedPlot.class);
    drawablePanel.addDrawable(plot);

    datasetRecreation =
        new Closure() {

          public void execute(Object input) {
            List<ValuePointColored> vps = (List<ValuePointColored>) input;
            points.add(vps);
            for (ValuePointColored vp : vps) {
              xAxis.add(vp);
              yAxis.add(vp);
            }

            if (points.size() > maxPoints) {
              List<ValuePointColored> removed = points.remove(0);
              for (ValuePointColored valuePoint : removed) {
                xAxis.remove(valuePoint);
                yAxis.remove(valuePoint);
              }
            }

            // for ilustration
            if (xAxis.size() > 0 && yAxis.size() > 0) {
              double lowerXBound =
                  Math.min(
                      data.getLeft(), Math.floor(xAxis.first().getPoint().toArray()[0] - buffer));
              double upperXBound =
                  Math.max(
                      data.getRight(), Math.ceil(xAxis.last().getPoint().toArray()[0] + buffer));
              double lowerYBound =
                  Math.min(
                      data.getBottom(), Math.floor(yAxis.first().getPoint().toArray()[1] - buffer));
              double upperYBound =
                  Math.max(data.getTop(), Math.ceil(yAxis.last().getPoint().toArray()[1] + buffer));

              data.setScale(lowerXBound, upperXBound, lowerYBound, upperYBound);
              double[][][] xyz = data.getData();

              for (int i = 0; i < resolution; i++) {
                for (int j = 0; j < resolution; j++) {
                  Point p = Point.at(xyz[i][j]);
                  // check the cached value of the point
                  xyz[i][j][2] = /*cache.containsKey(p) ? cache.get(p) :*/ function.valueAt(p);
                }
              }
            }

            plot.setGridData(data);

            drawablePanel.repaint();
          }
        };

    lastFunction = function;

    // initialize to center point
    double lowerXBound = Math.floor(centerX - buffer);
    double upperXBound = Math.ceil(centerX + buffer);
    double lowerYBound = Math.floor(centerY - buffer);
    double upperYBound = Math.ceil(centerY + buffer);

    data.setScale(lowerXBound, upperXBound, lowerYBound, upperYBound);
    double[][][] xyz = data.getData();

    for (int i = 0; i < resolution; i++) {
      for (int j = 0; j < resolution; j++) {
        Point p = Point.at(xyz[i][j]);
        // check the cached value of the point
        xyz[i][j][2] = /*cache.containsKey(p) ? cache.get(p) :*/ function.valueAt(p);
      }
    }

    plot.setGridData(data);
    drawablePanel.repaint();
  }
Ejemplo n.º 24
0
 /** Fills the panel with event specific fields. */
 protected void fillPanel() {
   JLabel l;
   Box fdp = Box.createVerticalBox();
   fdp.setBorder(BorderFactory.createTitledBorder("Fundamental Diagram"));
   fdChart = makeFDChart();
   ChartPanel cp = new ChartPanel(fdChart);
   cp.setMinimumDrawWidth(100);
   cp.setMinimumDrawHeight(60);
   cp.setPreferredSize(new Dimension(250, 80));
   fdp.add(new JScrollPane(cp));
   JPanel prmp = new JPanel(new SpringLayout());
   l = new JLabel("Capacity:", JLabel.TRAILING);
   prmp.add(l);
   spinMaxFlow = new JSpinner(new SpinnerNumberModel(mf, 0, 99999, 1.0));
   spinMaxFlow.setEditor(new JSpinner.NumberEditor(spinMaxFlow, "####0.00"));
   spinMaxFlow.addChangeListener(this);
   spinMaxFlow.setName(nmSpinMaxFlow);
   l.setLabelFor(spinMaxFlow);
   prmp.add(spinMaxFlow);
   l = new JLabel("Cap.Drop:", JLabel.TRAILING);
   prmp.add(l);
   spinCapDrop = new JSpinner(new SpinnerNumberModel(drp, 0, 99999, 1.0));
   spinCapDrop.setEditor(new JSpinner.NumberEditor(spinCapDrop, "####0.00"));
   spinCapDrop.addChangeListener(this);
   spinCapDrop.setName(nmSpinCapDrop);
   l.setLabelFor(spinCapDrop);
   prmp.add(spinCapDrop);
   l = new JLabel("C.Density:", JLabel.TRAILING);
   prmp.add(l);
   spinCritDen = new JSpinner(new SpinnerNumberModel(cd, 0, 99999, 1.0));
   spinCritDen.setEditor(new JSpinner.NumberEditor(spinCritDen, "####0.00"));
   spinCritDen.addChangeListener(this);
   spinCritDen.setName(nmSpinCritDen);
   l.setLabelFor(spinCritDen);
   prmp.add(spinCritDen);
   l = new JLabel("  V:", JLabel.TRAILING);
   prmp.add(l);
   spinVff = new JSpinner(new SpinnerNumberModel(mf / cd, 0, 200, 1.0));
   spinVff.setEditor(new JSpinner.NumberEditor(spinVff, "#0.00"));
   spinVff.addChangeListener(this);
   spinVff.setName(nmSpinVff);
   l.setLabelFor(spinVff);
   prmp.add(spinVff);
   l = new JLabel("J.Density:", JLabel.TRAILING);
   prmp.add(l);
   spinJamDen = new JSpinner(new SpinnerNumberModel(jd, 0, 99999, 1.0));
   spinJamDen.setEditor(new JSpinner.NumberEditor(spinJamDen, "####0.00"));
   spinJamDen.addChangeListener(this);
   spinJamDen.setName(nmSpinJamDen);
   l.setLabelFor(spinJamDen);
   prmp.add(spinJamDen);
   l = new JLabel("  W:", JLabel.TRAILING);
   prmp.add(l);
   if (jd == cd) jd = cd + 1;
   int ulim = (int) Math.max(Math.ceil(mf / (jd - cd)), 999);
   spinWc = new JSpinner(new SpinnerNumberModel(mf / (jd - cd), 0, ulim, 1.0));
   spinWc.setEditor(new JSpinner.NumberEditor(spinWc, "#0.00"));
   spinWc.addChangeListener(this);
   spinWc.setName(nmSpinWc);
   l.setLabelFor(spinWc);
   prmp.add(spinWc);
   SpringUtilities.makeCompactGrid(prmp, 3, 4, 2, 2, 2, 2);
   fdp.add(prmp);
   // add(new JScrollPane(fdp));
   add(fdp);
   return;
 }
Ejemplo n.º 25
0
public class MapPanel extends JPanel implements MouseListener, MouseMotionListener {

  private ArrayList<Hex> _hexes;
  // private ArrayList<BoardObject> _objects;

  private int[] _mousedown;
  private int[] _display_offset = {400, 0};

  private Hashtable<CoordPair, Pair> vertexContents;
  private Hashtable<Pair, Integer> roadContents;
  private Hashtable<Pair, BoardObject.type> portContents;

  public BoardObject _up;

  public SideBar sb;

  public int _x;
  public int _h;

  private int hexleft;
  private int hextop;
  private int radius = 75;

  private int _dieRoll;
  private int[] twoDice;

  private String _gameOver = "";
  private float _currAlpha = (float) 0.0;

  int intervalUp = (int) Math.ceil(radius * 0.866);
  int[] intervalSide = new int[] {(int) (radius / 2), radius};
  int rings;
  private final int[] DIE_DIST = {2, 3, 4, 4, 5, 5, 5, 6, 6, 8, 8, 9, 9, 9, 10, 10, 11, 12};
  private BufferedImage diceImage;
  // Robot r;

  private boolean _dismiss;

  private ClientGameBoard gameLogic;

  public MapPanel(ClientGameBoard gl) {
    super();

    _dismiss = false;
    gameLogic = gl;
    gameLogic._mapPanel = this;
    _hexes = new ArrayList<Hex>();
    vertexContents = new Hashtable<CoordPair, Pair>();
    roadContents = new Hashtable<Pair, Integer>();
    portContents = new Hashtable<Pair, BoardObject.type>();

    diceImage = new BufferedImage(582, 98, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = diceImage.createGraphics();
    g.drawImage(BoardObject.images.get(BoardObject.type.DICE), null, null);
    g.dispose();

    rings = gameLogic.getNumRings();

    hexleft =
        100
            - (int)
                (radius
                    + (Math.floor(rings / 2) * radius + Math.floor((rings - 1) / 2) * radius * 2));
    if (rings % 2 == 0) {
      hexleft -= radius / 2;
    }

    hextop = 300 - (int) (radius * 0.866 + (rings - 1) * 2 * (radius * 0.866));

    double border = 0.4;

    HashMap<Pair, Pair> hexData = gameLogic.getHexInfo(); // call the gamelogic

    Pair currCoord = gameLogic.getStartPoint();

    Pair topCoord = currCoord;

    int ring = 0;

    int currentDir = 5;
    int current = 0;
    int[][] directions = {{1, 1}, {0, 2}, {-1, 1}, {-1, -1}, {0, -2}, {1, -1}};

    int[][] HexCoordDirections = {{2, 1}, {0, 2}, {-2, 1}, {-2, -1}, {0, -2}, {2, -1}};

    Hex top =
        new Hex(
            100,
            300,
            radius,
            (BoardObject.type) (hexData.get(currCoord).getA()),
            (Integer) (hexData.get(currCoord).getB()));
    Hex curr = top;

    _hexes.add(top);
    while (true) {
      if (current == ring) {
        currentDir++;
        current = 0;
      }
      if (currentDir > 5) {
        currentDir = 0;
        current = 0;
        ring++;
        if (ring < rings) {
          topCoord = new Pair(currCoord.getA(), (Double) (currCoord.getB()) - 2);
          currCoord = topCoord;

          top =
              new Hex(
                  curr.getX(),
                  (curr.getY() - 2 * (Math.cos(Math.PI / 6) * (curr.getRadius() + border))),
                  curr.getRadius(),
                  (BoardObject.type) (hexData.get(currCoord).getA()),
                  (Integer) (hexData.get(currCoord).getB()));
          curr = top;

        } else {
          break;
        }
      }
      currCoord.setA((Object) ((Double) (currCoord.getA()) + HexCoordDirections[currentDir][0]));
      currCoord.setB((Object) ((Double) (currCoord.getB()) + HexCoordDirections[currentDir][1]));

      curr =
          new Hex(
              (curr.getX() + directions[currentDir][0] * (curr.getRadius() + border) * 3 / 2),
              (curr.getY()
                  + directions[currentDir][1]
                      * (Math.cos(Math.PI / 6) * (curr.getRadius() + border))),
              curr.getRadius(),
              (BoardObject.type) (hexData.get(currCoord).getA()),
              (Integer) (hexData.get(currCoord).getB()));
      _hexes.add(curr);

      current++;
    }

    addMouseListener(this);
    addMouseMotionListener(this);
  }

  private void callObjectAtLocation(int x, int y) {
    for (Hex o : _hexes) {
      if (Math.sqrt((o.getX() - x) * (o.getX() - x) + (o.getY() - y) * (o.getY() - y))
          < o.getRadius()) {
        o.clicked(x, y);
        return;
      }
    }
  }

  public void updateVertexContents(Hashtable<CoordPair, Pair> newy) {
    synchronized (vertexContents) {
      vertexContents = newy;
    }
    repaint();
  }

  public void updateEdgeContents(Hashtable<Pair, Integer> newy) {
    synchronized (roadContents) {
      roadContents = newy;
    }
    repaint();
  }

  public void updatePortContents(Hashtable<Pair, BoardObject.type> newy) {
    synchronized (portContents) {
      portContents = newy;
    }
    repaint();
  }

  public void updateRoll(int i) {
    _dieRoll = i;
    twoDice =
        new int[] {
          (int) Math.max(Math.floor(Math.random() * Math.min(_dieRoll - 1, 5)) + 1, _dieRoll - 6), 1
        };
    twoDice[1] = _dieRoll - twoDice[0];
    repaint();
  }

  public void gameOver(String s) {
    _gameOver = s;
    repaint();
  }

  public synchronized void paint(Graphics graphics) {

    Graphics2D g = (Graphics2D) graphics;

    Image water = Toolkit.getDefaultToolkit().getImage("catanui/water.jpg");
    g.drawImage(water, 0, 0, this);

    for (Hex o : _hexes) {
      o.paint(g, _display_offset[0], _display_offset[1]);
    }

    g.translate(_display_offset[0] + 2, _display_offset[1] - 1);
    synchronized (portContents) {
      for (Pair c : portContents.keySet()) {

        int lowx =
            hexleft
                + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getA()).getX() % 2) * intervalSide[0];
        int lowy = hextop + ((CoordPair) c.getA()).getY() * intervalUp;
        int highx =
            hexleft
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getB()).getX() % 2) * intervalSide[0];
        int highy = hextop + ((CoordPair) c.getB()).getY() * intervalUp;

        int dx = highx - lowx;
        int dy = highy - lowy;
        double rad = Math.atan((1.0) * dy / dx);

        if (dx < 0) rad += Math.PI;

        g.translate(lowx, lowy);
        g.rotate(rad);
        g.drawImage(
            BoardObject.images.get(BoardObject.type2port.get(portContents.get(c))), 0, -75, null);
        g.rotate(-rad);
        g.translate((-1) * lowx, (-1) * lowy);
      }
    }
    g.translate((-1) * _display_offset[0], (-1) * _display_offset[1]);

    synchronized (roadContents) {
      for (Pair c : roadContents.keySet()) {

        Road r =
            new Road(
                hexleft
                    + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                        / 2
                        * intervalSide[0]
                    + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                        / 2
                        * intervalSide[1]
                    + (((CoordPair) c.getA()).getX() % 2) * intervalSide[0],
                hextop + ((CoordPair) c.getA()).getY() * intervalUp);

        r.setX2(
            hexleft
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getB()).getX() % 2) * intervalSide[0]);
        r.setY2(hextop + ((CoordPair) c.getB()).getY() * intervalUp);

        r.setColor(roadContents.get(c));
        r.paint(g, _display_offset[0], _display_offset[1]);
      }
    }

    synchronized (vertexContents) {
      for (CoordPair c : vertexContents.keySet()) {
        int newx =
            hexleft
                + ((c._x - (c._x % 2)) / 2 * intervalSide[0]
                    + (c._x - (c._x % 2)) / 2 * intervalSide[1]
                    + (c._x % 2) * intervalSide[0])
                - 20;
        int newy = hextop + c._y * intervalUp - 20;

        if ((BoardObject.type) (vertexContents.get(c).getA()) == BoardObject.type.SETTLEMENT) {
          Settlement s = new Settlement(newx, newy, (Integer) (vertexContents.get(c).getB()));
          s.paint(g, _display_offset[0], _display_offset[1]);
        } else if ((BoardObject.type) (vertexContents.get(c).getA()) == BoardObject.type.CITY) {
          City s = new City(newx, newy, (Integer) (vertexContents.get(c).getB()));
          s.paint(g, _display_offset[0], _display_offset[1]);
        } else System.out.println("neither -_-");
      }
    }

    g.setColor(Color.GRAY);
    g.fill(new Rectangle(0, 0, 110, 60));
    g.setColor(Color.LIGHT_GRAY);
    g.fill(new Rectangle(3, 3, 104, 56));
    if (_dieRoll > 0) {
      BufferedImage r1img =
          diceImage.getSubimage((int) (Math.floor((twoDice[0] - 1) * 94.7)), 0, 94, 93);
      g.drawImage(r1img, 5, 7, 48, 47, null);
      BufferedImage r2img =
          diceImage.getSubimage((int) (Math.floor((twoDice[1] - 1) * 94.7)), 0, 94, 93);
      g.drawImage(r2img, 55, 7, 48, 47, null);
    }

    if (_up != null) _up.paint(g);

    if (!_gameOver.equals("") && !_dismiss) {
      _currAlpha += 0.007;
    }
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, _currAlpha));
    g.setColor(Color.GRAY);
    g.fill(new Rectangle(-20, 0, 1020, 650));
    g.setColor(Color.BLACK);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 1.0));
    if (!_gameOver.equals("")) {

      if (_currAlpha >= 0.8) {
        if (_gameOver.equals(gameLogic._name)) {
          g.drawString("Congratulations, you won!", 350, 200);
        } else {
          g.drawString(_gameOver + " has won!", 350, 200);
        }
        _dismiss = true;
      } else repaint();
    }
  }

  /** MOUSE EVENTS! */
  @Override
  public void mouseClicked(MouseEvent e) {
    callObjectAtLocation(e.getX() - _display_offset[0], e.getY() - _display_offset[1]);
    repaint();
  }

  @Override
  public void mouseEntered(MouseEvent e) {
    repaint();
  }

  @Override
  public void mouseExited(MouseEvent e) {

    if (_up != null) { // && (e.getY() < _h-10)) {
      if (_up.getType() == BoardObject.type.SETTLEMENT) sb.activateExchanger(0, true);
      else if (_up.getType() == BoardObject.type.ROAD) sb.activateExchanger(1, true);
      else if (_up.getType() == BoardObject.type.CITY) sb.activateExchanger(3, true);
      //                 sb.setUp(_up,e.getX(),e.getY());
      _up = null;
      repaint();
    } else {

    }
  }

  @Override
  public void mousePressed(MouseEvent e) {
    if (_up == null) _mousedown = new int[] {e.getX(), e.getY()};
  }

  @Override
  public void mouseReleased(MouseEvent e) {

    if (_up != null) {
      int[] pos = setUpNearest(e);

      if (_up.getType() == BoardObject.type.SETTLEMENT)
        gameLogic.writeBuildSettlement(pos[0], pos[1]);
      else if (_up.getType() == BoardObject.type.CITY) gameLogic.writeBuildCity(pos[0], pos[1]);
      else if ((_up.getType() == BoardObject.type.ROAD) && (((Road) _up).oneDown == true)) {

        gameLogic.writeBuildRoad(((Road) _up).mycoord[0], ((Road) _up).mycoord[1], pos[0], pos[1]);
      }

      if (_up.getType() == BoardObject.type.ROAD) {
        if (((Road) _up).oneDown == false) {

          _up.setX(
              hexleft
                  + ((pos[0] - (pos[0] % 2)) / 2 * intervalSide[0]
                      + (pos[0] - (pos[0] % 2)) / 2 * intervalSide[1]
                      + (pos[0] % 2) * intervalSide[0])
                  + _display_offset[0]);
          _up.setY(hextop + pos[1] * intervalUp + _display_offset[1]);

          ((Road) _up).oneDown = true;
          ((Road) _up).mycoord = pos;

          _mousedown = null;
          e.consume();
        } else {
          ((Road) _up)
              .setX2(
                  hexleft
                      + ((pos[0] - (pos[0] % 2)) / 2 * intervalSide[0]
                          + (pos[0] - (pos[0] % 2)) / 2 * intervalSide[1]
                          + (pos[0] % 2) * intervalSide[0]));
          ((Road) _up).setY2(hextop + pos[1] * intervalUp);
          ((Road) _up).oneDown = true;
          _up = null;
          _mousedown = null;
        }
      } else {
        _up.setX(
            hexleft
                + ((pos[0] - (pos[0] % 2)) / 2 * intervalSide[0]
                    + (pos[0] - (pos[0] % 2)) / 2 * intervalSide[1]
                    + (pos[0] % 2) * intervalSide[0])
                - _up.getW() / 2);
        _up.setY(hextop + pos[1] * intervalUp - _up.getH() / 2);
        _up = null;
        _mousedown = null;
      }
    }
    repaint();
  }

  private int[] setUpNearest(MouseEvent e) {

    int mousex = e.getX() - _display_offset[0];
    int mousey = e.getY() - _display_offset[1];

    int i = 0;
    int j;

    j = (int) Math.round((mousey - hextop) * 1.0 / intervalUp);

    if ((j % 2 + (rings - 1) % 2) == 0 || (((j - 1) % 2 + (rings) % 2) == 0)) {
      int glob = 1;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              < mousex - hexleft - radius / 2;
          i++) glob += (((i % 2) == 0) ? 1 : 3);

      double dx =
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              - (mousex - hexleft - radius / 2);

      if ((i % 2) == 1 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 0 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;

    } else {
      int glob = 0;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) < mousex - hexleft;
          i++) glob += (((i % 2) == 0) ? 3 : 1);

      double dx =
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) - (mousex - hexleft);

      if ((i % 2) == 0 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 1 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;
    }

    return new int[] {i, j};
  }

  @Override
  public void mouseDragged(MouseEvent e) {

    if (_mousedown != null && _up == null) {
      _display_offset[0] += e.getX() - _mousedown[0];
      _display_offset[1] += e.getY() - _mousedown[1];
      _mousedown = new int[] {e.getX(), e.getY()};
    }
    if (_up != null) {
      if (_up.getType() == BoardObject.type.ROAD) {
        if (((Road) _up).oneDown == false) {
          _up.setX(e.getX());
          _up.setY(e.getY());
        } else {
          ((Road) _up).setX2(e.getX());
          ((Road) _up).setY2(e.getY());
        }
      } else {
        _up.setX(e.getX() - _up.getW() / 2);
        _up.setY(e.getY() - _up.getH() / 2);
      }
    }

    repaint();
  }

  @Override
  public void mouseMoved(MouseEvent e) {
    if (_up != null) mouseDragged(e);
  }

  public void setUp(BoardObject u, int x, int y) {

    u.setX(5);
    _up = u;
  }
}
    public int print(java.awt.Graphics pg, java.awt.print.PageFormat pageFormat, int pageIndex)
        throws java.awt.print.PrinterException {

      if (pageIndex >= m_maxNumPage || m_bi == null) {
        return NO_SUCH_PAGE;
      }

      pg.translate((int) pageFormat.getImageableX() + 1, (int) pageFormat.getImageableY() + 1);

      int wPage = (int) pageFormat.getImageableWidth() + 1;

      int hPage = (int) pageFormat.getImageableHeight() + 1;

      double scale = percentSize / 100.0;

      wPage = (int) (wPage / scale);

      hPage = (int) (hPage / scale);

      /*

      int wPage = (int)pageFormat.getImageableWidth();

      int hPage = (int)pageFormat.getImageableHeight();



      int w = m_bi.getWidth(this);

      int h = m_bi.getHeight(this);

      if (w == 0 || h == 0)

      return NO_SUCH_PAGE;

      int nCol = Math.max((int)Math.ceil((double)w/wPage), 1);

      int nRow = Math.max((int)Math.ceil((double)h/hPage), 1);

      m_maxNumPage = nCol*nRow;



      int iCol = pageIndex % nCol;

      int iRow = pageIndex / nCol;

      int x = iCol*wPage;

      int y = iRow*hPage;

      int wImage = Math.min(wPage, w-x);

      int hImage = Math.min(hPage, h-y);

      */

      int w = m_bi.getWidth(this);

      int h = m_bi.getHeight(this);

      // int resizedw = (int)(w*(percentSize/100.0));

      // int resizedh = (int)(h*(percentSize/100.0));

      java.awt.Graphics2D g2d = (java.awt.Graphics2D) pg;

      g2d.scale(percentSize / 100.0, percentSize / 100.0);

      if (w == 0 || h == 0) {
        return NO_SUCH_PAGE;
      }

      int nCol = Math.max((int) Math.ceil((double) w / wPage), 1);

      int nRow = Math.max((int) Math.ceil((double) h / hPage), 1);

      m_maxNumPage = nCol * nRow;

      int iCol = pageIndex % nCol;

      int iRow = pageIndex / nCol;

      int x = iCol * wPage;

      int y = iRow * hPage;

      int wImage = Math.min(wPage, w - x);

      int hImage = Math.min(hPage, h - y);

      g2d.drawImage(m_bi, 0, 0, wImage, hImage, x, y, x + wImage, y + hImage, this);

      // pg.drawImage(m_bi, 0, 0, 40, 40,  x, y, x+wImage, y+hImage, this);

      System.gc();

      return PAGE_EXISTS;
    }
  public InfoPanelForDrawable(
      final Map map_line2treenodes, final String[] y_colnames, final Drawable dobj) {
    super();
    super.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    /* Define DecialFormat for the displayed time */
    if (fmt == null) {
      fmt = (DecimalFormat) NumberFormat.getInstance();
      fmt.applyPattern(FORMAT);
    }
    if (tfmt == null) tfmt = new TimeFormat();
    if (Normal_Border == null) {
      /*
      Normal_Border = BorderFactory.createCompoundBorder(
                      BorderFactory.createRaisedBevelBorder(),
                      BorderFactory.createLoweredBevelBorder() );
      */
      Normal_Border = BorderFactory.createEtchedBorder();
    }
    if (Shadow_Border == null) {
      Shadow_Border =
          BorderFactory.createTitledBorder(
              Normal_Border,
              " Preview State ",
              TitledBorder.LEFT,
              TitledBorder.TOP,
              Const.FONT,
              Color.magenta);
    }

    drawable = dobj;

    // Set the CategoryLabel Icon
    Dimension panel_max_size;
    Category type = null;
    CategoryLabel label_type = null;
    JPanel top_panel = new JPanel();
    top_panel.setLayout(new BoxLayout(top_panel, BoxLayout.X_AXIS));
    if (drawable instanceof Shadow && ((Shadow) drawable).getSelectedSubCategory() != null) {
      type = ((Shadow) drawable).getSelectedSubCategory();
      label_type = new CategoryLabel(type);
      ((Shadow) drawable).clearSelectedSubCategory();
      top_panel.setBorder(Shadow_Border);
    } else {
      type = drawable.getCategory();
      label_type = new CategoryLabel(type);
      top_panel.setBorder(Normal_Border);
    }
    top_panel.add(STRUT);
    top_panel.add(label_type);
    top_panel.add(GLUE);
    top_panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    panel_max_size = top_panel.getPreferredSize();
    panel_max_size.width = Short.MAX_VALUE;
    top_panel.setMaximumSize(panel_max_size);
    super.add(top_panel);

    // Determine the text of the drawable
    TextAreaBuffer textbuf;
    int num_cols, num_rows;
    textbuf = new TextAreaBuffer(map_line2treenodes, y_colnames);
    if (drawable instanceof Shadow) textbuf.setShadowText((Shadow) drawable, type);
    else if (drawable instanceof Composite) textbuf.setCompositeText((Composite) drawable);
    else textbuf.setPrimitiveText((Primitive) drawable);
    textbuf.finalized();
    num_cols = textbuf.getColumnCount();
    num_rows = textbuf.getRowCount();

    // Set the TextArea
    JTextArea text_area;
    int adj_num_cols;
    text_area = new JTextArea(textbuf.toString());
    adj_num_cols = Routines.getAdjNumOfTextColumns(text_area, num_cols);
    num_cols = (int) Math.ceil(adj_num_cols * 85.0d / 100.0d);
    text_area.setColumns(num_cols);
    text_area.setRows(num_rows);
    text_area.setEditable(false);
    text_area.setLineWrap(true);
    JScrollPane scroller = new JScrollPane(text_area);
    scroller.setAlignmentX(Component.LEFT_ALIGNMENT);
    super.add(scroller);
  }