Intersection between two (perpendicular) lines - geometry

Let's assume I have a (infinite) line defined as y = z * x how can I find the closest point in this line to any given coordinate? Technically I seek the intersection between the initial line and its perpendicular passing on the given coordinate.

Let (x, zx) be a point on the given line, and (u, v) the outside point.
The squared distance is
(x - u)² + (zx - v)² = (z² + 1) x² - 2 (u + zv) x + u² + v²
and the minimum of this quadratic expression is achieved by
x = (u + zv) / (z² + 1)
giving you the orthogonal projection of the point onto the line.

I did a line intersection sample a few weeks a go. You could try that:
https://github.com/feldhaus/math-geometry-playground/blob/master/line-intersection/index.html

Related

find point where barycentric weights have a specific value

I have triangle: a, b, c. Each vertex has a value: va, vb, vc. In my software the user drags point p around inside and outside of this triangle. I use barycentric coordinates to determine the value vp at p based on va, vb, and vc. So far, so good.
Now I want to limit p so that vp is within range min and max. If a user chooses p where vp is < min or > max, how can I find the point closest to p where vp is equal to min or max, respectively?
Edit: Here is an example where I test each point. Light gray is within min/max. How can I find the equations of the lines that make up the min/max boundary?
a = 200, 180
b = 300, 220
c = 300, 300
va = 1
vb = 1.4
vc = 3.2
min = 0.5
max = 3.5
Edit: FWIW, so far first I get the barycentric coordinates v,w for p using the triangle vertices a, b, c (standard stuff I think, but looks like this). Then to get vp:
u = 1 - w - v
vp = va * u + vb * w + vc * v
That is all fine. My trouble is that I need the line equations for min/max so I can choose a new position for p when vp is out of range. The new position for p is the point closest to p on the min or max line.
Note that p is an XY coordinate and vp is a value for that coordinate determined by the triangle and the values at each vertex. min and max are also values. The two line equations I need will give me XY coordinates for which the values determined by the triangle are min or max.
It doesn't matter if barycentric coordinates are used in the solution.
The trick is to use the ratio of value to cartesian distance to extend each triangle edge until it hits min or max. Easier to see with a pic:
The cyan lines show how the triangle edges are extended, the green Xs are points on the min or max lines. With just 2 of these points we know the slope if the line. The yellow lines show connecting the Xs aligns with the light gray.
The math works like this, first get the value distance between vb and vc:
valueDistBtoC = vc - vb
Then get the cartesian distance from b to c:
cartesianDistBtoC = b.distance(c)
Then get the value distance from b to max:
valueDistBtoMax = max - vb
Now we can cross multiply to get the cartesian distance from b to max:
cartesianDistBtoMax = (valueDistBtoMax * cartesianDistBtoC) / valueDistBtoC
Do the same for min and also for a,b and c,a. The 6 points are enough to restrict the position of p.
Consider your triangle to actually be a 3D triangle, with points (ax,ay,va), (bx,by,vb), and (cx,cy,vc). These three points define a plane, containing all the possible p,vp triplets obtainable through barycentric interpolation.
Now think of your constraints as two other planes, at z>=max and z<=min. Each of these planes intersects your triangle's plane along an infinite line; the infinite beam between them, projected back down onto the xy plane, represents the area of points which satisfy the constraints. Once you have the lines (projected down), you can just find which (if either) is violated by a particular point, and move it onto that constraint (along a vector which is perpendicular to the constraint).
Now I'm not sure about your hexagon, though. That's not the shape I would expect.
Mathematically speaking the problem is simply a change of coordinates. The more difficult part is finding a good notation for the quantities involved.
You have two systems of coordinates: (x,y) are the cartesian coordinates of your display and (v,w) are the baricentric coordinates with respect to the vectors (c-a),(b-a) which determine another (non orthogonal) system.
What you need is to find the equation of the two lines in the (x,y) system, then it will be easy to project the point p on these lines.
To achieve this you could explicitly find the matrix to pass from (x,y) coordinates to (v,w) coordinates and back. The function you are using toBaryCoords makes this computation to find the coordinates (v,w) from (x,y) and we can reuse that function.
We want to find the coefficients of the transformation from world coordinates (x,y) to barycentric coordinates (v,w). It must be in the form
v = O_v + x_v * x + y_v * y
w = O_w + x_w * x + y_w * y
i.e.
(v,w) = (O_v,O_w) + (x_v,y_y) * (x,y)
and you can determine (O_v,O_w) by computing toBaryCoord(0,0), then find (x_v,x_w) by computing the coordinates of (1,0) and find (y_v,y_w)=toBaryCoord(1,0) - (O_v,O_w) and then find (y_v,y_w) by computing (y_v,y_w) = toBaryCoord(0,1)-(O_v,O_w).
This computation requires calling toBaryCoord three times, but actually the coefficients are computed inside that routine every time, so you could modify it to compute at once all six values.
The value of your function vp can be computed as follows. I will use f instead of v because we are using v for a baricenter coordinate. Hence in the following I mean f(x,y) = vp, fa = va, fb = vb, fc = vc.
You have:
f(v,w) = fa + (fb-fa)*v + (fc-fa)*w
i.e.
f(x,y) = fa + (fb-fa) (O_v + x_v * x + y_v * y) + (fc-fa) (O_w + x_w * x + y_w * y)
where (x,y) are the coordinates of your point p. You can check the validity of this equation by inserting the coordinates of the three vertices a, b, c and verify that you obtain the three values fa, fb and fc. Remember that the barycenter coordinates of a are (0,0) hence O_v + x_v * a_x + y_v * a_y = 0 and so on... (a_x and a_y are the x,y coordinates of the point a).
If you let
q = fa + (fb_fa)*O_v + (fc-fa)*O_w
fx = (fb-fa)*x_v + (fc-fa) * x_w
fy = (fb-fa)*y_v + (fc-fa) * y_w
you get
f(x,y) = q + fx*x + fy * y
Notice that q, fx and fy can be computed once from a,b,c,fa,fb,fc and you can reuse them if you only change the coordinates (x,y) of the point p.
Now if f(x,y)>max, you can easily project (x,y) on the line where max is achieved. The coordinates of the projection are:
(x',y') = (x,y) - [(x,y) * (fx,fy) - max + q]/[(fx,fy) * (fx,fy)] (fx,fy)
Now. You would like to have the code. Well here is some pseudo-code:
toBarycoord(Vector2(0,0),a,b,c,O);
toBarycoord(Vector2(1,0),a,b,c,X);
toBarycoord(Vector2(0,1),a,b,c,Y);
X.sub(O); // X = X - O
Y.sub(O); // Y = Y - O
V = Vector2(fb-fa,fc-fa);
q = fa + V.dot(O); // q = fa + V*O
N = Vector2(V.dot(X),V.dot(Y)); // N = (V*X,V*Y)
// p is the point to be considered
f = q + N.dot(p); // f = q + N*p
if (f > max) {
Vector2 tmp;
tmp.set(N);
tmp.multiply((N.dot(p) - max + q)/(N.dot(N))); // scalar multiplication
p.sub(tmp);
}
if (f < min) {
Vector2 tmp;
tmp.set(N);
tmp.multiply((N.dot(p) - min + q)/(N.dot(N))); // scalar multiplication
p.sum(tmp);
}
We think of the problem as follows: The three points are interpreted as a triangle floating in 3D space with the value being the Z-axis and the cartesian coordinates mapped to the X- and Y- axes respectively.
Then the question is to find the gradient of the plane that is defined by the three points. The lines where the plane intersects with the z = min and z = max planes are the lines you want to restrict your points to.
If you have found a point p where v(p) > max or v(p) < min we need to go in the direction of the steepest slope (the gradient) until v(p + k * g) = max or min respectively. g is the direction of the gradient and k is the factor we need to find. The coordinates you are looking for (in the cartesian coordinates) are the corresponding components of p + k * g.
In order to determine g we calculate the orthonormal vector that is perpendicular to the plane that is determined by the three points using the cross product:
// input: px, py, pz,
// output: p2x, p2y
// local variables
var v1x, v1y, v1z, v2x, v2y, v2z, nx, ny, nz, tp, k,
// two vectors pointing from b to a and c respectively
v1x = ax - bx;
v1y = ay - by;
v1z = az - bz;
v2x = cx - bx;
v2y = cy - by;
v2z = cz - bz;
// the cross poduct
nx = v2y * v1z - v2z * v1y;
ny = v2z * v1x - v2x * v1z;
nz = v2x * v1y - v2y * v1x;
// using the right triangle altitude theorem
// we can calculate the vector that is perpendicular to n
// in our triangle we are looking for q where p is nz, and h is sqrt(nx*nx+ny*ny)
// the theorem says p*q = h^2 so p = h^2 / q - we use tp to disambiguate with the point p - we need to negate the value as it points into the opposite Z direction
tp = -(nx*nx + ny*ny) / nz;
// now our vector g = (nx, ny, tp) points into the direction of the steepest slope
// and thus is perpendicular to the bounding lines
// given a point p (px, py, pz) we can now calculate the nearest point p2 (p2x, p2y, p2z) where min <= v(p2z) <= max
if (pz > max){
// find k
k = (max - pz) / tp;
p2x = px + k * nx;
p2y = py + k * ny;
// proof: p2z = v = pz + k * tp = pz + ((max - pz) / tp) * tp = pz + max - pz = max
} else if (pz < min){
// find k
k = (min - pz) / tp;
p2x = px + k * nx;
p2y = py + k * ny;
} else {
// already fits
p2x = px;
p2y = py;
}
Note that obviously if the triangle is vertically oriented (in 2D it's not a triangle anymore actually), nz becomes zero and tp cannot be calculated. That's because there are no more two lines where the value is min or max respectively. For this case you will have to choose another value on the remaining line or point.

How to find coordinates (as Natural numbers) of two points that form a tangent line for a circle limited by the x axis?

Two points P and Q with coordinates (Px, Py) and (Qx, Qy) satisfy the following properties:
The coordinates Px, Py, Qx, and Qy are integers.
Px = −Qx.
The line PQ is tangent to a circle with center (0, 0) and radius r
0 < Px ≤ a for some integer limit a.
How do I find all such pairs of points P and Q?
For example, in the image below I have a circle with radius r=2 and the limit a = 6. The pair of points P = (6, 2) and Q = (−6, −7) are a solution, because:
The coordinates of P and Q are integers.
Px = −Qx.
The line PQ is tangent to the circle.
0 < Px ≤ 6.
But this is just one pair. I need to find all such pairs. There are a finite number of solutions.
So, is there a way to check if coordinates of points are tangent to the circle and are integers, then to list them all? I've looked at slope equations and shortest path from the center of the circle to the line equations, however, in the first case it requires coordinates to be known (which I could do by brute forcing every single digit, but I cannot see the pattern, because my guts tell me there should be some sort of equation I should apply), and in the second case I have to know the slope equation.
This is the algorithm I came up with but I don't think it is correct or good enough:
Find the slope equation y = mx + b for all 1 ≤ Px ≤ a and −a ≤ Qx ≤ −1.
For every y = mx + b check if it is tangent to the circle (how to do that???)
If true, return the pair
Line PQ has equation:
(x-Px)/(Qx-Px)=(y-Py)/(Qy-Py) or
(x-Px)*(Qy-Py)-(y-Py)*(Qx-Px)=0 or
x*(Qy-Py)+y*(Px-Qx)-Px*Qy+Px*Py+Py*Qx-Py*Px =
x*(Qy-Py)+y*2*Px-Px*(Qy+Py)=0
Distance from zero point to this line (circle radius) is
r=Px*(Qy+Py)/Sqrt((2*Px)^2+(Qy-Py)^2)
Note that radius and nominator are integers, so denominator must be integer too. It is possible when 2*Px and |Qy-Py| are members of some Pythagorean triple (for your example - 12^2+9^2 =15^2).So you can use "Generating a triple" method from the above link to significantly reduce the search and find all the possible point pairs (with radius checking)
Px = k * m * n (for m>=n, radius < k*m*n <= a)
|Qy-Py| = k * (m^2 - n^2)
With a=6 max value of n is 2, and your example corresponds to (k, m, n) set of (3, 2, 1)

Define a function for a circle caps the end of a line segment

I need a function that returns points on a circle in three dimensions.
The circle should "cap" a line segment defined by points A and B and it's radius. each cap is perpendicular to the line segment. and centered at one of the endpoints.
Here is a shitty diagram
Let N be the unit vector in the direction from A to B, i.e., N = (B-A) / length(A-B). The first step is to find two more vectors X and Y such that {N, X, Y} form a basis. That means you want two more vectors so that all pairs of {N, X, Y} are perpendicular to each other and also so that they are all unit vectors. Another way to think about this is that you want to create a new coordinate system whose x-axis lines up with the line segment. You need to find vectors pointing in the direction of the y-axis and z-axis.
Note that there are infinitely many choices for X and Y. You just need to somehow find two that work.
One way to do this is to first find vectors {N, W, V} where N is from above and W and V are two of (1,0,0), (0,1,0), and (0,0,1). Pick the two vectors for W and V that correspond to the smallest coordinates of N. So if N = (.31, .95, 0) then you pick (1,0,0) and (0,0,1) for W and V. (Math geek note: This way of picking W and V ensures that {N,W,V} spans R^3). Then you apply the Gram-Schmidt process to {N, W, V} to get vectors {N, X, Y} as above. Note that you need the vector N to be the first vector so that it doesn't get changed by the process.
So now you have two vectors that are perpendicular to the line segment and perpendicular to each other. This means the points on the circle around A are X * cos t + Y * sin t + A where 0 <= t < 2 * pi. This is exactly like the usual description of a circle in two dimensions; it is just written in the new coordinate system described above.
As David Norman noted the crux is to find two orthogonal unit vectors X,Y that are orthogonal to N. However I think a simpler way to compute these is by finding the householder reflection Q that maps N to a multiple of (1,0,0) and then to take as X the image of (0,1,0) under Q and Y as the image of (0,0,1) under Q. While this might sound complicated it comes down to:
s = (N[0] > 0.0) ? 1.0 : -1.0
t = N[0] + s; f = -1.0/(s*t);
X[0] = f*N[1]*t; X[1] = 1 + f*N[1]*N[1]; X[2] = f*N[1]*N[2];
Y[0] = f*N[2]*t; Y[1] = f*N[1]*N[2]; Y[2] = 1 + f*N[2]*N[2];

How to set up quadratic equation for a ray/sphere intersection?

I'm researching the math for a ray tracer, but I'm not following a transition that is made in just about every article I've read on the subject. This is what I have:
Formula for a sphere:
(X - Cx)^2 + (Y - Cy)^2 + (Z - Cz)^2 - R^2 = 0
Where R is the radius, C is the center, and X, Y, Z are all the points in the sphere.
Formula for a line:
X + DxT, Y + DyT, Z + DzT
where D is a normalized direction vector for the line and X, Y, Z are all the points on the line, and T is a parameter for some point on the line.
By substituting the components of the line into the sphere equation, we get:
(X + DxT - Cx)^2 + (Y + DyT - Cy)^2 + (Z + DzT - Cz)^2 - R^2 = 0
I follow everything up to that point (at least I think I do), but then every tutorial I've read makes a jump from that to a quadratic equation without explaining it (this is copied from one of the sites, so the terms are a little different from my example):
A = Xd^2 + Yd^2 + Zd^2
B = 2 * (Xd * (X0 - Xc) + Yd * (Y0 - Yc) + Zd * (Z0 - Zc))
C = (X0 - Xc)^2 + (Y0 - Yc)^2 + (Z0 - Zc)^2 - Sr^2
I get how to then solve for T using the quadratic formula, but I don't understand how they get to the quadratic equation from the above formulas. I'm assuming that's just some piece of common math knowledge that I've long since forgotten, but googling for "How to set up a quadratic equation" hasn't really yielded anything either.
I'd really like to understand how to get to this step before moving on, as I don't like writing code I don't fully grasp.
Here's a detailed walkthrough of each step; hopefully this will make things crystal clear. The equation for a three-dimensional sphere is:
(x-a)^2 + (y-b)^2 + (z-c)^2 = r^2
with <a, b, c> being the center of the sphere and r its radius. The point <x, y, z> is on the sphere if it satisfies this equation.
The parametric equations for a ray are:
X = xo + xd*t
Y = yo + yd*t
Z = zo + zd*t
where <xo, yo, zo> is the origin of the ray, and <xd,yd,yd> is camera ray's direction.
To find the intersection, we want to see what points on the ray are the same as points on the sphere. So we substitute the ray equation into the sphere equation:
(xo + xd*t - a)^2 + (yo + yd*t - b)^2 + (zo + zd*t - c)^2 = r^2
which expands to:
(xd^2 + yd^2 + zd^2) * t^2 +
[2[xd * (xo - a) + yd * (yo - b) + zd *(zo - c)]] * t +
[(xo - a)^2 + (yo - b)^2 + (zo - c^)2 - r^2] * 1
= 0
Notice that this is a quadratic equation in the form At^2 + Bt + C = 0, with:
A = (xd^2 + yd^2 + zd^2)
B = [2[xd * (xo - a) + yd * (yo - b) + zd *(zo - c)]]
C = [(xo - a)^2 + (yo - b)^2 + (zo - c^)2 - r^2]
We can apply the general quadratic formula for an unknown variable, which is:
t = [-B +- sqrt(B^2 - 4AC)] / 2A
The B^2 - 4AC portion is called the "discriminant". Depending on the value of the discriminant, we will get zero, one, or two solutions to this equation:
If it is less than zero, the solution is an imaginary number, and the ray and sphere do not intersect in the real plane.
If it is equal to zero, then the ray intersects the sphere at exactly 1 point (it is exactly tangent to the sphere).
If it is greater than zero, then the ray intersects the sphere at exactly 2 points.
If the discriminant indicates that there's no solution, then you're done! The ray doesn't intersect the sphere. If the discriminant indicates at least one solution, you can solve for t to determine the intersection point. The two solutions are:
t_1 = [-B + sqrt(B^2 - 4AC)] / 2A
t_2 = [-B - sqrt(B^2 - 4AC)] / 2A
The smaller solution is the point at which the ray first hits the sphere.
From here:
(X + DxT - Cx)^2 + (Y + DyT - Cy)^2 + (Z + DzT - Cz)^2 - R^2 = 0
Expand the three squared terms, so you have a long expression:
X^2 + Dx^2T^2 + Cx^2 + 2XDxT - 2XCx - 2DxTCx + ...... = 0
(This is due to using the formula (x+y+z)^2 = x^2 + y^2 + z^2 + 2xy + 2xz + 2yz)
Then group so you have factors of T^2, T, and 1:
(....)T^2 + (....)T + .... = 0
These factors are the A,B,C given above. This is a quadratic equation for T, and can be solved using the quadratic formula.

Find start and end XY coords of perpendicular line calculated from start and end XY coords of baseline

Using the following start and end point coordinate values of a baseline:
X1 = 5296823.36
Y1 = 2542131.23
X2 = 5311334.21
Y2 = 2548768.66
I would like to calculate the start and end coordinates of a pendicular line that intersects the baseline at the mid-point. This intersecting, perpendicular line should extend at a given distance either side of the baseline (e.g. Dist=100).
I would be very grateful if anyone could provide some guidance using simple formulas that can be tranferred to Excel or VB.
Many thanks in advance.
Steps to do:
Find the midpoint of the two coordinates (xmid, ymid)
Find the gradient of the line segment joining the two coordinates (call it m).
The gradient of a line perpendicular to this line is -1/m.
Use this new gradient and the coordinates of the midpoint (xmid, ymid) to find the equation of the perpendicular line (substitute xmid, ymid and -1/m into the equation of a line), call it y = -1x/m + k
Imagine a right angled triangle from xmid, ymid to your target point (r units along the perpendicular line is the hypotenuse). The x component will be X units across, the y component will be (-1X/m + k) units up.
Solve
r^2 = X^2 + (-1X/m + k)^2
to find X. Where you have already found r, m and k in the previous steps.
Substitute the +ve and -ve values of this into y = -1x/m + k to get the y coordinates of your endpoints, and Bob's your Uncle.
It should be relatively straight forward to translate this into any given programming language in a very short space of time but you may need to understand the underlying maths to do so, and as a Maths teacher I'm not going to do your Homework for you.

Resources