From fa1f5a0dd0b682dc52a80a91a9c3bc1fa55406b8 Mon Sep 17 00:00:00 2001 From: Ray Greenwell Date: Thu, 15 Dec 2005 02:49:28 +0000 Subject: [PATCH] Added getClosest() for finding the closest direction in a list to one specified. I'm not sure I'll actually end up needing this, but it's handy for what I'm currently toying with. git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@3783 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- .../com/threerings/util/DirectionUtil.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/java/com/threerings/util/DirectionUtil.java b/src/java/com/threerings/util/DirectionUtil.java index 79b23b922..99254300f 100644 --- a/src/java/com/threerings/util/DirectionUtil.java +++ b/src/java/com/threerings/util/DirectionUtil.java @@ -23,6 +23,8 @@ package com.threerings.util; import java.awt.Point; +import com.samskivert.util.IntListUtil; + /** * Direction related utility functions. */ @@ -133,6 +135,44 @@ public class DirectionUtil implements DirectionCodes return rotateCW(direction, FINE_CW_ROTATE.length/2); } + /** + * Get the direction closest to the specified direction, out of + * the directions in the possible list (preferring a clockwise match). + */ + public static int getClosest (int direction, int[] possible) + { + return getClosest(direction, possible, true); + } + + /** + * Get the direction closest to the specified direction, out of + * the directions in the possible list. + * + * @param preferCW whether to prefer a clockwise match or a + * counter-clockwise match. + */ + public static int getClosest (int direction, int[] possible, + boolean preferCW) + { + // rotate a tick at a time, looking for matches + int first = direction; + int second = direction; + for (int ii = 0; ii <= FINE_DIRECTION_COUNT / 2; ii++) { + if (IntListUtil.contains(possible, first)) { + return first; + } + + if (ii != 0 && IntListUtil.contains(possible, second)) { + return second; + } + + first = preferCW ? rotateCW(first, 1) : rotateCCW(first, 1); + second = preferCW ? rotateCCW(second, 1) : rotateCW(second, 1); + } + + return NONE; + } + /** * Returns which of the eight compass directions that point * b lies in from point a as one of the