Ejemplo n.º 1
0
 /**
  * Calculate angle of tangent line at a particular point
  *
  * @param t : parameter
  * @return angle
  */
 public double calcDirectionAt(double t) {
   final boolean db = false;
   calcTangentAt(t, workPt);
   double a = Math.atan2(workPt.y, workPt.x);
   if (db) {
     System.out.println("calcDirectionAt " + Tools.f(t) + " a=" + Tools.fa(a));
   }
   return a;
 }
Ejemplo n.º 2
0
 public int getSliceNumber(String label) {
   int slice = 0;
   if (label.length() >= 14 && label.charAt(4) == '-' && label.charAt(9) == '-')
     slice = (int) Tools.parseDouble(label.substring(0, 4), -1);
   else if (label.length() >= 17 && label.charAt(5) == '-' && label.charAt(11) == '-')
     slice = (int) Tools.parseDouble(label.substring(0, 5), -1);
   else if (label.length() >= 20 && label.charAt(6) == '-' && label.charAt(13) == '-')
     slice = (int) Tools.parseDouble(label.substring(0, 6), -1);
   return slice;
 }
Ejemplo n.º 3
0
  /**
   * Clip out a section of the arm, using internal parameter values
   *
   * @param c0 : start of section to clip out
   * @param c1 : end of section to clip out; if < c0, c0 & c1 are swapped
   */
  private void clip0(double c0, double c1) {
    final boolean db = false;

    if (c0 > c1) {
      double t = c0;
      c0 = c1;
      c1 = t;
    }

    // array to store new clip elements in
    DArray nc = new DArray();

    if (db) {
      System.out.println("clip " + Tools.f(c0) + "..." + Tools.f(c1));
    }

    for (int i = 0; i < visSeg.size(); i += 2) {

      double t0 = visSeg.getDouble(i), t1 = visSeg.getDouble(i + 1);
      if (db) {

        System.out.println(" seg " + i + " " + Tools.f(t0) + "..." + Tools.f(t1));
      }

      // if this seg is outside clip region, leave intact (add it)
      if (t0 >= c1 || t1 <= c0) {
        nc.addDouble(t0);
        nc.addDouble(t1);
        continue;
      }

      if (t0 >= c0 && t1 <= c1) {
        if (db) {
          System.out.println("  clipping entire segment");
        }
        // remove entire segment, by skipping it
        continue;
      }

      // add unclipped portion
      if (t0 < c0) {
        nc.addDouble(t0);
        nc.addDouble(c0);
      }
      if (t1 > c1) {
        nc.addDouble(c1);
        nc.addDouble(t1);
      }
    }
    visSeg = nc;
    if (db) {
      System.out.println(" after clipping:" + visSeg);
    }
  }
Ejemplo n.º 4
0
    @Override
    public void actionPerformed(ActionEvent arg0) {
      try {
        pref.clear();
        Tools.notify((Image) null, "Prefs", "Preferences were cleared");
      } catch (Exception e) {
        System.out.println("Remove preferences from splash fail");
      }

      s.setIcon(new ImageIcon(Tools.findImage("splash")));
      p.remove(r);
    }
Ejemplo n.º 5
0
  public void render(Color c, int stroke, int markType) {
    if (c == null) c = Color.RED;
    V.pushColor(c);
    if (defined()) {
      seg.render(c, stroke, markType);
    } else {

      for (int i = 0; i < 2; i++) {
        if (i == 1 && discA == discB) continue;

        EdObject obj = object(i);
        if (obj instanceof EdDisc) {
          EdDisc d = (EdDisc) obj;

          stroke = STRK_RUBBERBAND;
          V.pushStroke(stroke);
          double r = Math.max(d.getRadius() - 4, 2.0);
          V.drawCircle(d.getOrigin(), r);
          V.popStroke();
        } else {
          Tools.unimp("rendering undefined bitangents of polygons");
        }
      }
    }
    V.popColor();
  }
Ejemplo n.º 6
0
 public void reload() {
   userhp.setMaximum(battle.user.leader.health.max);
   userhp.setValue(battle.user.leader.health.cur);
   userhp.setToolTipText(battle.user.leader.health.cur + "/" + battle.user.leader.health.max);
   enemyhp.setMaximum(battle.enemy.leader.health.max);
   enemyhp.setValue(battle.enemy.leader.health.cur);
   enemyhp.setToolTipText(battle.enemy.leader.health.cur + "/" + battle.enemy.leader.health.max);
   userxp.setMaximum(battle.user.leader.xpNeeded());
   userxp.setValue(battle.user.leader.xp);
   userpic.setIcon(new ImageIcon(Tools.findImage(battle.user.leader)));
   enemypic.setIcon(new ImageIcon(Tools.findImage(battle.enemy.leader)));
   username.setText(battle.user.party.leader().name + " Lvl." + battle.user.leader.level);
   enemyname.setText(battle.enemy.leader.name + " Lvl." + battle.enemy.leader.level);
   userstatus.setText(battle.user.leader.status.toString());
   enemystatus.setText(battle.enemy.leader.status.toString());
   Tools.game.repaint();
 }
Ejemplo n.º 7
0
 /**
  * Synchroneous method to load the image. It should only be called by something which is a thread
  * itself such as the HtmlDistillerThread. Since this intended for large batch operations this
  * bypasses the cache.
  *
  * @param imageUrl The Url of the image to be loaded
  * @param rotation The angle by which it is to be roated upon loading.
  */
 public void loadPictureImd(URL imageUrl, double rotation) {
   Tools.log("loadPictureImd invoked with URL: " + imageUrl.toString());
   if (sourcePicture != null) sourcePicture.removeListener(this);
   sourcePicture = new SourcePicture();
   sourcePicture.addListener(this);
   setStatus(LOADING, "Loading: " + imageUrl.toString());
   scaleAfterLoad = true;
   sourcePicture.loadPicture(imageUrl, rotation);
 }
