Java Code Examples for javafx.geometry.Bounds#contains()

The following examples show how to use javafx.geometry.Bounds#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MouseUtils.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param screenBounds boundary box in screen coordinates
 * @param mouseLoc mouse screen coordinate
 * @return maximum external distance (Manhattan-Norm) from the boundary rectangle
 */
public static double mouseOutsideBoundaryBoxDistance(final Bounds screenBounds, final Point2D mouseLoc) {
    if (screenBounds.contains(mouseLoc)) {
        return 0;
    }
    final double x = mouseLoc.getX();
    final double y = mouseLoc.getY();
    final double minX;
    if (x < screenBounds.getMinX()) {
        minX = screenBounds.getMinX() - x;
    } else if (x > screenBounds.getMaxX()) {
        minX = x - screenBounds.getMaxX();
    } else {
        minX = 0.0;
    }
    final double minY;
    if (y < screenBounds.getMinY()) {
        minY = screenBounds.getMinY() - y;
    } else if (y > screenBounds.getMaxY()) {
        minY = y - screenBounds.getMaxY();
    } else {
        minY = 0.0;
    }

    return Math.max(minX, minY);
}
 
Example 2
Source File: MouseUtils.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param screenBounds boundary box in screen coordinates
 * @param mouseLoc mouse screen coordinate
 * @return minimum internal distance (Manhattan-Norm) from the boundary rectangle
 */
public static double mouseInsideBoundaryBoxDistance(final Bounds screenBounds, final Point2D mouseLoc) {
    if (!screenBounds.contains(mouseLoc)) {
        return 0;
    }
    final double x = mouseLoc.getX();
    final double y = mouseLoc.getY();
    final double minX;
    if (x > screenBounds.getMinX() && x < screenBounds.getMaxX()) {
        minX = Math.min(x - screenBounds.getMinX(), screenBounds.getMaxX() - x);
    } else {
        minX = 0.0;
    }
    final double minY;
    if (y > screenBounds.getMinY() && y < screenBounds.getMaxY()) {
        minY = Math.min(y - screenBounds.getMinY(), screenBounds.getMaxY() - y);
    } else {
        minY = 0.0;
    }

    return Math.min(minX, minY);
}
 
Example 3
Source File: JavaFXElementPropertyAccessor.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
protected int getIndexAt(ListView<?> listView, Point2D point) {
    if (point == null) {
        return listView.getSelectionModel().getSelectedIndex();
    }
    point = listView.localToScene(point);
    Set<Node> lookupAll = getListCells(listView);
    ListCell<?> selected = null;
    for (Node cellNode : lookupAll) {
        Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
        if (boundsInScene.contains(point)) {
            selected = (ListCell<?>) cellNode;
            break;
        }
    }
    if (selected == null) {
        return -1;
    }
    return selected.getIndex();
}
 
Example 4
Source File: JavaFXElementPropertyAccessor.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public int getRowAt(TreeView<?> treeView, Point2D point) {
    if (point == null) {
        return treeView.getSelectionModel().getSelectedIndex();
    }
    point = treeView.localToScene(point);
    int itemCount = treeView.getExpandedItemCount();
    @SuppressWarnings("rawtypes")
    List<TreeCell> cells = new ArrayList<>();
    for (int i = 0; i < itemCount; i++) {
        cells.add(getCellAt(treeView, i));
    }
    TreeCell<?> selected = null;
    for (Node cellNode : cells) {
        Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
        if (boundsInScene.contains(point)) {
            selected = (TreeCell<?>) cellNode;
            break;
        }
    }
    if (selected == null) {
        return -1;
    }
    return selected.getIndex();
}
 
Example 5
Source File: DataPointTooltip.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
private DataPoint findDataPoint(final MouseEvent event, final Bounds plotAreaBounds) {
    if (!plotAreaBounds.contains(event.getX(), event.getY())) {
        return null;
    }

    final Point2D mouseLocation = getLocationInPlotArea(event);

    Chart chart = getChart();
    return findNearestDataPointWithinPickingDistance(chart, mouseLocation);
}
 
Example 6
Source File: Zoomer.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
private boolean isMouseEventWithinCanvas(final MouseEvent mouseEvent) {
    final Canvas canvas = getChart().getCanvas();
    // listen to only events within the canvas
    final Point2D mouseLoc = new Point2D(mouseEvent.getScreenX(), mouseEvent.getScreenY());
    final Bounds screenBounds = canvas.localToScreen(canvas.getBoundsInLocal());
    return screenBounds.contains(mouseLoc);
}
 
