Related
I am very sorry for asking a question that is probably very easy if you know how to solve it, and where many versions of the same question has been asked before. However, I am creating a new post since I have not found an answer to this specific question.
Basically, I have a 200cm x 200cm square that I am recording with a camera above it. However, the camera distorts the square slightly, see example here.. I am wondering how I go from transforming the x,y coordinates in the camera to real-life x,y coordinates (e.g., between 0-200 cm for each side). I understand that I probably need to apply some kind of transformation matrix, but I do not know which one, nor how to determine the transformation matrix. I haven't done any serious linear-algebra in a long time, so I appreciate any pointers for what to read up on, or how to get it done. I am working in python, so if there is some ready code for doing the transformation that would also be useful to know.
Thanks a lot!
I will show this using python and numpy.
import numpy as np
First, you have to understand the projection model
def apply_homography(H, p1):
p = H # p1.T
return (p[:2] / p[2]).T
With some algebraic manipulation you can determine the points at the plane z=1 that produced the given points.
def revert_homography(H, p2):
Hb = np.linalg.inv(H)
# 1 figure out which z coordinate should be added to p2
# order to get z=1 for p1
z = 1/(Hb[2,2] + (Hb[2,0] * p2[:,0] + Hb[2,1]*p2[:,1]))
p2 = np.hstack([p2[:,:2] * z[:,None], z[:, None]])
return p2 # Hb.T
The projection is not invertible, but under the complanarity assumption it may be inverted successfully.
Now, let's see how to determine the H matrix from the given points (assuming they are coplanar).
If you have the four corners in order in order you can simply specify the (x,y) coordinates of the cornder, then you can use the projection equations to determine the homography matrix like here, or here.
This requires at least 5 points to be determined as there is 9 coefficients, but we can fix one element of the matrix and make it an inhomogeneous equation.
def find_homography(p1, p2):
A = np.zeros((8, 2*len(p1)))
# x2'*(H[2,0]*x1+H[2,1]*x2)
A[6,0::2] = p1[:,0] * p2[:,0]
A[7,0::2] = p1[:,1] * p2[:,0]
# - (H[0,0]*x1+H[0,1]*y1+H[0,2])
A[0,0::2] = -p1[:,0]
A[1,0::2] = -p1[:,1]
A[2,0::2] = -1
# y2'*(H[2,0]*x1+H[2,1]*x2)
A[6,1::2] = p1[:,0] * p2[:,1]
A[7,1::2] = p1[:,1] * p2[:,1]
# - (H[1,0]*x1+H[1,1]*y1+H[1,2])
A[3,1::2] = -p1[:,0]
A[4,1::2] = -p1[:,1]
A[5,1::2] = -1
# assuming H[2,2] = 1 we can pass its coefficient
# to the independent term making an inhomogeneous
# equation
b = np.zeros(2*len(p2))
b[0::2] = -p2[:,0]
b[1::2] = -p2[:,1]
h = np.ones(9)
h[:8] = np.linalg.lstsq(A.T, b, rcond=None)[0]
return h.reshape(3,3)
Here a complete usage example. I pick a random H and transform four random points, this is what you have, I show how to find the transformation matrix H_. Next I create a test set of points, and I show how to find the world coordinates from the image coordinates.
# Pick a random Homography
H = np.random.rand(3,3)
H[2,2] = 1
# Pick a set of random points
p1 = np.random.randn(4, 3);
p1[:,2] = 1;
# The coordinates of the points in the image
p2 = apply_homography(H, p1)
# testing
# Create a set of random points
p_test = np.random.randn(20, 3)
p_test[:,2] = 1;
p_test2 = apply_homography(H, p_test)
# Now using only the corners find the homography
# Find a homography transform
H_ = find_homography(p1, p2)
assert np.allclose(H, H_)
# Predict the plane points for the test points
p_test_predicted = revert_homography(H_, p_test2)
assert np.allclose(p_test_predicted, p_test)
I want to plot a simple object in scilab (3d). To understand the way scilab works in that regard, I wrote the following example:
xx = [[2;2;1;3;],[2;2;3;3],[2;2;3;1],[2;2;1;1],[1;3;3;1],[3;3;3;3],[3;3;1;1],[1;1;1;1],[1;2;2;3],[1;1;2;2],[3;2;2;3],[3;2;2;1]]
yy = [[2;2;1;1;],[2;2;1;3],[2;2;3;3],[2;2;3;1],[1;1;1;1],[1;3;3;1],[3;3;3;3],[3;1;1;3],[1;2;2;1],[1;3;2;2],[1;2;2;3],[3;2;2;3]]
zz = [[0;0;1;1;],[0;0;1;1],[0;0;1;1],[0;0;1;1],[1;1;2;2],[1;1;2;2],[1;2;2;1],[1;1;2;2],[2;3;3;2],[2;2;3;3],[2;3;3;2],[2;3;3;2]]
col = ones(12,1)*3
plot3d(xx,yy,list(zz,col))
//h = get("hdl")
//h.hiddencolor = -1 // backside and frontside same color
with the following result:
While the structure is absolutley fine, the coloring on 2 faces is inside out. I tried to draw the points of the affected faces in different ways counterclockwise/clockwise, different starting points, etc.. But the faces seem to keep oriented inwards the structure. I found a workaround by setting the backside of the faces equal to the frontside (the 2 commented lines in the code) but I want to understand how scilab determines the orientation of the faces for later work. Any clues?
EDIT:
So i tried PTRK's suggestions. While his provided Matrices are definitely different:
The result is still the same. Even the output of the provided Testscript is different:
Perhaps thats some kind of version/system thing? I'm using Scilab 6.0.0 on Windows 10.
Let a surface defined by 3 nodes: [P1,P2,P3]. Then you must cycle clockwise trough theses nodes to have the right orientation of inside and outside. Here is a drawing explaining it:
3 of your polygones are defined conterclockwise, thoses with y=1, y=3 and x = 1. When drawing 4 points polygones, to switch the rotation from clockwise to counterclockwise, just swap the 2nd and 4th nodes or 1st and 3rd.
Thus you must set your points as:
xx = [[2;2;1;3;],[2;2;3;3],[2;2;3;1],[2;2;1;1],[1;1;3;3],[3;3;3;3],[3;3;1;1],[1;1;1;1],[1;2;2;3],[1;1;2;2],[3;2;2;3],[3;2;2;1]]
yy = [[2;2;1;1;],[2;2;1;3],[2;2;3;3],[2;2;3;1],[1;1;1;1],[1;1;3;3],[3;3;3;3],[3;3;1;1],[1;2;2;1],[1;3;2;2],[1;2;2;3],[3;2;2;3]]
zz = [[0;0;1;1;],[0;0;1;1],[0;0;1;1],[0;0;1;1],[1;2;2;1],[1;2;2;1],[1;2;2;1],[1;2;2;1],[2;3;3;2],[2;2;3;3],[2;3;3;2],[2;3;3;2]]
This will give the desired output :
Scilab 6.0.0 bug
In this version, if your surfaces are parallel to the cartesian axes, then Scilab will direct it along the axis, no matter how you defined it. Thus your problem. A workaround could be to offset one of the coordinate by a small delta, which must be not too small, as shown in below example.
Regarding your problem, if we want to keep the geometry of your object, we could tilt it with a tiny angle: using rotation matrix, if the computational cost induced by the rotation of all the coordinates doesn't bother you. Here's your script with the tilted object
clc
clear
xdel(winsid())
xx = [[2;2;1;3;],[2;2;3;3],[2;2;3;1],[2;2;1;1],[1;1;3;3],[3;3;3;3],[3;3;1;1],[1;1;1;1],[1;2;2;3],[1;1;2;2],[3;2;2;3],[3;2;2;1]]
yy = [[2;2;1;1;],[2;2;1;3],[2;2;3;3],[2;2;3;1],[1;1;1;1],[1;1;3;3],[3;3;3;3],[3;3;1;1],[1;2;2;1],[1;3;2;2],[1;2;2;3],[3;2;2;3]]
zz = [[0;0;1;1;],[0;0;1;1],[0;0;1;1],[0;0;1;1],[1;2;2;1],[1;2;2;1],[1;2;2;1],[1;2;2;1],[2;3;3;2],[2;2;3;3],[2;3;3;2],[2;3;3;2]]
col = ones(12,1)*3
figure(1)
set(gcf(),'background',-2)
subplot(2,1,1)
plot3d(xx,yy,list(zz,col))
title('Object with surfaces orthogonal to cartesian axis')
subplot(2,1,2)
// t is angle in radian showing the tilt
t = %pi/10000
c = cos(t)
s = sin(t)
rot = [1,0,0;0,c,-s;0,s,c]*[c,0,s;0,1,0;-s,0,c]*[c,-s,0;s,c,0;0,0,1]
for i=1:size(xx,1)
for j = 1:size(xx,2)
xyz=(rot*[xx(i,j);yy(i,j);zz(i,j)])
x(i,j)=xyz(1)
y(i,j)=xyz(2)
z(i,j)=xyz(3)
end
end
plot3d(x,y,list(z,col))
title('Object with surfaces tildted by an angle of '+string(t)+' rad')
Script showing 2 surfaces defined by the same nodes but in opposite order.
clc
clear
xdel(winsid())
figure(1)
set(gcf(),'background',-2)
cr=color('red') // color of the outside surface
P1 = [0,0,0] //
P2 = [0,1,0]
P3 = [1,0,0]
F1 = [P1;P2;P3] // defining surface clockwise
F2 = [P1;P3;P2] // counterclockwise
subplot(2,2,1)
plot3d(F1(:,1),F1(:,2),list(F1(:,3),cr*ones(F1(:,3))))
xstring(F1(:,1),F1(:,2),['P1','P2','P3'])
title('surface is [P1,P2,P3] with z_P3=0')
set(gca(),'data_bounds',[0,1,0,1,-1,1])
subplot(2,2,2)
plot3d(F2(:,1),F2(:,2),list(F2(:,3),cr*ones(F2(:,3))))
xstring(F2(:,1),F2(:,2),['P1','P3','P2'])
title('surface is [P1,P3,P2] with z_P3=0, broken with Scilab 6.0.0')
set(gca(),'data_bounds',[0,1,0,1,-1,1])
subplot(2,2,3)
plot3d(F2(:,1),F2(:,2),list(F2(:,3)+[0;0;10^-7],cr*ones(F2(:,3))))
xstring(F2(:,1),F2(:,2),['P1','P3','P2'])
title('surface is [P1,P3,P2] with |z_P3| < 10^-8')
set(gca(),'data_bounds',[0,1,0,1,-1,1])
subplot(2,2,4)
plot3d(F2(:,1),F2(:,2),list(F2(:,3)+[0;0;10^-8],cr*ones(F2(:,3))))
xstring(F2(:,1),F2(:,2),['P1','P3','P2'])
title('surface is [P1,P3,P2] with |z_P3| = 10^-8, broken in 6.0.0')
set(gca(),'data_bounds',[0,1,0,1,-1,1])
Scilab 5.5.1
Scilab 6.0.0
PLEASE do not just post a solution to my problem. For me, this is all about understanding how to do this and be able to explain to myself and others how this and that makes it all work!
I have a dart board I created with turtle. I can post it if someone really wants to see it.
Now, I need to create a function that will create a random spot on the board to hit, then incorporate the point value for that spot. The random point is simple. But is there a way that I can assign the correct value to an AREA without having to name EVERY coordinate one by one?
Say your dart board is centered at (x0, y0), and you have a dart at (x, y). You need to translate your dart into polar coordinates (phi, r):
r = sqrt((x - x0) ** 2, (y - y0) ** 2)
phi = math.atan2(y, x)
Then figure out whether r makes your dart is in center, inner, mid or outer ring, and in which section of the circle your phi lies.
What you need is a reverse transform, one that given x,y coordinates can identify which area it belongs to.
The best way to deal with this problem is to think in terms of coordinate systems. The area of a dart board is specified by its angle and radius. You must convert your x,y coordinates to an angle and radius, then determining the area it falls within will be simple.
Determining the angle is best done with an arctan2 function, which can directly convert an x,y offset into an angle. The radius is a simple sqrt(x**2 + y**2) once you have subtracted the center point from x,y.
good ol' Pythagoras
Let the point (x1, y1) be the center of the dart board that is used from the constructor. and let (x2, y2) be the random point on the board you find.
Use this formula to find d the distance from the center. Then you just need a few if statements
if 0 <= d || d <= 2:
# area 0
elif d < 2 || 4 <= d:
# area 1
elif d < 4 || 6 <= d:
# area 2
Ok, I know this sounds really daft to be asking here, but it is programming related.
I'm working on a game, and I'm thinking of implementing a system that allows users to triangulate their 3D coordinates to locate something (eg for a task).
I also want to be able to let the user make the coordinates of the points they are using for triangulation have user-determined coordinates (so the location's coordinate is relative, probably by setting up a beacon or something).
I have a method in place for calculating the distance between the points, so essentially I can calculate the lengths of the sides of the triangle/pyramid as well as all but the coordinate I am after.
It has been a long time since I have done any trigonometry and I am rusty with the sin, cos and tan functions, I have a feeling they are required but have no clue how to implement them.
Can anyone give me a demonstration as to how I would go about doing this in a mathematical/programatical way?
extra info:
My function returns the exact distance between the two points, so say you set two points to 0,0,0 and 4,4,0 respectively, and those points are set to scale(the game world is divided into a very large 3d grid, with each 'block' area being represented by a 3d coordinate) then it would give back a value at around 5.6.
The key point about it varying is that the user can set the points, so say they set a point to read 0,0,0, the actual location could be something like 52, 85, 93. However, providing they then count the blocks and set their other points correctly (eg, set a point 4,4,0 at the real point 56, 89, 93) then the final result will return the relative position (eg the object they are trying to locate is at real point 152, 185, 93, it will return the relative value 100,100,0). I need to be able to calculate it knowing every point but the one it's trying to locate, as well as the distances between all points.
Also, please don't ask why I can't just calculate it by using the real coordinates, I'm hoping to show the equation up on screen as it calculates the result.7
Example:
Here is a diagram
Imagine these are points in my game on a flat plain.
I want to know the point f.
I know the values of points d and e, and the sides A,B and C.
Using only the data I know, I need to find out how to do this.
Answered Edit:
After many days of working on this, Sean Kenny has provided me with his time, patience and intellect, and thus I have now got a working implementation of a triangulation method.
I hope to place the different language equivalents of the code as I test them so that future coders may use this code and not have the same problem I have had.
I spent a bit of time working on a solution but I think the implementer, i.e you, should know what it's doing, so any errors encountered can be tackled later on. As such, I'll give my answer in the form of strong hints.
First off, we have a vector from d to e which we can work out: if we consider the coordinates as position vectors rather than absolute coordinates, how can we determine what the vector pointing from d to e is? Think about how you would determine the displacement you had moved if you only knew where you started and where you ended up? Displacement is a straight line, point A to B, no deviation, not: I had to walk around that house so I walked further. A straight line. If you started at the point (0,0) it would be easy.
Secondly, the cosine rule. Do you know what it is? If not, read up on it. How can we rearrange the form given in the link to find the angle d between vectors DE and DF? Remember you need the angle, not a function of the angle (cos is a function remember).
Next we can use a vector 'trick' called the scalar product. Notice there is a cos function in there. Now, you may be thinking, we've just found the angle, why are we doing it again?
Define DQ = [1,0]. DQ is a vector of length 1, a unit vector, along the x-axis. Which other vector do we know? Do we know of two position vectors?
Once we have two vectors (I hope you worked out the other one) we can use the scalar product to find the angle; again, just the angle, not a function of it.
Now, hopefully, we have 2 angles. Could we take one from the other to get yet another angle to our desired coordinate DF? The choice of using a unit vector earlier was not arbitrary.
The scalar product, after some cancelling, gives us this : cos(theta) = x / r
Where x is the x ordinate for F and r is the length of side A.
The end result being:
theta = arccos( xe / B ) - arccos( ( (A^2) + (B^2) - (C^2) ) / ( 2*A*B ) )
Where theta is the angle formed between a unit vector along the line y = 0 where the origin is at point d.
With this information we can find the x and y coordinates of point f relative to d. How?
Again, with the scalar product. The rest is fairly easy, so I'll give it to you.
x = r.cos(theta)
y = r.sin(theta)
From basic trigonometry.
I wouldn't advise trying to code this into one value.
Instead, try this:
//pseudo code
dx = 0
dy = 0 //initialise coordinates somehow
ex = ex
ey = ey
A = A
B = B
C = C
cosd = ex / B
cosfi = ((A^2) + (B^2) - (C^2)) / ( 2*A*B)
d = acos(cosd) //acos is a method in java.math
fi = acos(cosfi) //you will have to find an equivalent in your chosen language
//look for a method of inverse cos
theta = fi - d
x = A cos(theta)
y = A sin(theta)
Initialise all variables as those which can take decimals. e.g float or double in Java.
The green along the x-axis represents the x ordinate of f, and the purple the y ordinate.
The blue angle is the one we are trying to find because, hopefully you can see, we can then use simple trig to work out x and y, given that we know the length of the hypotenuse.
This yellow line up to 1 is the unit vector for which scalar products are taken, this runs along the x-axis.
We need to find the black and red angles so we can deduce the blue angle by simple subtraction.
Hope this helps. Extensions can be made to 3D, all the vector functions work basically the same for 3D.
If you have the displacements from an origin, regardless of whether this is another user defined coordinate or not, the coordinate for that 3D point are simply (x, y, z).
If you are defining these lengths from a point, which also has a coordinate to take into account, you can simply write (x, y, z) + (x1, y1, z1) = (x2, y2, z2) where x2, y2 and z2 are the displacements from the (0, 0, 0) origin.
If you wish to find the length of this vector, i.e if you defined the line from A to B to be the x axis, what would the x displacement be, you can use Pythagoras for 3D vectors, it works just the same as with 2D:
Length l = sqrt((x^2) + (y^2) + (z^2))
EDIT:
Say you have a user defined point A (x1, y1, z1) and you want to define this as the origin (0,0,0). You have another user chosen point B (x2, y2, z2) and you know the distance from A to B in the x, y and z plane. If you want to work out what this point is, in relation to the new origin, you can simply do
B relative to A = (x2, y2, z2) - (x1, y1, z1) = (x2-x1, y2-y1, z2-z1) = C
C is the vector A>B, a vector is a quantity which has a magnitude (the length of the lines) and a direction (the angle from A which points to B).
If you want to work out the position of B relative to the origin O, you can do the opposite:
B relative to O = (x2, y2, z2) + (x1, y1, z1) = (x1+x2, y1+y2, z1+z2) = D
D is the vector O>B.
Edit 2:
//pseudo code
userx = x;
usery = y;
userz = z;
//move origin
for (every block i){
xi = xi-x;
yi = yi - y;
zi = zi -z;
}
I have three vertices which make up a plane/polygon in 3D Space, v0, v1 & v2.
To calculate barycentric co-ordinates for a 3D point upon this plane I must first project both the plane and point into 2D space.
After trawling the web I have a good understanding of how to calculate barycentric co-ordinates in 2D space, but I am stuck at finding the best way to project my 3D points into a suitable 2D plane.
It was suggested to me that the best way to achieve this was to "drop the axis with the smallest projection". Without testing the area of the polygon formed when projected on each world axis (xy, yz, xz) how can I determine which projection is best (has the largest area), and therefore is most suitable for calculating the most accurate barycentric co-ordinate?
Example of computation of barycentric coordinates in 3D space as requested by the OP. Given:
3D points v0, v1, v2 that define the triangle
3D point p that lies on the plane defined by v0, v1 and v2 and inside the triangle spanned by the same points.
"x" denotes the cross product between two 3D vectors.
"len" denotes the length of a 3D vector.
"u", "v", "w" are the barycentric coordinates belonging to v0, v1 and v2 respectively.
triArea = len((v1 - v0) x (v2 - v0)) * 0.5
u = ( len((v1 - p ) x (v2 - p )) * 0.5 ) / triArea
v = ( len((v0 - p ) x (v2 - p )) * 0.5 ) / triArea
w = ( len((v0 - p ) x (v1 - p )) * 0.5 ) / triArea
=> p == u * v0 + v * v1 + w * v2
The cross product is defined like this:
v0 x v1 := { v0.y * v1.z - v0.z * v1.y,
v0.z * v1.x - v0.x * v1.z,
v0.x * v1.y - v0.y * v1.x }
WARNING - Almost every thing I know about using barycentric coordinates, and using matrices to solve linear equations, was learned last night because I found this question so interesting. So the following may be wrong, wrong, wrong - but some test values I have put in do seem to work.
Guys and girls, please feel free to rip this apart if I screwed up completely - but here goes.
Finding barycentric coords in 3D space (with a little help from Wikipedia)
Given:
v0 = (x0, y0, z0)
v1 = (x1, y1, z1)
v2 = (x2, y2, z2)
p = (xp, yp, zp)
Find the barycentric coordinates:
b0, b1, b2 of point p relative to the triangle defined by v0, v1 and v2
Knowing that:
xp = b0*x0 + b1*x1 + b2*x2
yp = b0*y0 + b1*y1 + b2*y2
zp = b0*z0 + b1*z1 + b2*z2
Which can be written as
[xp] [x0] [x1] [x2]
[yp] = b0*[y0] + b1*[y1] + b2*[y2]
[zp] [z0] [z1] [z2]
or
[xp] [x0 x1 x2] [b0]
[yp] = [y0 y1 y2] . [b1]
[zp] [z0 z1 z2] [b2]
re-arranged as
-1
[b0] [x0 x1 x2] [xp]
[b1] = [y0 y1 y2] . [yp]
[b2] [z0 z1 z2] [zp]
the determinant of the 3x3 matrix is:
det = x0(y1*z2 - y2*z1) + x1(y2*z0 - z2*y0) + x2(y0*z1 - y1*z0)
its adjoint is
[y1*z2-y2*z1 x2*z1-x1*z2 x1*y2-x2*y1]
[y2*z0-y0*z2 x0*z2-x2*z0 x2*y0-x0*y2]
[y0*z1-y1*z0 x1*z0-x0*z1 x0*y1-x1*y0]
giving:
[b0] [y1*z2-y2*z1 x2*z1-x1*z2 x1*y2-x2*y1] [xp]
[b1] = ( [y2*z0-y0*z2 x0*z2-x2*z0 x2*y0-x0*y2] . [yp] ) / det
[b2] [y0*z1-y1*z0 x1*z0-x0*z1 x0*y1-x1*y0] [zp]
If you need to test a number of points against the triangle, stop here. Calculate the above 3x3 matrix once for the triangle (dividing it by the determinant as well), and then dot product that result to each point to get the barycentric coords for each point.
If you are only doing it once per triangle, then here is the above multiplied out (courtesy of Maxima):
b0 = ((x1*y2-x2*y1)*zp+xp*(y1*z2-y2*z1)+yp*(x2*z1-x1*z2)) / det
b1 = ((x2*y0-x0*y2)*zp+xp*(y2*z0-y0*z2)+yp*(x0*z2-x2*z0)) / det
b2 = ((x0*y1-x1*y0)*zp+xp*(y0*z1-y1*z0)+yp*(x1*z0-x0*z1)) / det
That's quite a few additions, subtractions and multiplications - three divisions - but no sqrts or trig functions. It obviously does take longer than the pure 2D calcs, but depending on the complexity of your projection heuristics and calcs, this might end up being the fastest route.
As I mentioned - I have no idea what I'm talking about - but maybe this will work, or maybe someone else can come along and correct it.
Update: Disregard, this approach does not work in all cases
I think I have found a valid solution to this problem.
NB: I require a projection to 2D space rather than working with 3D Barycentric co-ordinates as I am challenged to make the most efficient algorithm possible. The additional overhead incurred by finding a suitable projection plane should still be smaller than the overhead incurred when using more complex operations such as sqrt or sin() cos() functions (I guess I could use lookup tables for sin/cos but this would increase the memory footprint and defeats the purpose of this assignment).
My first attempts found the delta between the min/max values on each axis of the polygon, then eliminated the axis with the smallest delta. However, as suggested by #PeterTaylor there are cases where dropping the axis with the smallest delta, can yeild a straight line rather than a triangle when projected into 2D space. THIS IS BAD.
Therefore my revised solution is as follows...
Find each sub delta on each axis for the polygon { abs(v1.x-v0.x), abs(v2.x-v1.x), abs(v0.x-v2.x) }, this results in 3 scalar values per axis.
Next, multiply these scaler values to compute a score. Repeat this, calculating a score for each axis. (This way any 0 deltas force the score to 0, automatically eliminating this axis, avoiding triangle degeneration)
Eliminate the axis with the lowest score to form the projection, e.g. If the lowest score is in the x-axis, project onto the y-z plane.
I have not had time to unit test this approach but after preliminary tests it seems to work rather well. I would be eager to know if this is in-fact the best approach?
After much discussion there is actually a pretty simple way to solve the original problem of knowing which axis to drop when projecting to 2D space. The answer is described in 3D Math Primer for Graphics and Game Development as follows...
"A solution to this dilemma is to
choose the plane of projection so as
to maximize the area of the projected
triangle. This can be done by
examining the plane normal; the
coordinate that has the largest
absolute value is the coordinate that
we will discard. For example, if the
normal is [–1, 0, 0], then we would
discard the x values of the vertices
and p, projecting onto the yz plane."
My original solution which involved computing a score per axis (using sub deltas) is flawed as it is possible to generate a zero score for all three axis, in which case the axis to drop remains undetermined.
Using the normal of the collision plane (which can be precomputed for efficiency) to determine which axis to drop when projecting into 2D is therefore the best approach.
To project a point p onto the plane defined by the vertices v0, v1 & v2 you must calculate a rotation matrix. Let us call the projected point pd
e1 = v1-v0
e2 = v2-v0
r = normalise(e1)
n = normalise(cross(e1,e2))
u = normalise(n X r)
temp = p-v0
pd.x = dot(temp, r)
pd.y = dot(temp, u)
pd.z = dot(temp, n)
Now pd can be projected onto the plane by setting pd.z=0
Also pd.z is the distance between the point and the plane defined by the 3 triangles. i.e. if the projected point lies within the triangle, pd.z is the distance to the triangle.
Another point to note above is that after rotation and projection onto this plane, the vertex v0 lies is at the origin and v1 lies along the x axis.
HTH
I'm not sure that the suggestion is actually the best one. It's not too hard to project to the plane containing the triangle. I assume here that p is actually in that plane.
Let d1 = sqrt((v1-v0).(v1-v0)) - i.e. the distance v0-v1.
Similarly let d2 = sqrt((v2-v0).(v2-v0))
v0 -> (0,0)
v1 -> (d1, 0)
What about v2? Well, you know the distance v0-v2 = d2. All you need is the angle v1-v0-v2. (v1-v0).(v2-v0) = d1 d2 cos(theta). Wlog you can take v2 as having positive y.
Then apply a similar process to p, with one exception: you can't necessarily take it as having positive y. Instead you can check whether it has the same sign of y as v2 by taking the sign of (v1-v0)x(v2-v0) . (v1-v0)x(p-v0).
As an alternative solution, you could use a linear algebra solver on the matrix equation for the tetrahedral case, taking as the fourth vertex of the tetrahedron v0 + (v1-v0)x(v2-v0) and normalising if necessary.
You shouldn't need to determine the optimal area to find a decent projection.
It's not strictly necessary to find the "best" projection at all, just one that's good enough, and that doesn't degenerate to a line when projected into 2D.
EDIT - algorithm deleted due to degenerate case I hadn't thought of