Ejemplo n.º 8
0
  private void construct() {
    setTitle("JPokemon (ver 0.1)");
    setIconImage(Tools.findImage("main-icon"));
    setSize(720, 457); // WIDTH, HEIGHT
    setUndecorated(true);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    // Using JLayeredPane so my buttons can sit on the picture
    p = new JLayeredPane();
    ImageIcon bg;
    // Add Splash
    if (pref.getBoolean("beat", false)) bg = new ImageIcon(Tools.findImage("splashalt"));
    else bg = new ImageIcon(Tools.findImage("splash"));
    s.setIcon(bg);
    s.setBounds(10, 10, 700, 437);
    p.add(s, new Integer(-1));

    // Load Button
    LoadButton l = new LoadButton(this);
    l.setBounds(550, 100, 110, 30); // 10px border on all sides
    p.add(l, new Integer(0));

    // New Game Button
    NewButton n = new NewButton(this);
    n.setBounds(550, 60, 110, 30);
    p.add(n, new Integer(0));

    // Exit Game Button
    QuitButton q = new QuitButton(this);
    q.setBounds(550, 140, 110, 30);
    p.add(q, new Integer(0));

    // OPTIONAL: Reset Splash logon
    if (pref.getBoolean("beat", false)) {
      r = new ResetButton();
      r.setBounds(550, 180, 110, 30);
      p.add(r, new Integer(0));
    }
    add(p);

    setLocationRelativeTo(null);
  }
Ejemplo n.º 9
0
  /**
   * Construct a hyperbola
   *
   * @param f1 FPoint2 : first focus
   * @param f2 FPoint2 : second focus
   * @param interceptDistance : closest distance of point on arm to f1
   */
  public Hyperbola(FPoint2 f1, FPoint2 f2, double interceptDistance) {
    double fDist = f2.distance(f1);
    if (!(interceptDistance >= 0 && interceptDistance <= fDist))
      throw new FPError(
          "Hyperbola construction: icept="
              + Tools.f(interceptDistance)
              + " of max "
              + Tools.f(fDist)
              + "\n f1="
              + f1
              + " f2="
              + f2);

    double ratio = 0;
    if (fDist > 0) {
      ratio = interceptDistance / fDist;
    }
    FPoint2 pt = FPoint2.interpolate(f1, f2, ratio);
    construct(f1, f2, pt);
  }
Ejemplo n.º 10
0
  /**
   * Determine closest point on hyperbolic arm to a point pt
   *
   * @param pt : point
   * @return t value for closest point; not necessarily within clipped range
   */
  public double closestPointTo(FPoint2 pt) {

    final boolean db = false;

    pt = toCurveSpace(pt, null);

    double U = B + 1;
    double V = -pt.y;
    double W = B * pt.x;

    Polyn p =
        new Polyn( //
            B * U * U, //
            2 * B * U * V, //
            B * V * V + A * U * U - W * W, //
            2 * A * U * V, //
            A * V * V //
            );

    if (db) Streams.out.println("closestPointTo, pt=" + pt + "\n" + p);
    double ret = 0;

    try {
      DArray r = new DArray();

      if (Math.abs(p.c(0)) < 1e-5) r.addDouble(0);
      else p.solve(r);

      if (r.isEmpty()) {
        throw new FPError("can't find closest point, poly=\n" + p);
      }

      double bestDist = 0;

      for (int i = 0; i < r.size(); i++) {
        double t = r.getDouble(i);
        FPoint2 apt = calcPoint(t);
        double dist = apt.distance(pt);
        if (i == 0 || dist < bestDist) {
          bestDist = dist;
          ret = t;
        }
      }
    } catch (FPError e) {
      Tools.warn("caught FPError");
      //      Streams.out.println("caught:\n" + e);
      ret = (this.minParameter() + this.maxParameter()) * .5;
    }

    return ret;
  }
 private boolean buildTree() {
   InspectionProfile profile = myInspectionProfile;
   boolean isGroupedBySeverity = myGlobalInspectionContext.getUIOptions().GROUP_BY_SEVERITY;
   myGroups.clear();
   final Map<String, Tools> tools = myGlobalInspectionContext.getTools();
   boolean resultsFound = false;
   for (Tools currentTools : tools.values()) {
     InspectionToolWrapper defaultToolWrapper = currentTools.getDefaultState().getTool();
     final HighlightDisplayKey key = HighlightDisplayKey.find(defaultToolWrapper.getShortName());
     for (ScopeToolState state : myProvider.getTools(currentTools)) {
       InspectionToolWrapper toolWrapper = state.getTool();
       if (myProvider.checkReportedProblems(myGlobalInspectionContext, toolWrapper)) {
         addTool(
             toolWrapper,
             ((InspectionProfileImpl) profile)
                 .getErrorLevel(key, state.getScope(myProject), myProject),
             isGroupedBySeverity);
         resultsFound = true;
       }
     }
   }
   return resultsFound;
 }
Ejemplo n.º 12
0
  public String visString() {
    StringBuilder sb = new StringBuilder();
    if (visSeg != null) {
      for (int i = 0; i < visSeg.size(); i += 2) {
        double t0 = 0, t1 = 0;
        if (flipped()) {
          int j = visSeg.size() - i - 2;
          t0 = toExt(visSeg.getDouble(j + 1));
          t1 = toExt(visSeg.getDouble(j));
        } else {
          t0 = visSeg.getDouble(i);
          t1 = visSeg.getDouble(i + 1);
        }

        sb.append("<");
        sb.append(Tools.f(t0));
        sb.append("..");

        sb.append(Tools.f(t1));
        sb.append("> ");
      }
    }
    return sb.toString();
  }
Ejemplo n.º 13
0
  /**
   * Method that sets the status of the ScalablePicture object and notifies intereasted objects of a
   * change in status (not built yet).
   */
  private void setStatus(int statusCode, String statusMessage) {
    String filename = (imageUrl == null) ? "" : imageUrl.toString();
    Tools.log(
        "ScalablePicture.setStatus: sending: "
            + statusMessage
            + " to all Listeners from Image: "
            + filename);

    pictureStatusCode = statusCode;
    pictureStatusMessage = statusMessage;

    Enumeration e = scalablePictureStatusListeners.elements();
    while (e.hasMoreElements()) {
      ((ScalablePictureListener) e.nextElement())
          .scalableStatusChange(pictureStatusCode, pictureStatusMessage);
    }
  }
Ejemplo n.º 14
0
  /**
   * Test program for Hyperbola class
   *
   * @param args String[]
   */
  public static void main(String[] args) {

    final double[] pts = { //
      100, 0, -100, 0, 75, 20,

      //  120, 30, -100, -10, 70, 50,
    };

    for (int i = 0; i < pts.length; i += 6) {
      try {
        Hyperbola h =
            new Hyperbola(
                new FPoint2(pts[i + 0], pts[i + 1]),
                new FPoint2(pts[i + 2], pts[i + 3]),
                new FPoint2(pts[i + 4], pts[i + 5]));
        System.out.println("Constructed:\n" + h);

        for (double t = -50; t <= 50; t += 10) {

          FPoint2 pt = h.calcPoint(t);

          FPoint2 pt2 = new FPoint2(pt.x, pt.y + 5);

          double tClosest = h.closestPointTo(pt2);

          System.out.println("t=" + Tools.f(t) + " pt=" + pt + " closest=" + tClosest);

          if (t == -20) {
            for (double t2 = tClosest - .1; t2 <= tClosest + .1; t2 += .01) {
              FPoint2 pt3 = h.calcPoint(t2);
              Streams.out.println("t2=" + t2 + " dist=" + pt3.distance(pt2));
            }
          }
        }

      } catch (TBError e) {
        System.out.println(e.toString());
      }
    }
  }