Example 7
Source File: Zoomer.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
private boolean isMouseEventWithinCanvas(final ScrollEvent mouseEvent) {
    final Canvas canvas = getChart().getCanvas();
    // listen to only events within the canvas
    final Point2D mouseLoc = new Point2D(mouseEvent.getScreenX(), mouseEvent.getScreenY());
    final Bounds screenBounds = canvas.localToScreen(canvas.getBoundsInLocal());
    return screenBounds.contains(mouseLoc);
}
 
Example 8
Source File: EditDataSet.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
protected boolean isMouseEventWithinCanvas(final MouseEvent mouseEvent) {
    final Canvas canvas = getChart().getCanvas();
    // listen to only events within the canvas
    final Point2D mouseLoc = new Point2D(mouseEvent.getScreenX(), mouseEvent.getScreenY());
    final Bounds screenBounds = canvas.localToScreen(canvas.getBoundsInLocal());
    return screenBounds.contains(mouseLoc);
}
 
Example 9
Source File: FXEventQueueDevice.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void checkHit(Node child, double x, double y, List<Node> hits, String indent) {
    Bounds boundsInParent = child.getBoundsInParent();
    if (boundsInParent.contains(x, y)) {
        hits.add(child);
        if (!(child instanceof Parent)) {
            return;
        }
        ObservableList<Node> childrenUnmodifiable = ((Parent) child).getChildrenUnmodifiable();
        for (Node node : childrenUnmodifiable) {
            checkHit(node, x, y, hits, "    " + indent);
        }
    }
}
 
Example 10
Source File: JavaFXElementPropertyAccessor.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private TableCell<?, ?> getTableCellAt(TableView<?> tableView, Point2D point) {
    point = tableView.localToScene(point);
    Set<Node> lookupAll = getTableCells(tableView);
    TableCell<?, ?> selected = null;
    for (Node cellNode : lookupAll) {
        Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
        if (boundsInScene.contains(point)) {
            selected = (TableCell<?, ?>) cellNode;
            break;
        }
    }
    return selected;
}
 
Example 11
Source File: JavaFXElementPropertyAccessor.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public TreeTableCell<?, ?> getTreeTableCellAt(TreeTableView<?> treeTableView, Point2D point) {
    point = treeTableView.localToScene(point);
    Set<Node> lookupAll = getTreeTableCells(treeTableView);
    TreeTableCell<?, ?> selected = null;
    for (Node cellNode : lookupAll) {
        Bounds boundsInScene = cellNode.localToScene(cellNode.getBoundsInLocal(), true);
        if (boundsInScene.contains(point)) {
            selected = (TreeTableCell<?, ?>) cellNode;
            break;
        }
    }
    return selected;
}
 
Example 12
Source File: ShotDetector.java    From ShootOFF with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Alert the canvas tied to the camera the instantiation of this detector is
 * tied to of a new shot. This method preprocesses the shot by ensuring it
 * is not of an ignored color, it has the appropriate translation for
 * projectors if it's a shot on the arena, it has the appropriate
 * translation if the display resolution differs from the camera resolution,
 * and it is not a duplicate shot.
 * 
 * @param color
 *            the color of the detected shot (red or green)
 * @param x
 *            the exact x coordinate of the shot in the video frame it was
 *            detected in
 * @param y
 *            the exact y coordinate of the shot in the video frame it was
 *            detected in
 * @param timestamp
 *            the timestamp of the shot not adjusted for the shot timer
 * @param scaleShot
 *            <code>true</code> if the shot needs to be scaled if the
 *            display resolution differs from the webcam's resolution. This
 *            is always <code>false</code> for click-to-shoot.
 * @return <code>true</code> if the shot wasn't rejected during
 *         preprocessing
 */
