This question already has answers here:
Closest point on a cubic Bezier curve?
(6 answers)
Closed 4 years ago.
My approach was to loop trough the curve and check the mouse distance to various points
But the points get closer together as the curve get steeper, and if the mouse distance threshold is too high it prioritizes the first point in the loop instead of the closet to the mouse.
is there a way to get uniform points in it? Or to check if the mouse is over the Bézier curve and get the position in the curve?
I do it like this:
subdivide you curve to few chunks
tne number of chunks depends on the order of curve. As I usually use cubics I empirically find out that ~8 chunks is enough (for my purposes).
compute the closest point to a chunk
So simply handle each chunk as line and compute closest point on the line to the mouse position (minimal perpendicular distance). By computing it for each chunk and remember the closest one.
Now after this we know which chunk contain the "closest" point so from the intersection between line and perpendicular line to it going through mouse position from previous step we should have a parameter u=<0,1> telling us where on the chunk line the closest point is and we also know the curve parameter t of both endpoints of the chunk line (t0,t1). From this we can approximate t for the closest point simply by doing this:
t = t0 + (t1-t0)*u
On the image t0=0.25 and t1=0.375. This is sometimes enough but if you want better solution so after this just set:
dt = (t1-t0)/4
t0 = t-dt
t1 = t+dt
Use the t0,t,t1 to compute 3 endpoints of 2 chunks and look for the closest point again. You can recursively do this few times as with each iteration you increase precision of the result
The perpendicular distance of point to a line is computed by computing intersection between the line and axis perpendicular to it going through the point in question. So if the line is defined by endpoints p0,p1 and the queried point (mouse) is q then the axis in 2D will be:
dp=p1-p0 // line direction
dq=(dp.y,-dp.x) // axis direction is perpendicular to dp
dq/= |dq| // normalize
p(u) = p0+dp*u // point on line
p(v) = q +dq*v // point on axis
u = <0,1> // parameter on line
v = <-inf,+inf> // parameter on axis
And we want to know u,v from
p0+dp*u = q +dq*v
which is system of 2 linear equations in 2D. In 3D you need to exploit cross product to obtain the dq and the system would contain 3 equations. Solving this sytem will give you u,v where u will tell you where in the chunk the closest point is and |v| is the perpendicular distance itself. Do not forget that if u is not in the range <0,1> then you have to use closer endpoint of the line as the closest point.
The system can be solved either algebraically (but beware the edge cases as there are 2 solutions for the equations in 2D) or use inverse matrix...
There are two main approaches - subdivision of curve into small line segments and analytical solution.
For the second case you have to build polynomial for squared distance from point to curve depending on parameter t, differentiate it, and find zeros of result (5-th order polynomial). Then choose minimum from distances to point at t[i], t=0, t=1.
Another point of view - get projection of point onto curve, so curve tangent in this point is perpendicular to vector point-curvepoint, it should give the same expression.
About uniform points - it is rather hard problem because curve length could not be calculated analytically. But subdivision gives quite good approximation.
Related
I have array of 4 points and I want to check whether these points will create a rectangle or not. If it will create a rectangle than calculate area of this.
x,y value of point can be positive or negative or mix of it.
You can calculate the six distances between the four points.
Use Pythagoras for this.
If they result in three pairs of equal non-zero distances it is a rectangle.
The product of the shorter two is its area.
Make sure not to fall into rounding error traps; so use an epsilon criterion when comparing for 'equality' as floating point numbers have a tendency to not be equal even if they should be mathematically!
I have a number of non-coplanar 3D points and I want to calculate the nearest plane to them (They will always form a rough plane but with some small level of variation). This can be done by solving simultaneous linear equations, one for each point, of the form:
"Ax + By + Cz + D = 0"
The problem I'm having at the moment is twofold.
Firstly since the points are 3D floats they can't be relied on to be precise due to rounding errors.
Secondly all of the methods to solving linear equations programatically that I have found thus far involve using NXN matrices which severely limits what I would be able to do given that I have 4 unknowns and any number of linear equations (due to the variation in the number of 3D points).
Does anyone have a decent way to either solve the simultaneous linear equations without these constraints or, alternatively, a better way to calculate the nearest plane to non-coplanar points? (The precision of the plane calculation is not too much of a concern)
Thanks! :)
If your points are all close to the plane, you have a choice between ordinary least squares (where you see Z as a function of two independent variables X and Y and you minimize the sum of squared vertical distances to the plane), or total least squares (all variables independent, minimize the sum of normal distances). The latter requires a 3x3 SVD. (See http://en.wikipedia.org/wiki/Total_least_squares, unfortunately not the easiest presentation.)
If some of the points are outliers, you will need to resort to robust fitting methods. One of them is RANSAC: choose three points are random, build their plane and compute the sum of distances of all points to the plane, as a measure of fitness. Keep the best result after N drawings.
There are numerical methods for linear regression, which calculates the nearest line y=mx+c to a set of points. Your solution will be similar, only it has one more dimension and is thus a "planar regression".
If you don't care the mathematical accuracy of the algorithm and just want to get a rough result, then perhaps you'd randomly 3 points to construct a plane vector, then adjust it incrementally as you go through the rest of the points. Just some thoughts...
I need to find the distance of multiple points to a curve of the form: f(x) = a^(k^(bx))
My first option was using its derivative, using a line of the form with the inverse of the derivative, giving it coordinates of the Point and intersecting it with the original curve. Finally, we calculate the distance between points with simple geometry.
That's the mathematical process that I usually follow. I need to save time (since I'm doing a genetic algorithms program) so I need an efficient way to do this. Ideas?
The distance between a point (c,d) and your curve is the minimum of the function
sqrt((c-x)^2 + (d-a^(k^(bx)))^2)
To find its minimum, we can forget about the sqrt and look at the first derivative. Find out where it's 0 (it has to be the minimal distance, as there's no maximum distance). That gives you the x coordinate of the nearest point on the curve. To get the distance you need to calculate the y coordinate, and then calculate the distance to the point (you can just calculate the distance function at that x, it's the same thing).
Repeat for each of your points.
The first derivative of the distance function, is, unfortunately, a kind of bitch. Using Wolfram's derivator, the result is hopefully (if I haven't made any copying errors):
dist(x)/dx = 2(b * lna * lnk * k^(bx) * a^(k^(bx)) * (a^(k^(bx)) - d) - c + x)
To find distance from point to curve it's not a simple task, for that you need to find the global of function where f(x) is the function which determine your curve.
For that goal you could use:
Simplex method
Nelder_Mead_method
gradient_descent
This methods implemented in many libraries like Solver Foundation, NMath etc.
I would like to know if is there any way to determine if a cone is intersecting with a (finite) line segment. The cone is actually a circle located at P(x,y) with theta degree field of view and radius r:
I'm trying to do it in C# but I don't have any idea how to that, so for now this is what I'm doing:
Check if the line segment is intersecting with the circle;
If the line segment is intersecting with the circle then I check every single point in the line segment using a function I found here.
But I don't think this is the best way to do it. Does anyone have an idea?
For additional info, I need this function to make some kind of simple vision simulator.
Working with Polar Co-ordinates might help. Here, instead of representing a point as (x,y) you represent it as (r, angle), where r is distance from origin and angle is the angle made with a chosen axis (which corresponds to angle 0).
In your case, if you set P(x,y) to be origin and one of the rays of the cone as angle = 0 and find polar co-ordinates of the end points of the line segment, say (r1, ang1) and (r2, ang2) then you need the following four conditions to be true for the line segment to be completely within (including boundary) of the cone.
r1 <= r
r2 <= r
ang1 <= theta
ang2 <= theta
where r is the radius of the cone and theta is the angle of view and you chose the axis so that rotating counter-clockwise gives a corresponding positive angle.
Switching between polar and (x,y) (called rectangular) coordinates is easy, and you can find it on the wiki link I gave above.
In order to determine if any point of the line segment intersects the curve you can use the polar equation of a line give here: Link
We can use the Polar normal form
R = p sec(ang - omega)
We can figure out p and omega given the two end-points of the line segment as follows:
We have
p = r1 * cos(ang1-omega) = r2*cos(ang2-omega)
Using cos(x-y) = cos(x)*cos(y) + sin(x)*sin(y) we get
[r1*cos(ang1) - r2*cos(ang2)] * cos(omega) = [r2*sin(ang2) - r1*sin(ang1)] * sin(omega)
Thus you can calculate tan(omega) = sin(omega)/cos(omega) and use arctan (the inverse function of tan) to get the value of omega. Once you know what omega is, you can solve for p.
Now we need to know if there is some (R, ang) combination on this line such that
R <= r
0 <= ang <= theta
min{ang1, ang2} <= ang <= max{ang1, ang2}
(Note r was radius of cone, and theta was the angle of view, ang1 was angle of P1 and ang2 was angle of P2).
The equation can be rewritten as
Rcos(ang-omega) = p
Now cos(ang-omega) is a very nicely behaved function in terms of monotonicity and you only need to consider it in the interval [min{ang1, ang2}, max{ang1, ang2}].
You should be able to do some manual manipulations first in order to simplify your code.
I will leave the rest to you.
I'd Google around for line/convex polygon intersection algorithms, your field of view is composed of a triangle and a part of a circle which can be approximated to any degree of accuracy by a convex polygon. Your first step might still be useful to rule out lines which go nowhere near the field of view.
If you keep it 2D like above, intersection can be calculated as follows:
Starting point of line segment is S1, ending is S2.
Left edge of code is a vector along the edge C1, right edge is C2, Origin of code is O.
Take the sign of the Z component of the cross product of the vector formed from (O to S1) and C1.
Take the sign of the Z component of the cross product of the vector fromed from (O to S2) and C1. If the signs differ, your starting and ending points are on opposite sides of C1 and therefore they must intersect. If not, do the same comparisons with C2 instead of C1.
If neither side's signs differ, no edge intersection.
In 3D, it's a bit more complicated. I've googled and found cone sphere intersection any number of times. Doing it for lines, would be very similiar, I just need to think about it for a bit :)
A quick google of 'cone line intersection' got all sorts of hits. The basic idea is to form a plane from the cone's origin and the starting and ending point of the line. Once you have that, you can take the angle between that plane and the cone's direction normal. If that angle is less than the angle of the spread on the cone, you have an intersection.
Bit of a weird one this. I'm rendering datasets on a map and need to split out points that have exactly the same long and lat. I had the idea of grouping my dataset by long and lat and where they are the same adjusting slightly so that they are visible as seperate entities on the map - rather than overlapping.
I'm using linq to group them and then enumerating my grouped items and I'd like to spiral the adjusted points around the orginal point (this is a requirement as I may have a few hundred points that are the same geographically) so that they spread out from the original point.
Does anyone know of a simple calculation i can add to my loop to adjust the items in this manner.
Thanks,
The math behind this is pretty simple. A circle can be represented by the sine function in the x-axis and the cosine function in the y-axis. Here's some pseudo-code:
int num = OverlappingPoints.Length;
for(int i = 0; i < num; ++i)
{
int radius = 50;
// using 2*pi because most math functions use radians... change 2*pi to 360 if your math library uses 360 degrees instead of 2*pi radians to represent a circle.
Map.Plot(OverlappingPoints[i].Latitude + radius*sin(2*pi*i/num),
OverlappingPoints[i].Latitude + radius*cos(2*pi*i/num));
}
That pseudo-code, if properly implemented, will draw the points out in a circle around the original point. Change the radius multiplier to the sine and cosine functions if you want to increase the radius of the circle. If you want the points to spiral out instead of making a circle, choose a number of points per circle revolution and replace num with that number in the sin/cos functions. Also, increase the radius after each loop iteration, probably by using a number and multiplying it by the loop index. (i.e. you could change radius to 50*i).
Hope this helps.