Ejemplo n.º 15
0
  /**
   * method that is invoked by the SourcePictureListener interface. Usually this will be called by
   * the SourcePicture telling the ScalablePicture that it has completed loading. The
   * ScalablePicture should then change it's own status and tell the ScalableListeners what's up.
   */
  public void sourceStatusChange(int statusCode, String statusMessage, SourcePicture sp) {
    // Tools.log("ScalablePicture.sourceStatusChange: status received from SourceImage: " +
    // statusMessage);

    switch (statusCode) {
      case SourcePicture.UNINITIALISED:
        Tools.log(
            "ScalablePicture.sourceStatusChange: pictureStatus was: UNINITIALISED message: "
                + statusMessage);
        setStatus(UNINITIALISED, statusMessage);
        break;
      case SourcePicture.ERROR:
        Tools.log(
            "ScalablePicture.sourceStatusChange: pictureStatus was: ERROR message: "
                + statusMessage);
        setStatus(ERROR, statusMessage);
        sourcePicture.removeListener(this);
        break;
      case SourcePicture.LOADING:
        Tools.log(
            "ScalablePicture.sourceStatusChange: pictureStatus was: LOADING message: "
                + statusMessage);
        setStatus(LOADING, statusMessage);
        break;
      case SourcePicture.ROTATING:
        Tools.log(
            "ScalablePicture.sourceStatusChange: pictureStatus was: ROTATING message: "
                + statusMessage);
        setStatus(LOADING, statusMessage);
        break;
      case SourcePicture.READY:
        Tools.log(
            "ScalablePicture.sourceStatusChange: pictureStatus was: READY message: "
                + statusMessage);
        setStatus(LOADED, statusMessage);
        sourcePicture.removeListener(this);
        if (scaleAfterLoad) {
          createScaledPictureInThread(Thread.MAX_PRIORITY);
          scaleAfterLoad = false;
        }
        break;
      default:
        Tools.log(
            "ScalablePicture.sourceStatusChange: Don't recognize this status: " + statusMessage);
        break;
    }
  }
Ejemplo n.º 16
0
  /**
   * Calculate a point on the hyperbola
   *
   * @param t : parameter in internal space (after flipping has occurred)
   * @param dest : where to store the calculated point
   */
  private FPoint2 calcPointInternal(double t, FPoint2 dest) {
    final boolean db = false;
    if (!valid) throw new FPError("calcPoint of invalid hyperbola");

    //    Tools.ASSERT(valid, "calcPoint of invalid hyperbola");
    //    final FPoint2 work = new FPoint2();
    //
    //    work.setLocation(Polyn.sqrt(A + t * t * B), t);
    dest = toW2.apply(Polyn.sqrt(A + t * t * B), t, dest);
    //
    //    if (dest == null)
    //      dest = new FPoint2();
    //    Matrix.apply(toW2, work, dest);
    if (db) {
      System.out.println(
          "calcPoint t="
              + Tools.f(toExt(t)) // + " armsp=" + work
              + " world="
              + dest);
    }
    return dest;
  }
Ejemplo n.º 17
0
  /**
   * Add a border of a particular style to a component
   *
   * @param c : JComponent to add border to
   * @param borderType : type of border, BD_x
   * @param label : if not null, string to display at top of border
   * @param labelAlignment : if label defined, this determines its horizontal alignment
   */
  public static void addBorder(JComponent c, int borderType, String label, int labelAlignment) {
    final Border[] b = {
      // #0: empty, spacing of 2
      BorderFactory.createEmptyBorder(2, 2, 2, 2),
      // #1: lowered etched, interior spacing of 2
      BorderFactory.createCompoundBorder(
          BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
          BorderFactory.createEmptyBorder(2, 2, 2, 2)),
      // BorderFactory.createLineBorder(Color.red,3),
    };

    Tools.ASSERT(!(label != null && borderType < 0));

    if (label != null) {
      TitledBorder t = BorderFactory.createTitledBorder(b[borderType], label);

      int tbAlign = 0;
      switch (labelAlignment) {
        default:
          tbAlign = TitledBorder.LEFT;
          break;
        case SwingConstants.CENTER:
          tbAlign = TitledBorder.CENTER;
          break;
        case SwingConstants.RIGHT:
          tbAlign = TitledBorder.RIGHT;
          break;
      }
      t.setTitleJustification(tbAlign);
      c.setBorder(t);
    } else {
      if (borderType >= 0) {
        c.setBorder(b[borderType]);
      }
    }
  }
