Need to check if point X is in any distance from a line made between 2 dots [duplicate] - line

This question already has answers here:
Shortest distance between a point and a line segment
(56 answers)
Closed 2 years ago.
I am using Sourcepawn, can also understand java ,but I need just a tip, idea to work on
- 2 red dots are end points of the beam. Beam can be in any angles (X,Y). I need to focus on green dot, check the closest distance between orange line (I don't have any points more, just 2 ends) and green dot.
Any tips appreciated, thanks!

Given that you want to know the vector d with defined points p1, p2 and p3 you could do the following (vector variables are underlined):
Or, in a more code friendly notation (I am using JavaScript here) we represent vectors as arrays with x- and y-values:
const fromP1=(p,i)=>p-p1[i], // subtract vector p1 from current vector
dot=(a,b)=>a.reduce((v,p,i)=>v+p*b[i],0); // scalar product
// these are just arbitrary sample point values:
const p1=[1,5,0], p2=[6,2.5,0], p3=[2,2,0];
const a=p2.map(fromP1), // vector from P1 to P2
b=p3.map(fromP1), // vector from P1 to P3
fa=dot(a,b)/dot(a,a), // scalar factor for vector a
c=a.map(p=>p*fa), // scale vector a by fa
d=b.map((p,i)=>p-c[i]); // vector d = vector b - vector c
console.log("vector c:",c);
console.log("vector d:",d)
As a little side note: This method works just as well for 3 (or even more!) dimensions. Simply add further components (=coordinate values) to (all of) the vector arrays. The vector functions will automatically work with all defined dimensions.
If you only want to know the scalar value of the minimum distance then things get a littlie easier:
const fromP1=(p,i)=>p-p1[i], // subtract vector p1 from current vector
dot=(a,b)=>a.reduce((v,p,i)=>v+p*b[i],0); // scalar product
// sample point values (3D):
const p1=[1,5,0], p2=[6,2.5,0], p3=[2,2,0];
const a=p2.map(fromP1), // vector from P1 to P2
b=p3.map(fromP1); // vector from P1 to P3
const ab=dot(a,b);
console.log("distance:",Math.sqrt(dot(b,b) - ab*ab/dot(a,a)) );

Related

Calculate radius and remove GPS coordinates

I have a question about how to remove some "unnecessary" coordinates from a "maps.txt" file using segment line, projection vector or other method.
Path Created on Google Maps:
Map1
Total of 275 coordinates, extracted from the ".KML" file of Google Maps.
Map1_2
Map2
When I do it manually it stays that way (Map2), with 9 coordinates.
I have a file called "maps.txt" where its lines, with coordinates, are in this format:
Obs: A coordinate on each line: latitude, longitude.
-37.2012600, -59.8404600
-37.2000200, -59.8419600
-37.1985300, -59.8439200
-37.1970600, -59.8458500
-37.1959100, -59.8473500
-37.1957800, -59.8475200
-37.1948600, -59.8486900
-37.1939500, -59.8498600
-37.1931400, -59.8509400
-37.1928400, -59.8513100
-37.1926700, -59.8515000
-37.1924600, -59.8517200
-37.1922600, -59.8519200
Is there any way for a code to read my file "maps.txt" and do the line segment, vector projection, point distance calculation using a radius of 100 meters?
In case the code would "remove the line / unnecessary coordinate" from the file "maps.txt", leaving it this way (just an example):
-37.2012600, -59.8404600
-37.1948600, -59.8486900
-37.1922600, -59.8519200
In Python, C, C ++ or another language.
I hope I have been clear and thank you in advance for any help.
Thank you (:
I'll try to explain better.
In the following figure I have 3 coordinates (1, 2 and 3).
The coordinate "1" has a radius within 100m with respect to the "2" coordinate, but from "1" to "3" I have a value greater than 100m, ie in this case the coordinate "1", "2" "and" 3 "in my text file" maps.txt ".
Example1
In the following figure from example 2, I would need only the coordinates "1" and "3" in the file "maps.txt".
Example2
Update:
Here's a script that converts KML to GPX: https://gist.github.com/timabell/8791116
And here's a Python script that seems like it'll do what you want (for GPX files): https://wiki.openstreetmap.org/wiki/User:Travelling_salesman/gpx_reduce
Previous answer:
I don't know how far you're asking us to take our answers; this problem is slightly complex, so here's some pseudocode for starters:
Overall algorithm:
Vector from point 1 to 3. Check distance of point 2 from this vector. (Assuming threshold is okay)
Vector from point 1 to 4. Check distance of points 2 and 3 from this vector. (Assuming threshold is okay)
Vector from point 1 to 5. Check distance of points 2, 3, and 4 from this vector. (Assuming threshold is bad)
First vector is determined: it's from point 1 to 4. Second vector starts at point 4.
Vector from point 4 to 6. Check distance of point 5 from this vector.
Vector from point 4 to 7. Check distance of points 5 and 6 from this vector.
...
Distance of point from vector:
At this point, we need to make a decision:
If we want this to be (quite) exact, we have to find a line that is perpendicular to our line and goes through this point, and find the intersection of these two lines. Then, we calculate the distance using the haversine formula between the intersection and the point. (Unless we sometimes have longer distances between coordinates, I don't think we need this.)
If we don't care too much about exactness, we use the following formula to calculate the "distance", and then "experimentally" find a good threshold value that works for us. (This threshold value is just some float number that we use when checking the distance. If it's above the threshold value, we start a new line.)
https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points
(Where (x0, y0) is the point we're investigating, and the line goes through (x1, y1) and (x2, y2).)

Subdivide multi segmented Cubic Bezier spline

First of let me apologies for a bad English and probably not very straight forward question, as I am not really sure how to call it.
I have a multi segmented Cubic Bezier curve In After Effects, it is is defined by 5 vertices with IN & OUT tangents. My task is to subdivide it into N small linear chunks in Java Script.
EDIT submited more info.
Given a multi segmented Cubic Bezier spline defined by 5 points with In & Out tangents, I need to get a linear representation of it. Where N is number of linear segments, defined by user.
Cubic Bezier Spline:
Segment1: P0, P0out, P1in, P1;
Segment2: P1, P1out, P2in, P2;
Segment3: P2, P2out, P3in, P3;
Segment4: P3, P3out, P4in, P4;
Expected output:
N = 1: linear spline with 2 anchors representing entire shape;
N = 2: linear spline with 3 anchors representing entire shape;
N = 3: linear spline with 4 anchors representing entire shape;
N = 4: linear spline with 5 anchors representing entire shape;
...
N = 8: linear spline with 9 anchors representing entire shape;
distance(L0,L1) = distance(L1,L2) = distance(L2,L3) = ... = distance(L-n, Ln)
In example image I use 4-segmented spline, where segment length is equal to one another - this is just easier to draw to explain my task. But in real project those segments will not be equal, and there will be more then 4 segments total.
I have looked at de Casteljau method, but as I can understand, it works with one segment spline. My math skills are dusty, so I am not really sure if I can use de Casteljau in my example.
This is conceptually straight forward, although it might involve quite a bit of code for reasons explained a little later on. What you're trying to do is flatten a (cubic) poly-Bezier, so let's start with that:
Individual cubic Bezier curves are generated by four points: a start point, a control point that determines the tangent at the start point, an end point, and a control point that determines the tangent at the end point. The curve, then, is a plot of the cubic Bezier function:
Bx(t) = p1.x × (1-t)³ + 2 × p2.x × (1-t)² × t + 2 × p3.x × (1-t) × t² + p4.x × t³
By(t) = p1.y × (1-t)³ + 2 × p2.y × (1-t)² × t + 2 × p3.y × (1-t) × t² + p4.y × t³
A single Bezier curve is plotted over the interval t=[0,1], so a poly-Bezier of N segments is plotted over a total interval N × [0,1].
First, the simple case: simple flattening. Bezier curves are non-linear curves and so let's first not bother to enforce "same length for each of the line segments". Given an N-segment poly-Bezier:
S = number of segments we want
points = empty list
for (s = 0):(s = S):(step = S/N):
v = s * step
segmentid = floor(v)
segment = polycurve.segments[segmentid]
t = v % 1
points.push(
segment.pointAt(t)
)
We now have all the points we need, and we just connect them with lines. Done.
However, Bezier curves are non-linear curves, so flattening in this way does not yield equidistant segments in the slightest. If we want to do that, we need to work with distance along the curve rather than t values.
S = number of segments we want
points = empty list
for (s = 0):(s = S):(step = S/N):
v = s * step
segmentid = floor(v)
segment = polycurve.segments[segmentid]
distanceRatio = v % 1
t = segment.getTforDistanceRatio(distanceRatio)
points.push(
segment.pointAt(t)
)
This will work exactly as you want, but getTforDistanceRatio is the hard part, because what we're doing here is reparameterizing the curve for distance, rather than time, and that is a very hard mathematical problem (for which no general symbolic solution exists). The cheapest way to do this is using a Lookup Table (LUT), which is explained in the link above, for "distance along the curve".
The de Casteljau method is used to compute a point on the Bezier curve and also obtain the control points for the two subdivided curves in the process. So, yes you should be able to use de Cateljau method to evaluate as many points as you want on a Bezier curve if you know the control points.
From the picture you show and the fact that your "cubic Bezier spline" takes in/out tangents as input, I think your spline is actually "cubic Hermite spline", in which each segment is indeed a cubic Bezier curve. You can convert each segment of your spline to a cubic Bezier curve, then use de Cateljau method to evaluate as many points as you want, then connect these points by straight lines.

The math to render a cube?

My friend and I are making a 3d rendering engine from scratch in our VB class at school, but I am not sure how the math to form the cube would work. Given six variables:
rotX
rotY
rotZ
lenX
lenY
lenZ
Which represent the rotation on x,y,z and the length on x,y,z respectively, what would be the formulas to make the cube? I know that all I have to do is calculate three segments and from those segments just create three parallelograms, so I just need the math to find what the three segments are.
Thanks!
there are 2 basic 3D object representations for both are your data is insufficient.
surface representation
objects are set of surface polygons/vertexes/...
for cube its a set of 8 points + the triangles/quads for 6 faces
analytical representation
objects are set of equations describing the object
for cube its a intersection of 6 planes
I think you are using option 1 so what you need is:
- position
- orientation
- size
usually an axis aligned cube looks like this:
const double a=1.0; //cube size;
double pnt[8][3]= //cube points
{
+a,-a,+a,
+a,+a,+a,
-a,+a,+a,
-a,-a,+a,
+a,-a,-a,
+a,+a,-a,
-a,+a,-a,
-a,-a,-a
};
int tab[24]=
{
0,1,2,3, // 1st.quad
7,6,5,4, // 2nd.quad
4,5,1,0, // 3th.quad ...
5,6,2,1,
6,7,3,2,
7,4,0,3
};
well for size and orientation you can apply transformation matrix
or directly recompute points by direction vectors
so you need to remember position (point) and orientation (3 vectors) and size (scalar)
all above can be stored in single transformation matrix 4x4
but if you want the vectors then points will be like this:
P(+a,-a,+a) -> +a*I -a*J +a*K
where I,J,K are the orientation vectors
a is cube size
P(+a,-a,+a) is original axis aligned point in table above
Option 2 is more tricky to implement and unless you really need it (ray-tracing renders) then forget about it.

How can DWT be used in LSB substitution steganography

In steganography, the least significant bit (LSB) substitution method embeds the secret bits in the place of bits from the cover medium, for example, image pixels. In some methods, the Discrete Wavelet Transform (DWT) of the image is taken and the secret bits are embedded in the DWT coefficients, after which the inverse trasform is used to reconstruct the stego image.
However, the DWT produces float coefficients and for the LSB substitution method integer values are required. Most papers I've read use the 2D Haar Wavelet, yet, they aren't clear on their methodology. I've seen the transform being defined in terms of low and high pass filters (float transforms), or taking the sum and difference of pair values, or the average and mean difference, etc.
More explicitly, either in the forward or the inverse transform (but not necessarily in both depending on the formulas used) eventually float numbers will appear. I can't have them for the coefficients because the substitution won't work and I can't have them for the reconstructed pixels because the image requires integer values for storage.
For example, let's consider a pair of pixels, A and B as a 1D array. The low frequency coefficient is defined by the sum, i.e., s = A + B, and the high frequency coefficient by the difference, i.e., d = A - B. We can then reconstruct the original pixels with B = (s - d) / 2 and A = s - B. However, after any bit twiddling with the coefficients, s - d may not be even anymore and float values will emerge for the reconstructed pixels.
For the 2D case, the 1D transform is applied separately for the rows and the columns, so eventually a division by 4 will occur somewhere. This can result in values with float remainders .00, .25, .50 and .75. I've only come across one paper which addresses this issue. The rest are very vague in their methodology and I struggle to replicate them. Yet, the DWT has been widely implemented for image steganography.
My question is, since some of the literature I've read hasn't been enlightening, how can this be possible? How can one use a transform which introduces float values, yet the whole steganography method requires integers?
One solution that has worked for me is using the Integer Wavelet Transform, which some also refer to as a lifting scheme. For the Haar wavelet, I've seen it defined as:
s = floor((A + B) / 2)
d = A - B
And for inverse:
A = s + floor((d + 1) / 2)
B = s - floor(d / 2)
All the values throughout the whole process are integers. The reason it works is because the formulas contain information about both the even and odd parts of the pixels/coefficients, so there is no loss of information from rounding down. Even if one modifies the coefficients and then takes the inverse transform, the reconstructed pixels will still be integers.
Example implementation in Python:
import numpy as np
def _iwt(array):
output = np.zeros_like(array)
nx, ny = array.shape
x = nx // 2
for j in xrange(ny):
output[0:x,j] = (array[0::2,j] + array[1::2,j])//2
output[x:nx,j] = array[0::2,j] - array[1::2,j]
return output
def _iiwt(array):
output = np.zeros_like(array)
nx, ny = array.shape
x = nx // 2
for j in xrange(ny):
output[0::2,j] = array[0:x,j] + (array[x:nx,j] + 1)//2
output[1::2,j] = output[0::2,j] - array[x:nx,j]
return output
def iwt2(array):
return _iwt(_iwt(array.astype(int)).T).T
def iiwt2(array):
return _iiwt(_iiwt(array.astype(int).T).T)
Some languages already have built-in functions for this purpose. For example, Matlab uses lwt2() and ilwt2() for 2D lifting-scheme wavelet transform.
els = {'p',[-0.125 0.125],0};
lshaarInt = liftwave('haar','int2int');
lsnewInt = addlift(lshaarInt,els);
[cAint,cHint,cVint,cDint] = lwt2(x,lsnewInt) % x is your image
xRecInt = ilwt2(cAint,cHint,cVint,cDint,lsnewInt);
An article example where IWT was used for image steganography is Raja, K.B. et. al (2008) Robust image adaptive steganography using integer wavelets.

Most efficient way to check if a point is in or on a convex quad polygon

I'm trying to figure out the most efficient/fast way to add a large number of convex quads (four given x,y points) into an array/list and then to check against those quads if a point is within or on the border of those quads.
I originally tried using ray casting but thought that it was a little overkill since I know that all my polygons will be quads and that they are also all convex.
currently, I am splitting each quad into two triangles that share an edge and then checking if the point is on or in each of those two triangles using their areas.
for example
Triangle ABC and test point P.
if (areaPAB + areaPAC + areaPBC == areaABC) { return true; }
This seems like it may run a little slow since I need to calculate the area of 4 different triangles to run the check and if the first triangle of the quad returns false, I have to get 4 more areas. (I include a bit of an epsilon in the check to make up for floating point errors)
I'm hoping that there is an even faster way that might involve a single check of a point against a quad rather than splitting it into two triangles.
I've attempted to reduce the number of checks by putting the polygon's into an array[,]. When adding a polygon, it checks the minimum and maximum x and y values and then using those, places the same poly into the proper array positions. When checking a point against the available polygons, it retrieves the proper list from the array of lists.
I've been searching through similar questions and I think what I'm using now may be the fastest way to figure out if a point is in a triangle, but I'm hoping that there's a better method to test against a quad that is always convex. Every polygon test I've looked up seems to be testing against a polygon that has many sides or is an irregular shape.
Thanks for taking the time to read my long winded question to what's prolly a simple problem.
I believe that fastest methods are:
1: Find mutual orientation of all vector pairs (DirectedEdge-CheckedPoint) through cross product signs. If all four signs are the same, then point is inside
Addition: for every edge
EV[i] = V[i+1] - V[i], where V[] - vertices in order
PV[i] = P - V[i]
Cross[i] = CrossProduct(EV[i], PV[i]) = EV[i].X * PV[i].Y - EV[i].Y * PV[i].X
Cross[i] value is positive, if point P lies in left semi-plane relatively to i-th edge (V[i] - V[i+1]), and negative otherwise. If all the Cross[] values are positive, then point p is inside the quad, vertices are in counter-clockwise order. f all the Cross[] values are negative, then point p is inside the quad, vertices are in clockwise order. If values have different signs, then point is outside the quad.
If quad set is the same for many point queries, then dmuir suggests to precalculate uniform line equation for every edge. Uniform line equation is a * x + b * y + c = 0. (a, b) is normal vector to edge. This equation has important property: sign of expression
(a * P.x + b * Y + c) determines semi-plane, where point P lies (as for crossproducts)
2: Split quad to 2 triangles and use vector method for each: express CheckedPoint vector in terms of basis vectors.
P = a*V1+b*V2
point is inside when a,b>=0 and their sum <=1
Both methods require about 10-15 additions, 6-10 multiplications and 2-7 comparisons (I don't consider floating point error compensation)
If you could afford to store, with each quad, the equation of each of its edges then you could save a little time over MBo's answer.
For example if you have an inward pointing normal vector N for each edge of the quad, and a constant d (which is N.p for one of the vertcies p on the edge) then a point x is in the quad if and only if N.x >= d for each edge. So thats 2 multiplications, one addition and one comparison per edge, and you'll need to perform up to 4 tests per point.This technique works for any convex polygon.