/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.scenegraph.g2d.snap; import java.awt.geom.Point2D; import java.io.Serializable; import org.simantics.scl.runtime.function.Function1; /** * @author Tuukka Lehtonen */ public class GridSnapAdvisor implements ISnapAdvisor, Serializable { private static final long serialVersionUID = 2411311098028229134L; double resolution; Function1 enabled; public GridSnapAdvisor(double resolution) { this.resolution = resolution; } public void setEnabledFunction(Function1 function) { this.enabled = function; } public void setResolution(double resolution) { this.resolution = resolution; } public double getResolution() { return resolution; } @Override public void snap(Point2D point) { if (enabled != null && !enabled.apply(null)) return; point.setLocation( Math.round(point.getX() / resolution) * resolution, Math.round(point.getY() / resolution) * resolution); } @Override public void snap(Point2D point, Point2D[] features) { if (enabled != null && !enabled.apply(null)) return; double dx = features[0].getX(); double dy = features[0].getY(); point.setLocation( Math.round((point.getX()-dx) / resolution) * resolution + dx, Math.round((point.getY()-dy) / resolution) * resolution + dy); } @Override public String toString() { return getClass().getSimpleName() + "[resolution=" + resolution + "]"; } @Override public int hashCode() { long temp = Double.doubleToLongBits(resolution); return (int) (temp ^ (temp >>> 32)); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GridSnapAdvisor other = (GridSnapAdvisor) obj; return Double.doubleToLongBits(resolution) != Double.doubleToLongBits(other.resolution); } }