Ejemplo n.º 18
0
  private void construct() {
    // @preformat

    // Root Panel
    JPanel root = new JPanel();
    root.setLayout(new BoxLayout(root, BoxLayout.PAGE_AXIS));
    // Fighters panel
    JPanel f = new JPanel();
    f.setLayout(new FlowLayout());
    // User Panel
    JPanel userpane = new JPanel();
    userpane.setLayout(new FlowLayout());
    // Party Info
    uparty = new JPanel();
    uparty.setPreferredSize(new Dimension(40, 50));
    for (int i = 0; i < 6; i++) {
      if (battle.user.party.pkmn[i] != null && battle.user.party.pkmn[i].awake)
        uparty.add(new JLabel(new ImageIcon(Tools.findImage("active"))));
      else {
        uparty.add(new JLabel(new ImageIcon(Tools.findImage("inactive"))));
      }
    }
    userpane.add(uparty);
    // Picture
    userpic = new JLabel(new ImageIcon(Tools.findImage(battle.user.leader)));
    userpane.add(userpic);
    // Info
    JPanel userinfo = new JPanel();
    userinfo.setLayout(new BoxLayout(userinfo, BoxLayout.PAGE_AXIS));
    // Name
    username = new JLabel(battle.user.party.leader().name + " Lvl." + battle.user.leader.level);
    userinfo.add(username);
    // HP Bar
    userhp = new JProgressBar(0, battle.user.leader.health.max);
    userhp.setValue(battle.user.leader.health.cur);
    userhp.setForeground(Color.PINK);
    userhp.setBackground(Color.GRAY);
    userhp.setStringPainted(true);
    userhp.setBorderPainted(false);
    userinfo.add(userhp);
    // XP Bar
    userxp = new JProgressBar(0, battle.user.leader.xpNeeded());
    userxp.setValue(battle.user.leader.xp);
    userxp.setForeground(Color.CYAN);
    userxp.setBackground(Color.GRAY);
    userxp.setStringPainted(true);
    userxp.setBorderPainted(false);
    userinfo.add(userxp);
    // Status
    userstatus = new JLabel(battle.user.leader.status.toString());
    userinfo.add(userstatus);
    userpane.add(userinfo);
    f.add(userpane);
    // Enemy Panel
    JPanel enemypane = new JPanel();
    enemypane.setLayout(new FlowLayout());
    // Info
    JPanel enemyinfo = new JPanel();
    enemyinfo.setLayout(new BoxLayout(enemyinfo, BoxLayout.PAGE_AXIS));
    // Name
    enemyname = new JLabel(battle.enemy.leader.name + " Lvl." + battle.enemy.leader.level);
    enemyinfo.add(enemyname);
    // HP Bar
    enemyhp = new JProgressBar(0, battle.enemy.leader.health.max);
    enemyhp.setValue(battle.enemy.leader.health.cur);
    enemyhp.setForeground(Color.PINK);
    enemyhp.setBackground(Color.GRAY);
    enemyhp.setStringPainted(true);
    enemyhp.setBorderPainted(false);
    enemyinfo.add(enemyhp);
    // Status
    enemystatus = new JLabel(battle.enemy.leader.status.toString());
    enemyinfo.add(enemystatus);
    enemypane.add(enemyinfo);
    // Picture
    enemypic = new JLabel(new ImageIcon(Tools.findImage(battle.enemy.leader)));
    enemypane.add(enemypic);
    // Party Info
    oparty = new JPanel();
    oparty.setPreferredSize(new Dimension(40, 50));
    for (int i = 0; i < 6; i++) {
      if (battle.enemy.party.pkmn[i] != null && battle.enemy.party.pkmn[i].awake)
        oparty.add(new JLabel(new ImageIcon(Tools.findImage("active"))));
      else {
        oparty.add(new JLabel(new ImageIcon(Tools.findImage("inactive"))));
      }
    }
    enemypane.add(oparty);
    f.add(enemypane);
    root.add(f);
    // Buttons panel
    JPanel b = new JPanel();
    b.add(new FightButton());
    b.add(new ItemButton());
    b.add(new SwapButton());
    b.add(new RunButton());
    root.add(b);
    add(root);
    // @format
  }