public boolean addShot(ShotColor color, double x, double y, long timestamp, boolean scaleShot) {
	if (!checkIgnoreColor(color)) return false;

	final Shot shot = new Shot(color, x, y, cameraManager.cameraTimeToShotTime(timestamp),
			cameraManager.getFrameCount());

	if (config.isAdjustingPOI())
	{
		if (logger.isTraceEnabled())
		{
			logger.trace("POI Adjustment: x {} y {}", config.getPOIAdjustmentX().get(), config.getPOIAdjustmentY().get());
			logger.trace("Adjusting offset via POI setting, coords were {} {} now {} {}", x, y, x+config.getPOIAdjustmentX().get(), y+config.getPOIAdjustmentY().get());
		}
		
		shot.adjustPOI(config.getPOIAdjustmentX().get(), config.getPOIAdjustmentY().get());

	}
	
	BoundsShot bShot = new BoundsShot(shot);

	if (scaleShot && (cameraManager.isLimitingDetectionToProjection() || cameraManager.isCroppingFeedToProjection())
			&& cameraManager.getProjectionBounds().isPresent()) {
		final Bounds b = cameraManager.getProjectionBounds().get();

		if (handlesBounds()) {
			bShot.adjustBounds(b.getMinX(), b.getMinY());
		} else {
			if (cameraManager.isLimitingDetectionToProjection() && !b.contains(x, y)) return false;
		}
	}
	
	DisplayShot dShot = new DisplayShot(bShot, config.getMarkerRadius());
	

	// If the shot didn't come from click to shoot (cameFromCanvas) and the
	// resolution of the display and feed differ, translate shot coordinates
	if (scaleShot && (config.getDisplayWidth() != cameraManager.getFeedWidth()
			|| config.getDisplayHeight() != cameraManager.getFeedHeight())) {
		dShot.setDisplayVals(config.getDisplayWidth(), config.getDisplayHeight(), cameraManager.getFeedWidth(),
				cameraManager.getFeedHeight());
	}

	if (!checkDuplicate(dShot)) return false;

	submitShot(dShot);

	return true;
}
 
Example 13
Source File: TargetView.java    From ShootOFF with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Optional<Hit> isHit(double x, double y) {
	if (targetGroup.getBoundsInParent().contains(x, y)) {
		// Target was hit, see if a specific region was hit
		for (int i = targetGroup.getChildren().size() - 1; i >= 0; i--) {
			final Node node = targetGroup.getChildren().get(i);

			if (!(node instanceof TargetRegion)) continue;

			final Bounds nodeBounds = targetGroup.getLocalToParentTransform().transform(node.getBoundsInParent());

			final int adjustedX = (int) (x - nodeBounds.getMinX());
			final int adjustedY = (int) (y - nodeBounds.getMinY());

			if (nodeBounds.contains(x, y)) {
				// If we hit an image region on a transparent pixel,
				// ignore it
				final TargetRegion region = (TargetRegion) node;

				// Ignore regions where ignoreHit tag is true
				if (region.tagExists(TargetView.TAG_IGNORE_HIT)
						&& Boolean.parseBoolean(region.getTag(TargetView.TAG_IGNORE_HIT)))
					continue;

				if (region.getType() == RegionType.IMAGE) {
					// The image you get from the image view is its
					// original size. We need to resize it if it has
					// changed size to accurately determine if a pixel
					// is transparent
					final Image currentImage = ((ImageRegion) region).getImage();

					if (adjustedX < 0 || adjustedY < 0) {
						logger.debug(
								"An adjusted pixel is negative: Adjusted ({}, {}), Original ({}, {}), "
										+ " nodeBounds.getMin ({}, {})",
								adjustedX, adjustedY, x, y, nodeBounds.getMaxX(),
								nodeBounds.getMinY());
						return Optional.empty();
					}

					if (Math.abs(currentImage.getWidth() - nodeBounds.getWidth()) > .0000001
							|| Math.abs(currentImage.getHeight() - nodeBounds.getHeight()) > .0000001) {

						final BufferedImage bufferedOriginal = SwingFXUtils.fromFXImage(currentImage, null);

						final java.awt.Image tmp = bufferedOriginal.getScaledInstance((int) nodeBounds.getWidth(),
								(int) nodeBounds.getHeight(), java.awt.Image.SCALE_SMOOTH);
						final BufferedImage bufferedResized = new BufferedImage((int) nodeBounds.getWidth(),
								(int) nodeBounds.getHeight(), BufferedImage.TYPE_INT_ARGB);

						final Graphics2D g2d = bufferedResized.createGraphics();
						g2d.drawImage(tmp, 0, 0, null);
						g2d.dispose();

						try {
							if (adjustedX >= bufferedResized.getWidth() || adjustedY >= bufferedResized.getHeight()
									|| bufferedResized.getRGB(adjustedX, adjustedY) >> 24 == 0) {
								continue;
							}
						} catch (final ArrayIndexOutOfBoundsException e) {
							final String message = String.format(
									"Index out of bounds while trying to find adjusted coordinate (%d, %d) "
											+ "from original (%.2f, %.2f) in adjusted BufferedImage for target %s "
											+ "with width = %d, height = %d",
									adjustedX, adjustedY, x, y, getTargetFile().getPath(),
									bufferedResized.getWidth(), bufferedResized.getHeight());
							logger.error(message, e);
							return Optional.empty();
						}
					} else {
						if (adjustedX >= currentImage.getWidth() || adjustedY >= currentImage.getHeight()
								|| currentImage.getPixelReader().getArgb(adjustedX, adjustedY) >> 24 == 0) {
							continue;
						}
					}
				} else {
					// The shot is in the bounding box but make sure it
					// is in the shape's
					// fill otherwise we can get a shot detected where
					// there isn't actually
					// a region showing
					final Point2D localCoords = targetGroup.parentToLocal(x, y);
					if (!node.contains(localCoords)) continue;
				}

				return Optional.of(new Hit(this, (TargetRegion) node, adjustedX, adjustedY));
			}
		}
	}

	return Optional.empty();
}
 
