tags:

views:

37

answers:

1

I have a canvas where I can draw, resize and move rectangles around.

I'm looking for an algorithm to prevent overlap and enable snapping of the rectangle I'm editing with other rectangles.

I'm tried different approaches but I couldn't get one working properly.

All my approaches are based on a simple loop that check the rectangle I'm editing (E) with other rectangles (O[n]).

Preventing overlap is not the problem, my problem is snapping as it can modify E while iterating O.

For example, if I'm moving E near O[1] it will snap with it, but this snap might create an overlap with O[0], overlap that won't be checked.

Before I start doing something recursive or too naïve, I was wondering if anybody knew a better approach.

+1  A: 

Would a two-pass approach help, e.g.

  1. In the first pass, check E against the O's and generate a short list of snap candidates.

  2. In the second pass, check each of the snap candidates for overlap against the O's.

If scanning the entire list of O's is prohibitively expensive (the effort grows linearly with the number of objects), consider a quad-tree for storing the objects and/or their vertices. A quadtree lets you narrow down on nearby points much faster.

Oren Trutner
Yea I can try that, I put that aside because I thought it would be a nightmare to check all combinaison of snap candidate, but after thinking a bit (not sure thought), for any rectangle combinaison you can have only 1 snap candidate that pass for x and 1 for y. This means I need 2 second passes, one with x candidate and a second with x/y (or y only if first pass fail). Not sure this is clear, but I think this should work.
Nicolas Goy