Ejemplo n.º 19
0
  public void show(List<Rule> rules) {
    if (original != null) config.restoreState(original);
    dialog = new JDialog(owner, true);
    dialog.setTitle(messages.getString("guiConfigWindowTitle"));

    Collections.sort(rules, new CategoryComparator());

    // close dialog when user presses Escape key:
    final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    final ActionListener actionListener =
        new ActionListener() {
          @Override
          public void actionPerformed(@SuppressWarnings("unused") ActionEvent actionEvent) {
            dialog.setVisible(false);
          }
        };
    final JRootPane rootPane = dialog.getRootPane();
    rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

    // JPanel
    final JPanel checkBoxPanel = new JPanel();
    checkBoxPanel.setLayout(new GridBagLayout());
    GridBagConstraints cons = new GridBagConstraints();
    cons.anchor = GridBagConstraints.NORTHWEST;
    cons.gridx = 0;
    cons.weightx = 1.0;
    cons.weighty = 1.0;
    cons.fill = GridBagConstraints.BOTH;
    DefaultMutableTreeNode rootNode = createTree(rules);
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    treeModel.addTreeModelListener(
        new TreeModelListener() {

          @Override
          public void treeNodesChanged(TreeModelEvent e) {
            DefaultMutableTreeNode node =
                (DefaultMutableTreeNode) e.getTreePath().getLastPathComponent();
            int index = e.getChildIndices()[0];
            node = (DefaultMutableTreeNode) (node.getChildAt(index));
            if (node instanceof RuleNode) {
              RuleNode o = (RuleNode) node;
              if (o.getRule().isDefaultOff()) {
                if (o.isEnabled()) {
                  config.getEnabledRuleIds().add(o.getRule().getId());
                } else {
                  config.getEnabledRuleIds().remove(o.getRule().getId());
                }
              } else {
                if (o.isEnabled()) {
                  config.getDisabledRuleIds().remove(o.getRule().getId());
                } else {
                  config.getDisabledRuleIds().add(o.getRule().getId());
                }
              }
            }
            if (node instanceof CategoryNode) {
              CategoryNode o = (CategoryNode) node;
              if (o.isEnabled()) {
                config.getDisabledCategoryNames().remove(o.getCategory().getName());
              } else {
                config.getDisabledCategoryNames().add(o.getCategory().getName());
              }
            }
          }

          @Override
          public void treeNodesInserted(TreeModelEvent e) {}

          @Override
          public void treeNodesRemoved(TreeModelEvent e) {}

          @Override
          public void treeStructureChanged(TreeModelEvent e) {}
        });
    configTree = new JTree(treeModel);
    configTree.setRootVisible(false);
    configTree.setEditable(false);
    configTree.setCellRenderer(new CheckBoxTreeCellRenderer());
    TreeListener.install(configTree);
    checkBoxPanel.add(configTree, cons);

    MouseAdapter ma =
        new MouseAdapter() {
          private void handlePopupEvent(MouseEvent e) {
            final JTree tree = (JTree) e.getSource();

            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
              return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

            TreePath[] paths = tree.getSelectionPaths();

            boolean isSelected = false;
            if (paths != null) {
              for (TreePath selectionPath : paths) {
                if (selectionPath.equals(path)) {
                  isSelected = true;
                }
              }
            }
            if (!isSelected) {
              tree.setSelectionPath(path);
            }
            if (node.isLeaf()) {
              JPopupMenu popup = new JPopupMenu();
              final JMenuItem aboutRuleMenuItem =
                  new JMenuItem(messages.getString("guiAboutRuleMenu"));
              aboutRuleMenuItem.addActionListener(
                  new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                      RuleNode node = (RuleNode) tree.getSelectionPath().getLastPathComponent();
                      Rule rule = node.getRule();
                      Language lang = config.getLanguage();
                      if (lang == null) {
                        lang = Language.getLanguageForLocale(Locale.getDefault());
                      }
                      Tools.showRuleInfoDialog(
                          tree,
                          messages.getString("guiAboutRuleTitle"),
                          rule.getDescription(),
                          rule,
                          messages,
                          lang.getShortNameWithCountryAndVariant());
                    }
                  });
              popup.add(aboutRuleMenuItem);
              popup.show(tree, e.getX(), e.getY());
            }
          }

          @Override
          public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopupEvent(e);
            }
          }

          @Override
          public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopupEvent(e);
            }
          }
        };
    configTree.addMouseListener(ma);
    final JPanel treeButtonPanel = new JPanel();
    cons = new GridBagConstraints();
    cons.gridx = 0;
    cons.gridy = 0;
    final JButton expandAllButton = new JButton(messages.getString("guiExpandAll"));
    treeButtonPanel.add(expandAllButton, cons);
    expandAllButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            TreeNode root = (TreeNode) configTree.getModel().getRoot();
            TreePath parent = new TreePath(root);
            for (Enumeration categ = root.children(); categ.hasMoreElements(); ) {
              TreeNode n = (TreeNode) categ.nextElement();
              TreePath child = parent.pathByAddingChild(n);
              configTree.expandPath(child);
            }
          }
        });

    cons.gridx = 1;
    cons.gridy = 0;
    final JButton collapseAllbutton = new JButton(messages.getString("guiCollapseAll"));
    treeButtonPanel.add(collapseAllbutton, cons);
    collapseAllbutton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            TreeNode root = (TreeNode) configTree.getModel().getRoot();
            TreePath parent = new TreePath(root);
            for (Enumeration categ = root.children(); categ.hasMoreElements(); ) {
              TreeNode n = (TreeNode) categ.nextElement();
              TreePath child = parent.pathByAddingChild(n);
              configTree.collapsePath(child);
            }
          }
        });

    final JPanel motherTonguePanel = new JPanel();
    motherTonguePanel.add(new JLabel(messages.getString("guiMotherTongue")), cons);
    motherTongueBox = new JComboBox(getPossibleMotherTongues());
    if (config.getMotherTongue() != null) {
      motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages));
    }
    motherTongueBox.addItemListener(
        new ItemListener() {

          @Override
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              Language motherTongue;
              if (motherTongueBox.getSelectedItem() instanceof String) {
                motherTongue =
                    getLanguageForLocalizedName(motherTongueBox.getSelectedItem().toString());
              } else {
                motherTongue = (Language) motherTongueBox.getSelectedItem();
              }
              config.setMotherTongue(motherTongue);
            }
          }
        });
    motherTonguePanel.add(motherTongueBox, cons);

    final JPanel portPanel = new JPanel();
    portPanel.setLayout(new GridBagLayout());
    // TODO: why is this now left-aligned?!?!
    cons = new GridBagConstraints();
    cons.insets = new Insets(0, 4, 0, 0);
    cons.gridx = 0;
    cons.gridy = 0;
    cons.anchor = GridBagConstraints.WEST;
    cons.fill = GridBagConstraints.NONE;
    cons.weightx = 0.0f;
    if (!insideOOo) {
      serverCheckbox = new JCheckBox(Tools.getLabel(messages.getString("guiRunOnPort")));
      serverCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("guiRunOnPort")));
      serverCheckbox.setSelected(config.getRunServer());
      portPanel.add(serverCheckbox, cons);
      serverCheckbox.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
              serverPortField.setEnabled(serverCheckbox.isSelected());
              serverSettingsCheckbox.setEnabled(serverCheckbox.isSelected());
            }
          });
      serverCheckbox.addItemListener(
          new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
              config.setRunServer(serverCheckbox.isSelected());
            }
          });

      serverPortField = new JTextField(Integer.toString(config.getServerPort()));
      serverPortField.setEnabled(serverCheckbox.isSelected());
      serverSettingsCheckbox = new JCheckBox(Tools.getLabel(messages.getString("useGUIConfig")));
      // TODO: without this the box is just a few pixels small, but why??:
      serverPortField.setMinimumSize(new Dimension(100, 25));
      cons.gridx = 1;
      portPanel.add(serverPortField, cons);
      serverPortField
          .getDocument()
          .addDocumentListener(
              new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                  changedUpdate(e);
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                  try {
                    int serverPort = Integer.parseInt(serverPortField.getText());
                    if (serverPort > -1 && serverPort < 65536) {
                      serverPortField.setForeground(null);
                      config.setServerPort(serverPort);
                    } else {
                      serverPortField.setForeground(Color.RED);
                    }
                  } catch (NumberFormatException ex) {
                    serverPortField.setForeground(Color.RED);
                  }
                }
              });

      cons.gridx = 0;
      cons.gridy = 10;
      serverSettingsCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("useGUIConfig")));
      serverSettingsCheckbox.setSelected(config.getUseGUIConfig());
      serverSettingsCheckbox.setEnabled(config.getRunServer());
      serverSettingsCheckbox.addItemListener(
          new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
              config.setUseGUIConfig(serverSettingsCheckbox.isSelected());
            }
          });
      portPanel.add(serverSettingsCheckbox, cons);
    }

    final JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridBagLayout());
    okButton = new JButton(Tools.getLabel(messages.getString("guiOKButton")));
    okButton.setMnemonic(Tools.getMnemonic(messages.getString("guiOKButton")));
    okButton.addActionListener(this);
    cancelButton = new JButton(Tools.getLabel(messages.getString("guiCancelButton")));
    cancelButton.setMnemonic(Tools.getMnemonic(messages.getString("guiCancelButton")));
    cancelButton.addActionListener(this);
    cons = new GridBagConstraints();
    cons.insets = new Insets(0, 4, 0, 0);
    buttonPanel.add(okButton, cons);
    buttonPanel.add(cancelButton, cons);

    final Container contentPane = dialog.getContentPane();
    contentPane.setLayout(new GridBagLayout());
    cons = new GridBagConstraints();
    cons.insets = new Insets(4, 4, 4, 4);
    cons.gridx = 0;
    cons.gridy = 0;
    cons.weightx = 10.0f;
    cons.weighty = 10.0f;
    cons.fill = GridBagConstraints.BOTH;
    contentPane.add(new JScrollPane(checkBoxPanel), cons);

    cons.gridx = 0;
    cons.gridy = 1;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.LINE_END;
    contentPane.add(treeButtonPanel, cons);

    cons.gridx = 0;
    cons.gridy = 2;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.WEST;
    contentPane.add(motherTonguePanel, cons);

    cons.gridx = 0;
    cons.gridy = 3;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.WEST;
    contentPane.add(portPanel, cons);

    cons.gridx = 0;
    cons.gridy = 4;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.EAST;
    contentPane.add(buttonPanel, cons);

    dialog.pack();
    dialog.setSize(500, 500);
    // center on screen:
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    final Dimension frameSize = dialog.getSize();
    dialog.setLocation(
        screenSize.width / 2 - frameSize.width / 2, screenSize.height / 2 - frameSize.height / 2);
    dialog.setLocationByPlatform(true);
    dialog.setVisible(true);
  }