Example 14
Source File: CanvasManager.java    From ShootOFF with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void addShot(DisplayShot shot, boolean isMirroredShot) {
	if (!isMirroredShot) {
		final Optional<ShotProcessor> rejectingProcessor = processShot(shot);
		if (rejectingProcessor.isPresent()) {
			recordRejectedShot(shot, rejectingProcessor.get());
			return;
		} else {
			notifyShot(shot);
		}

		// TODO: Add separate infrared sound or switch config to read
		// "red/infrared"
		if (config.useRedLaserSound()
				&& (ShotColor.RED.equals(shot.getColor()) || ShotColor.INFRARED.equals(shot.getColor()))) {
			TrainingExerciseBase.playSound(config.getRedLaserSound());
		} else if (config.useGreenLaserSound() && ShotColor.GREEN.equals(shot.getColor())) {
			TrainingExerciseBase.playSound(config.getGreenLaserSound());
		}
	}

	// Create a shot entry to show the shot's data
	// in the shot timer table if the shot timer
	// table is in use
	if (shotEntries != null) {
		final Optional<Shot> lastShot;

		if (shotEntries.isEmpty()) {
			lastShot = Optional.empty();
		} else {
			lastShot = Optional.of(shotEntries.get(shotEntries.size() - 1).getShot());
		}

		final ShotEntry shotEntry;
		if (hadMalfunction || hadReload) {
			shotEntry = new ShotEntry(shot, lastShot, config.getShotTimerRowColor(), hadMalfunction, hadReload);
			hadMalfunction = false;
			hadReload = false;
		} else {
			shotEntry = new ShotEntry(shot, lastShot, config.getShotTimerRowColor(), false, false);
		}

		try {
			shotEntries.add(shotEntry);
		} catch (final NullPointerException npe) {
			logger.error("JDK 8094135 exception", npe);
			jdk8094135Warning();
		}
	}

	shots.add(shot);
	drawShot(shot);

	final Optional<String> videoString = createVideoString(shot);

	boolean passedToArena = false;
	boolean processedShot = false;

	if (arenaPane.isPresent() && !(this instanceof MirroredCanvasManager) && projectionBounds.isPresent()) {
		final Bounds b = projectionBounds.get();

		if (b.contains(shot.getX(), shot.getY())) {
			passedToArena = true;


			final ArenaShot arenaShot = new ArenaShot(shot);
			
			scaleShotToArenaBounds(arenaShot);

			processedShot = arenaPane.get().getCanvasManager().addArenaShot(arenaShot, videoString, isMirroredShot);
		}
	}

	// If the arena canvas handled the shot, we don't need to do anything
	// else
	if (passedToArena || processedShot) return;

	final Optional<TrainingExercise> currentExercise = config.getExercise();
	final Optional<Hit> hit = checkHit(shot, videoString, isMirroredShot);
	if (hit.isPresent() && hit.get().getHitRegion().tagExists("command")) executeRegionCommands(hit.get(), isMirroredShot);

	if (currentExercise.isPresent() && !processedShot) {
		// If the canvas is mirrored, use the one without the camera manager
		// for exercises because that is the one for the arena window.
		// If we use the arena tab canvas manager the targets will be
		// copies and will not be the versions of the targets added
		// by exercises.
		if ((this instanceof MirroredCanvasManager) && cameraManager == null) {
			currentExercise.get().shotListener(shot, hit);
		} else if (!(this instanceof MirroredCanvasManager)) {
			currentExercise.get().shotListener(shot, hit);
		}
	}
}
 
Example 15
Source File: ZoneSelector.java    From AnchorFX with GNU Lesser General Public License v3.0 4 votes vote down vote up
public boolean overMe(double x, double y)
{
    Bounds screenBounds = localToScreen(getBoundsInLocal());
    return (screenBounds.contains(x, y));
}
 
Example 16
Source File: DockNode.java    From AnchorFX with GNU Lesser General Public License v3.0 3 votes vote down vote up
public boolean checkForTarget(double x, double y) {

        Point2D screenToScenePoint = getScene().getRoot().screenToLocal(x, y);
        Bounds sceneBounds = getSceneBounds();
        return sceneBounds.contains(screenToScenePoint.getX(), screenToScenePoint.getY());

    }