Ejemplo n.º 20
0
 public static void main(String args[]) {
   if (System.getProperty("java.version").substring(0, 3).compareTo("1.5") < 0) {
     javax.swing.JOptionPane.showMessageDialog(
         null, "ImageJ " + VERSION + " requires Java 1.5 or later.");
     System.exit(0);
   }
   boolean noGUI = false;
   int mode = STANDALONE;
   arguments = args;
   // System.setProperty("file.encoding", "UTF-8");
   int nArgs = args != null ? args.length : 0;
   boolean commandLine = false;
   for (int i = 0; i < nArgs; i++) {
     String arg = args[i];
     if (arg == null) continue;
     if (args[i].startsWith("-")) {
       if (args[i].startsWith("-batch")) noGUI = true;
       else if (args[i].startsWith("-debug")) IJ.setDebugMode(true);
       else if (args[i].startsWith("-ijpath") && i + 1 < nArgs) {
         if (IJ.debugMode) IJ.log("-ijpath: " + args[i + 1]);
         Prefs.setHomeDir(args[i + 1]);
         commandLine = true;
         args[i + 1] = null;
       } else if (args[i].startsWith("-port")) {
         int delta = (int) Tools.parseDouble(args[i].substring(5, args[i].length()), 0.0);
         commandLine = true;
         if (delta == 0) mode = EMBEDDED;
         else if (delta > 0 && DEFAULT_PORT + delta < 65536) port = DEFAULT_PORT + delta;
       }
     }
   }
   // If existing ImageJ instance, pass arguments to it and quit.
   boolean passArgs = mode == STANDALONE && !noGUI;
   if (IJ.isMacOSX() && !commandLine) passArgs = false;
   if (passArgs && isRunning(args)) return;
   ImageJ ij = IJ.getInstance();
   if (!noGUI && (ij == null || (ij != null && !ij.isShowing()))) {
     ij = new ImageJ(null, mode);
     ij.exitWhenQuitting = true;
   }
   int macros = 0;
   for (int i = 0; i < nArgs; i++) {
     String arg = args[i];
     if (arg == null) continue;
     if (arg.startsWith("-")) {
       if ((arg.startsWith("-macro") || arg.startsWith("-batch")) && i + 1 < nArgs) {
         String arg2 = i + 2 < nArgs ? args[i + 2] : null;
         Prefs.commandLineMacro = true;
         if (noGUI && args[i + 1].endsWith(".js")) Interpreter.batchMode = true;
         IJ.runMacroFile(args[i + 1], arg2);
         break;
       } else if (arg.startsWith("-eval") && i + 1 < nArgs) {
         String rtn = IJ.runMacro(args[i + 1]);
         if (rtn != null) System.out.print(rtn);
         args[i + 1] = null;
       } else if (arg.startsWith("-run") && i + 1 < nArgs) {
         IJ.run(args[i + 1]);
         args[i + 1] = null;
       }
     } else if (macros == 0 && (arg.endsWith(".ijm") || arg.endsWith(".txt"))) {
       IJ.runMacroFile(arg);
       macros++;
     } else if (arg.length() > 0 && arg.indexOf("ij.ImageJ") == -1) {
       File file = new File(arg);
       IJ.open(file.getAbsolutePath());
     }
   }
   if (IJ.debugMode && IJ.getInstance() == null) new JavaProperties().run("");
   if (noGUI) System.exit(0);
 }
Ejemplo n.º 21
0
  public void render(Color c, int stroke, int markType) {
    final boolean db = false;
    // Get array of visible segments.  If no such array exists,
    // use default.
    DArray vseg = visSeg;
    boolean dashed = false;

    //    if (step == 0) {
    double step = renderStep();
    //    }
    //    vp V = TestBed.view();

    if (db) Streams.out.println(" step=" + step);

    // plot each visible segment

    for (int seg = 0; seg < vseg.size(); seg += 2) {
      double t0 = vseg.getDouble(seg + 0), t1 = vseg.getDouble(seg + 1);
      t0 = MyMath.clamp(t0, -500.0, 500.0);
      t1 = MyMath.clamp(t1, -500.0, 500.0);

      // render() expects external parameters.

      double s0 = toExt(t0), s1 = toExt(t1);
      if (s0 > s1) {
        double tmp = s0;
        s0 = s1;
        s1 = tmp;
      }
      FPoint2 p0 = calcPoint(s0), p1 = calcPoint(s1);
      if (db) Streams.out.println(" p0=" + p0 + ", p1=" + p1);
      if (isLine() && !dashed) {
        V.drawLine(p0, p1);
      } else {

        /*
                  if (Math.abs(s0) >= 500
           ||Math.abs(s1) >= 500)
         System.out.println("Rendering "+t0+" to "+t1+" step "+step);
        */
        if (dashed) V.pushStroke(Globals.STRK_RUBBERBAND);
        {
          //          int count = 0;
          boolean first = true;
          for (double t = t0; ; t += step) { // , count++) {
            boolean last = (t >= t1);
            if (last) {
              t = t1;
            }
            calcPointInternal(t, p1);

            if (!p1.isValid()) {
              if (last) {
                break;
              }
              continue;
            }

            if (db) {
              System.out.println(" calcPt " + Tools.f(toExt(t)) + " = " + p1.x + "," + p1.y);
            }
            if (!first) {
              V.drawLine(p0, p1);
              if (false) {
                Tools.warn("highlighting int");
                V.mark(p0);
              }
            }
            if (last) {
              break;
            }
            p0.setLocation(p1);
            first = false;
          }
        }
        if (dashed) V.popStroke();
      }
    }
  }
Ejemplo n.º 22
0
  /**
   * Find intersections of hyperbolic arm with an axes-aligned line segment. Arm must intersect
   * segment, not its underlying (infinite) line. The intersection points are sorted into increasing
   * parameter values w.r.t. the arm.
   *
   * @param s0 : start of line segment
   * @param s1 : end of line segment
   * @param ipts : intersection points returned here
   * @param reverseOrder : if true, points are sorted by decreasing parameter values
   * @param dbFlag : true to print debug information
   */
  public void findOrthogonalIntersect(
      FPoint2 s0, FPoint2 s1, DArray ipts, boolean reverseOrder, boolean dbFlag) {

    final boolean db = true && dbFlag;

    if (db) {
      System.out.println(
          "findOrthogonalIntersect " + s0 + " -> " + s1 + " rev:" + Tools.f(reverseOrder));
    }

    // Determine whether this is a vertical or horizontal line segment.

    boolean vert = (Math.abs(s1.y - s0.y) > Math.abs(s1.x - s0.x));
    if (db) {
      System.out.println(" vert=" + Tools.f(vert));
    }

    // Find the quadratic to solve.
    Polyn p;
    PlaneCurve cv = getCurve();
    if (vert) {
      p = cv.solveForX(s0.x);
    } else {
      p = cv.solveForY(s0.y);
    }

    DArray lst = new DArray();
    p.solve(lst);

    if (db) {
      System.out.println(" curve=" + cv.toString(true));
      System.out.println(" polyn=" + p.toString(true));
      System.out.println(" roots=" + Tools.d(lst));
    }

    // Sort points, discarding those not on line segment,
    // and those not on the correct arm.
    ipts.clear();

    for (int i = 0; i < lst.size(); i++) {
      double ta = lst.getDouble(i);
      FPoint2 pt;
      if (vert) {
        pt = new FPoint2(s0.x, ta);
      } else {
        pt = new FPoint2(ta, s0.y);
      }

      if (db) {
        System.out.println(" position on arm for ta=" + ta + " is " + pt);
      }
      double t = MyMath.positionOnSegment(pt, s0, s1);
      if (db) {
        System.out.println("  pt=" + pt + " t=" + t);
      }
      if (t < 0 || t > 1) {
        if (db) {
          System.out.println("   not on segment, skipping");
        }
        continue;
      }

      FPoint2 cpt = toCurveSpace(pt, null);
      if (db) {
        System.out.println("  curveSpace=" + cpt);
      }
      if (cpt.x < 0) {
        if (db) {
          System.out.println("   skipping...");
        }
        continue;
      }

      double t1 = calcParameter(pt);
      int j = 0;
      while (true) {
        if (j == ipts.size()) {
          break;
        }
        double t2 = calcParameter(ipts.getFPoint2(j));
        if (!reverseOrder) {
          if (t1 < t2) {
            break;
          }
        } else if (t1 > t2) {
          break;
        }
        j++;
      }
      ipts.add(j, pt);
    }
    if (db) {
      System.out.println(" ipts=" + Tools.d(ipts));
    }
  }
Ejemplo n.º 23
0
  /**
   * method to invoke with a filename or URL of a picture that is to be loaded and scaled in a new
   * thread. This is handy to update the screen while the loading chuggs along in the background.
   * Make sure you invoked setScaleFactor or setScaleSize before invoking this method.
   *
   * <p>Step 1: Am I already loading what I need somewhere? If yes -> use it. Has it finished
   * loading? If no -> wait for it If yes -> use it Else -> load it
   *
   * @param priority The Thread priority
   * @param imageUrl The URL of the image you want to load
   * @param rotation The rotation 0-360 that the image should be put through after loading.
   */
  public void loadAndScalePictureInThread(URL imageUrl, int priority, double rotation) {
    this.imageUrl = imageUrl;

    boolean alreadyLoading = false;
    Tools.log(
        "ScalablePicture.loadAndScalePictureInThread: checking if picture "
            + imageUrl
            + " is already being loaded.");
    if ((sourcePicture != null)
        && (sourcePicture.getUrl().toString().equals(imageUrl.toString()))) {
      Tools.log(
          "ScalablePicture.loadAndScalePictureInThread: the SourcePicture is already loading the sourcePictureimage");
      alreadyLoading = true;
    } else if (PictureCache.isInCache(imageUrl)) {
      // in case the old image has a listener connected remove it
      //  fist time round the sourcePicture is still null therefore the if.
      if (sourcePicture != null) sourcePicture.removeListener(this);

      sourcePicture = PictureCache.getSourcePicture(imageUrl);
      String status = sourcePicture.getStatusMessage();
      if (status == null) status = "";
      Tools.log("ScalablePicture.loadAndScalePictureInThread: Picture in cache! Status: " + status);

      if (sourcePicture.getRotation() == rotation) {
        alreadyLoading = true;
        Tools.log(
            "ScalablePicture.loadAndScalePictureInThread: Picture was even rotated to the correct angle!");
      } else {
        alreadyLoading = false;
        Tools.log(
            "ScalablePicture.loadAndScalePictureInThread: Picture was in cache but with wrong rotation. Forcing reload.");
      }
    }

    if (alreadyLoading) {
      switch (sourcePicture.getStatusCode()) {
        case SourcePicture.UNINITIALISED:
          alreadyLoading = false;
          Tools.log(
              "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: UNINITIALISED");
          break;
        case SourcePicture.ERROR:
          alreadyLoading = false;
          Tools.log("ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ERROR");
          break;
        case SourcePicture.LOADING:
          Tools.log("ScalablePicture.loadAndScalePictureInThread: pictureStatus was: LOADING");
          sourcePicture.addListener(this);
          setStatus(LOADING, "Loading: " + imageUrl.toString());
          sourceLoadProgressNotification(
              SourcePicture.LOADING_PROGRESS, sourcePicture.getPercentLoaded());
          scaleAfterLoad = true;
          break;
        case SourcePicture.ROTATING:
          Tools.log("ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ROTATING");
          setStatus(LOADING, "Rotating: " + imageUrl.toString());
          sourceLoadProgressNotification(
              SourcePicture.LOADING_PROGRESS, sourcePicture.getPercentLoaded());
          scaleAfterLoad = true;
          break;
        case SourcePicture.READY:
          Tools.log(
              "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: READY. Sending SCALING status.");
          setStatus(SCALING, "Scaling: " + imageUrl.toString());
          createScaledPictureInThread(priority);
          break;
        default:
          Tools.log(
              "ScalablePicture.loadAndScalePictureInThread: Don't know what status this is:"
                  + Integer.toString(sourcePicture.getStatusCode()));
          break;
      }
    }

    // if the image is not already there then load it.
    if (!alreadyLoading) {
      if (sourcePicture != null) sourcePicture.removeListener(this);
      sourcePicture = new SourcePicture();
      sourcePicture.addListener(this);
      setStatus(LOADING, "Loading: " + imageUrl.toString());
      scaleAfterLoad = true;
      sourcePicture.loadPictureInThread(imageUrl, priority, rotation);
      // when the thread is done it sends a sourceStatusChange message to us
    }
  }
Ejemplo n.º 24
0
  private void construct(EdDisc a, EdDisc b) {
    this.discA = a;
    this.discB = b;

    if (EdDisc.partiallyDisjoint(a, b)) {

      // if (!UHullMain.oldBitanMethod())
      {
        final boolean db = false;

        if (a.getRadius() == b.getRadius()) {
          FPoint2 oa = a.getOrigin(), ob = b.getOrigin();

          FPoint2 n = new FPoint2(-(ob.y - oa.y), ob.x - oa.x);
          n.normalize();
          n.x *= a.getRadius();
          n.y *= a.getRadius();
          seg = new DirSeg(FPoint2.add(oa, n, null), FPoint2.add(ob, n, null));
          return;
        }

        boolean swap = a.getRadius() > b.getRadius();

        if (swap) {
          b = (EdDisc) discA;
          a = (EdDisc) discB;
        }

        if (db && T.update())
          T.msg(
              "BiTangent construct, arad="
                  + Tools.f(a.getRadius())
                  + " brad="
                  + Tools.f(b.getRadius())
                  + " swap="
                  + swap
                  + " origin.a="
                  + T.show(a.getOrigin()));

        FPoint2 oa = a.getOrigin();
        FPoint2 ob = b.getOrigin();

        double U = ob.x, V = ob.y;
        double A = oa.x - U, B = oa.y - V;
        double R1 = a.getRadius();
        double R2 = b.getRadius();
        double S = R2 - R1;

        double x1, y1, x2, y2;
        x1 = A;
        y1 = B;

        boolean secondRoot;
        boolean altSlope = Math.abs(B) < Math.abs(A);
        if (!altSlope) {

          double C1 = S * S / B, C2 = -A / B;
          double qA = 1 + C2 * C2, qB = 2 * C1 * C2, qC = C1 * C1 - S * S;
          double root = Math.sqrt(qB * qB - 4 * qA * qC);
          x2 = (-qB - root) / (2 * qA);
          y2 = C1 + C2 * x2;

          secondRoot = MyMath.sideOfLine(x2, y2, A, B, 0, 0) < 0;

          if (swap ^ secondRoot) {
            x2 = (-qB + root) / (2 * qA);
            y2 = C1 + C2 * x2;
          }
        } else {

          double C1 = S * S / A, C2 = -B / A;
          double qA = 1 + C2 * C2, qB = 2 * C1 * C2, qC = C1 * C1 - S * S;
          double root = Math.sqrt(qB * qB - 4 * qA * qC);
          y2 = (-qB - root) / (2 * qA);
          x2 = C1 + C2 * y2;

          secondRoot = MyMath.sideOfLine(x2, y2, A, B, 0, 0) < 0;

          if (swap ^ secondRoot) {
            y2 = (-qB + root) / (2 * qA);
            x2 = C1 + C2 * y2;
          }
        }
        // now grow both discs back to r1, r2

        double tx = U;
        double ty = V;

        //        if (S == 0) {
        //          FPoint2 unit = new FPoint2(-A, -B);
        //          if (swap) {
        //            unit.x = -unit.x;
        //            unit.y = -unit.y;
        //          }
        //          unit.normalize();
        //          tx += -unit.y * R1;
        //          ty += unit.x * R1;
        //        } else
        {
          double F = R1 / S;
          tx += x2 * F;
          ty += y2 * F;
        }

        if (db && T.update())
          T.msg("adding offset to both points: " + tx + ", " + ty + T.show(new FPoint2(tx, ty)));
        x1 += tx;
        y1 += ty;
        x2 += tx;
        y2 += ty;
        FPoint2 p1 = new FPoint2(x1, y1);
        FPoint2 p2 = new FPoint2(x2, y2);
        if (swap) {
          FPoint2 tmp = p1;
          p1 = p2;
          p2 = tmp;
        }

        seg = new DirSeg(p1, p2);

        if (db && T.update())
          T.msg(
              "swap="
                  + swap
                  + " altSlope="
                  + altSlope
                  + " secondRoot="
                  + secondRoot
                  + " dirseg="
                  + EdSegment.showDirected(p1, p2));
      }
      //      else {
      //
      //        double th = calcTheta(a, b);
      //        LineEqn eqn = new LineEqn(a.polarPoint(th + Math.PI / 2), th);
      //        double ta = eqn.parameterFor(a.getOrigin());
      //        double tb = eqn.parameterFor(b.getOrigin());
      //        seg = new DirSeg(eqn.pt(ta), eqn.pt(tb));
      //
      //      }
    }
  }
Ejemplo n.º 25
0
  /**
   * Construct a string
   *
   * @param javaMode : if true, generates java code to construct it
   * @return String
   */
  private String toString(boolean javaMode) {

    StringBuilder sb = new StringBuilder();
    //    sb.setLength(0);

    if (javaMode) {
      sb.append(
          "new Hyperbola(new FPoint2("
              + foci[RIGHT].x
              + ","
              + foci[RIGHT].y
              + "), new FPoint2("
              + foci[LEFT].x
              + ","
              + foci[LEFT].y
              + "), new FPoint2("
              + pt.x
              + ","
              + pt.y
              + "));");
    } else {
      sb.append("hyperbola: ");
      if (!valid) {
        sb.append("***INVALID***");
      } else {
        sb.append(
            "f(r)="
                + foci[RIGHT]
                + " f(l)="
                + foci[LEFT]
                + " a="
                + Tools.f(a)
                + " c="
                + Tools.f(c));
        sb.append(" flip=" + Tools.f(flipped()));
        if (visSeg != null) {
          sb.append("\nVisible segments: ");
          for (int i = 0; i < visSeg.size(); i += 2) {
            double t0 = 0, t1 = 0;
            if (flipped()) {
              int j = visSeg.size() - i - 2;
              t0 = toExt(visSeg.getDouble(j + 1));
              t1 = toExt(visSeg.getDouble(j));
            } else {
              t0 = visSeg.getDouble(i);
              t1 = visSeg.getDouble(i + 1);
            }

            sb.append("<");
            sb.append(Tools.f(t0));
            sb.append("..");

            sb.append(Tools.f(t1));
            sb.append("> ");
          }
          sb.append("\n");
        }
      }
    }
    return sb.toString();
  }