I am writing a raytracer in java, and I was able to get tracing of spheres working, but I believe I have something wrong with how I am tracing triangles.
Here is the basic algorithm, as I understand it:
First determine if the ray even intersects the plane that the triangle is on.
Clip all points so they are on the same plane as the triangle (so to the xy plane, as an example).
Determine if the potential intersection point falls inside or out of the triangle, based on the number of polygon edges you cross when sending out a ray in an arbitrary direction along the new plane.
Now, here is my implementation of that (specifically the first point):
public Vector getIntersectionVector(Ray ray)
{
Vector planeIntersectionVector = getPlaneIntersectionVector(ray, getPlaneNormal());
if (planeIntersectionVector != null)
{
if (isIntersectionVectorInsideTriangle(planeIntersectionVector))
{
return planeIntersectionVector;
}
else
{
return null;
}
}
else
{
return null;
}
}
Where getPlaceIntersectionVector() is:
private Vector getPlaneIntersectionVector(Ray ray, Vector planeNormal)
{
double vd = planeNormal.dotProduct(ray.getDirection());
//(p_n \dot r_d) == 0, parallel. (p_n \dot r_d) > 0 Plane normal pointing away from ray.
if (vd >= 0)
{
return null;
}
double distance = planeNormal.distance(0d, 0d, 0d);
double vo = -(planeNormal.dotProduct(ray.getOrigin()) + distance);
double intersectionDistance = vo / vd;
//intersectionDistance <= 0 means the "intersection" is behind the ray, so not a real intersection
return (intersectionDistance <= 0) ? null : ray.getLocation(intersectionDistance);
}
Which basically tries to mimic this:
And this:
Where t is the distance along the ray that the point hits, ro is the origin of the ray, rd is the direction of the ray, pn refers to the plane normal of the triangle/plane, and d is the distance from the plane that the triangle is on to the origin (0,0,0)
Am I doing that wrong? When I send out the ray from the first pixel in the image (0,0), I am seeing that the intersectionDistance (or t) is almost 1100, which intuitively seems wrong to me. I would think that the intersection point would be much closer.
Here is the relevant data:
Ray origin (0,0,1), Ray Direction is roughly (0.000917, -0.4689, -0.8833).
Triangle has vertices as (-0.2, 0.1, 0.1), (-0.2, -0.5, 0.2), (-0.2, 0.1, -0.3), which makes the plane normal (-1, 0, 0).
According to my code, the Ray intersects the plane 1090 distance away, which as I mentioned before, seems wrong to me. The scene is only -1.0 to 1.0 in every direction, which means the intersection is very very far in the distance.
Am I doing the plane intersection wrong?
Please let me know where to clarify points, and if you need any more information.
The problem is this line:
double distance = planeNormal.distance(0d, 0d, 0d);
A plane is defined by a normal and a distance from the plane to the origin. The distance of a vector from the origin is the length of a vector, so what you are calculating there is just the length of the plane normal (which will always be 1.0 if it has been normalized).
The distance of the plane from the origin is an extra piece of information that needs to be passed into your function, you can't just calculate it from the normal because it's independent of it (you can can have lots of planes with normals pointing in the same direction at different distances from the origin).
So define your function something like this:
private Vector getPlaneIntersectionVector(Ray ray, Vector planeNormal, double planeDistance)
and call it something like this:
Vector planeIntersectionVector = getPlaneIntersectionVector(ray, getPlaneNormal(), getPlaneDistance());
Then you can calculate vo like this:
double vo = -(planeNormal.dotProduct(ray.getOrigin()) + planeDistance);
Slightly different approach:
Let's triangle vertices are V0, V1, V2
Edge vectors are
A = V1-V0
B = V2 - V0
Ray has parametric equation (as you wrote)
P = R0 + t * Rd
From the other side, intersection point has parametric coordinates u, v in the triangle plane
P = V0 + u * A + v * B
So you can write system of three linear equation for x, y, z coordinates and solve it for t, u, v. If determinant ius non-zero (ray is not parallel to the plane), and t >=0, and u, v, u+v lie in range 0..1, then P is inside triangle.
R0.X + t * Rd.X = V0.X + u * A.X + v * B.X
R0.Y + t * Rd.Y = V0.Y + u * A.Y + v * B.Y
R0.Z + t * Rd.Z = V0.Z + u * A.Z + v * B.Z
Related
I'm rendering some basic triangles, and I'm generating the normals in code. This is my "calculate normals" method. It gets the face normal of a triangle from its three vertices:
public static Vector3f calculateNormal(Vector3f v0, Vector3f v1, Vector3f v2) {
Vector3f u = Vector3f.sub(v2, v0, null);
Vector3f w = Vector3f.sub(v1, v0, null);
Vector3f n = new Vector3f();
Vector3f.cross(u, w, n);
n.normalise(n);
if (Float.isNaN(n.x) || Float.isNaN(n.y) || Float.isNaN(n.z)) {
System.out.println("It's NaN!");
return new Vector3f(0,1,0);
}
return n;
}
Except it outputs "NaN" for about half the triangles. I tried switching the order of the vertices, and that doesn't do anything.
Your calculateNormal function looks okay to me :)
But, the triangles with NaN normals, probably have co-linear vertices (i.e., they are degenerated triangles). Try checking if n.length is zero (or almost zero) to detect this edge case.
Without knowing which math library you are using, I cannot answer specifically. However, to find the cross product with 3 points, you need to find the vector from one point to the other two.
Vector3f toPoint2 = point2 - point1;
Vector3f toPoint3 = point3 - point1;
Once you have the two vectors, you need to find their cross product, which is orthogonal to both toPoint2 and toPoint3. In order to find the cross product, find the determinate of the following matrix:
[i j k ]
[toPoint2.x toPoint2.y toPoint2.z]
[toPoint3.x toPoint3.y toPoint3.z]
The cross product is:
Vector3f vec = new Vector3f(toPoint2.y * toPoint3.z - toPoint2.z * toPoint3.y,
toPoint2.z * toPoint3.x - toPoint2.x * toPoint3.z,
toPoint2.x * toPoint3.y - toPoint2.y * toPoint3.x)
This cross product will result in the normal vector of point1 with respect to point2 and point3.
EDIT: I found out that all the pixels were upside down because of the difference between screen and world coordinates, so that is no longer a problem.
EDIT: After following a suggestion from #TheVee (using absolute values), my image got much better, but I'm still seeing issues with color.
I having a little trouble with ray-tracing triangles. This is a follow-up to my previous question about the same topic. The answers to that question made me realize that I needed to take a different approach. The new approach I took worked much better, but I'm seeing a couple of issues with my raytracer now:
There is one triangle that never renders in color (it is always black, even though it's color is supposed to be yellow).
Here is what I am expecting to see:
But here is what I am actually seeing:
Addressing debugging the first problem, even if I remove all other objects (including the blue triangle), the yellow triangle is always rendered black, so I don't believe that it is an issues with my shadow rays that I am sending out. I suspect that it has to do with the angle that the triangle/plane is at relative to the camera.
Here is my process for ray-tracing triangles which is based off of the process in this website.
Determine if the ray intersects the plane.
If it does, determine if the ray intersects inside of the triangle (using parametric coordinates).
Here is the code for determining if the ray hits the plane:
private Vector getPlaneIntersectionVector(Ray ray)
{
double epsilon = 0.00000001;
Vector w0 = ray.getOrigin().subtract(getB());
double numerator = -(getPlaneNormal().dotProduct(w0));
double denominator = getPlaneNormal().dotProduct(ray.getDirection());
//ray is parallel to triangle plane
if (Math.abs(denominator) < epsilon)
{
//ray lies in triangle plane
if (numerator == 0)
{
return null;
}
//ray is disjoint from plane
else
{
return null;
}
}
double intersectionDistance = numerator / denominator;
//intersectionDistance < 0 means the "intersection" is behind the ray (pointing away from plane), so not a real intersection
return (intersectionDistance >= 0) ? ray.getLocationWithMagnitude(intersectionDistance) : null;
}
And once I have determined that the ray intersects the plane, here is the code to determine if the ray is inside the triangle:
private boolean isIntersectionVectorInsideTriangle(Vector planeIntersectionVector)
{
//Get edges of triangle
Vector u = getU();
Vector v = getV();
//Pre-compute unique five dot-products
double uu = u.dotProduct(u);
double uv = u.dotProduct(v);
double vv = v.dotProduct(v);
Vector w = planeIntersectionVector.subtract(getB());
double wu = w.dotProduct(u);
double wv = w.dotProduct(v);
double denominator = (uv * uv) - (uu * vv);
//get and test parametric coordinates
double s = ((uv * wv) - (vv * wu)) / denominator;
if (s < 0 || s > 1)
{
return false;
}
double t = ((uv * wu) - (uu * wv)) / denominator;
if (t < 0 || (s + t) > 1)
{
return false;
}
return true;
}
Is think that I am having some issue with my coloring. I think that it has to do with the normals of the various triangles. Here is the equation I am considering when I am building my lighting model for spheres and triangles:
Now, here is the code that does this:
public Color calculateIlluminationModel(Vector normal, boolean isInShadow, Scene scene, Ray ray, Vector intersectionPoint)
{
//c = cr * ca + cr * cl * max(0, n \dot l)) + cl * cp * max(0, e \dot r)^p
Vector lightSourceColor = getColorVector(scene.getLightColor()); //cl
Vector diffuseReflectanceColor = getColorVector(getMaterialColor()); //cr
Vector ambientColor = getColorVector(scene.getAmbientLightColor()); //ca
Vector specularHighlightColor = getColorVector(getSpecularHighlight()); //cp
Vector directionToLight = scene.getDirectionToLight().normalize(); //l
double angleBetweenLightAndNormal = directionToLight.dotProduct(normal);
Vector reflectionVector = normal.multiply(2).multiply(angleBetweenLightAndNormal).subtract(directionToLight).normalize(); //r
double visibilityTerm = isInShadow ? 0 : 1;
Vector ambientTerm = diffuseReflectanceColor.multiply(ambientColor);
double lambertianComponent = Math.max(0, angleBetweenLightAndNormal);
Vector diffuseTerm = diffuseReflectanceColor.multiply(lightSourceColor).multiply(lambertianComponent).multiply(visibilityTerm);
double angleBetweenEyeAndReflection = scene.getLookFrom().dotProduct(reflectionVector);
angleBetweenEyeAndReflection = Math.max(0, angleBetweenEyeAndReflection);
double phongComponent = Math.pow(angleBetweenEyeAndReflection, getPhongConstant());
Vector phongTerm = lightSourceColor.multiply(specularHighlightColor).multiply(phongComponent).multiply(visibilityTerm);
return getVectorColor(ambientTerm.add(diffuseTerm).add(phongTerm));
}
I am seeing that the dot product between the normal and the light source is -1 for the yellow triangle, and about -.707 for the blue triangle, so I'm not sure if the normal being the wrong way is the problem. Regardless, when I added made sure the angle between the light and the normal was positive (Math.abs(directionToLight.dotProduct(normal));), it caused the opposite problem:
I suspect that it will be a small typo/bug, but I need another pair of eyes to spot what I couldn't.
Note: My triangles have vertices(a,b,c), and the edges (u,v) are computed using a-b and c-b respectively (also, those are used for calculating the plane/triangle normal). A Vector is made up of an (x,y,z) point, and a Ray is made up of a origin Vector and a normalized direction Vector.
Here is how I am calculating normals for all triangles:
private Vector getPlaneNormal()
{
Vector v1 = getU();
Vector v2 = getV();
return v1.crossProduct(v2).normalize();
}
Please let me know if I left out anything that you think is important for solving these issues.
EDIT: After help from #TheVee, this is what I have at then end:
There are still problems with z-buffering, And with phong highlights with the triangles, but the problem I was trying to solve here was fixed.
It is an usual problem in ray tracing of scenes including planar objects that we hit them from a wrong side. The formulas containing the dot product are presented with an inherent assumption that light is incident at the object from a direction to which the outer-facing normal is pointing. This can be true only for half the possible orientations of your triangle and you've been in bad luck to orient it with its normal facing away from the light.
Technically speaking, in a physical world your triangle would not have zero volume. It's composed of some layer of material which is just thin. On either side it has a proper normal that points outside. Assigning a single normal is a simplification that's fair to take because the two only differ in sign.
However, if we made a simplification we need to account for it. Having what technically is an inwards facing normal in our formulas gives negative dot products, which case they are not made for. It's like light was coming from the inside of the object or that it hit a surface could not possibly be in its way. That's why they give an erroneous result. The negative value will subtract light from other sources, and depending on the magnitude and implementation may result in darkening, full black, or numerical underflow.
But because we know the correct normal is either what we're using or its negative, we can simply fix the cases at once by taking a preventive absolute value where a positive dot product is implicitly assumed (in your code, that's angleBetweenLightAndNormal). Some libraries like OpenGL do that for you, and on top use the additional information (the sign) to choose between two different materials (front and back) you may provide if desired. Alternatively, they can be set to not draw the back faces for solid object at all because they will be overdrawn by front faces in solid objects anyway (known as face culling), saving about half of the numerical work.
3d terrain.
I have 3 vertices that define a plane. (the 3 nearest pixels in a height map)
I have an x,z on that plane. (my location in the world)
How do you find the y-intercept? (so that I stand on the surface of that plane)
The equation of a plane is:
Ax + By + Cz = D, where D = Ax0 + By0 + Cz0,
If you have three vertices, find two vectors from the vertices. For example, for three vertices T, U, V, there would be, for example, a vector TU, and a a vector UV.
Find the cross product of the two vectors. That's your normal vector, n, which has three components n1, n2, and n3.
A = n1
B = n2
C = n3
Take one of the points. The coordinates of that point are x0, y0, and z0.
Input this into the equation to calculate D.
Then substitute your x and z for x and z and solve for y!
So in the end y is:
y = (A*x0 + B*y0 + C*z0 - A*x - C*z)/B
Somebody correct me if my algebra was wrong.
You can calculate the cross product like this:
For two vectors a and b, with components a1, a2, a3 and b1, b2, b3, respectively, the cross product is :
which goes to:
A = the coefficient of i-hat (the bolded i)
B = the coefficient of j-hat (the bolded j)
C = the coefficient of k-hat (the bolded k)
You say that you are looking at the three nearest pixels in the height map, which makes me assume that you have a regular grid from which you extract your vertices. In this case, you can use image interpolation methods to perform linear being similar to the answer from eboix or bicubic interpolation. Your height value is then equivalent to the brightness value in the image processing domain.
The math is much easier in the linear case, and the grid structure makes it possible to use a simple form. Let c by your cell size, and p, q, r the height values of your 3 vertices, like this
p q
+--.
| /
|/
r
and x, and y the distances along the legs of your right angled triangle. Where the triangle is of course the projection of your 3 vertices on the x, y plane. Then your interpolated height value is
z = (q-p)/c * x + (r-q)/c * y
Alright, so I'm trying to achieve whats in this image:
I believe this would be a barycentric coord system, but where the X always equals 1? Basically I need it to only increase/decrease when I move towards/away from the highest point in my triangle. This is the code I got for it so far (Note I'm using the LWJGL library in java).
public float getDist( Vector3f p, Vector3f a, Vector3f b, Vector3f c )
{
Vector3f v0 = new Vector3f(0,0,0);
Vector3f.sub( c, a, v0 );
Vector3f v1 = new Vector3f(0,0,0);
Vector3f.sub( b, a, v1);
Vector3f v2 = new Vector3f(0,0,0);
Vector3f.sub( p, a, v2 );
float dot00 = Vector3f.dot(v0, v0);
float dot01 = Vector3f.dot(v0, v1);
float dot02 = Vector3f.dot(v0, v2);
float dot11 = Vector3f.dot(v1, v1);
float dot12 = Vector3f.dot(v1, v2);
float inverse = 1.0f / (dot00 * dot11 - dot01 * dot01);
float u = (dot11 * dot02 - dot01 * dot12) * inverse;
float v = (dot00 * dot12 - dot01 * dot02) * inverse;
if((u >= 0) && (v >= 0) && (u + v <= 1)) return (float) (Math.sin(u) * Math.cos(v));
else return 0;
}
edit: I guess what I'm asking is: Is there a way to get the distance that a point inside a triangle has travailed from the lowest point the triangle has in space where 1 would be the highest point on the triangle (mosty far away from the lowist) without taking it's deviating vector into account? I.E. notice that the two red dots on the image have the same coords even though they have different dists from the top's x?
Edit2:
If I understand what you're saying: you have a triangle (abc) in 3D coordinates, and you want to evaluate the elevation of a fourth point (p) above one edge, proportionate to its opposite point:
b --------------- 1.0
|\
| \
| p\ ------------- (result)
| \
a----c ---------- 0.0
You are correct in that this result is one of three barycentric coordinates for a point on the triangle.
I recommend something like the following:
find the normal of the plane of the triangle: vABC = cross(c-a, b-a)
find a normal perpendicular to vABC and ac: vPerpAC = cross(c-a, vABC)
evaluate the vector ab with respect to it: sAB = dot(vPerpAC, b-a)
evaluate your target point: sAP = dot(vPerpAC, p-a)
your final result is the ratio of these last two evaluations: return sAP / sAB
This should be robust against points that aren't actually on the triangle: they are effectively projected perpendicularly onto the abc plane.
Note that, if you know abc beforehand, you can precalculate the following values:
the scaled normal: vScaled = vPerpAC / sAB
the scaled offset: sScaled = dot(vScaled, a)
and compute the result of a series of points p more efficiently:
return dot(vScaled, p) - sScaled
This effectively precomputes an oriented plane, pre-scaled to directly provide the desired result.
The code I'm using in my collision detection code is this:
(note: Vector3f is part of the LWJGL library.)
(Note2:Tri is a class composed of three of LWJGL's Vector3fs. v1, v2, and v3.)
public Vector<Tri> getTrisTouching(Vector3f pos, float radius){
Vector<Tri> tempVec = new Vector<Tri>();
for(int i = 0; i < tris.size(); i++){
Tri t = tris.get(i);
Vector3f one_to_point = new Vector3f(0,0,0);
Vector3f.sub(pos,t.v1,one_to_point); //Storing vector A->P
Vector3f one_to_two = new Vector3f(0,0,0);
Vector3f.sub(t.v2,t.v1, one_to_two); //Storing vector A->B
Vector3f one_to_three = new Vector3f(0,0,0);
Vector3f.sub(t.v3, t.v1, one_to_three); //Storing vector A->C
float q1 = Vector3f.dot(one_to_point, one_to_two) / one_to_two.lengthSquared(); // The normalized "distance" from a to
float q2 = Vector3f.dot(one_to_point, one_to_three) / one_to_three.lengthSquared(); // The normalized "distance" from a to
if (q1 > 0 && q2 > 0 && q1 + q2 < 1){
tempVec.add(t);
}
}
return tempVec;
}
My question is how do I correctly see if a point in space is touching one of my triangles?
To test if your point is inside the triangle, create a ray with its origin at the test point and extend it to infinity. A nice easy one would be a ray which is horizontal ( e.g. y constant, and x increases to infinity. Then count the number of times it intersects with one of your polygon edges. Zero or an even number of intersections means you are outside the triangle. The nice thing about this it works not just for triangles but any polygon.
http://erich.realtimerendering.com/ptinpoly/
The only way I can help you is by providing you with this link.
Unfortunately, I'm not very good with LWJGL Geometry so here you are. - Vector3f
Hope it helps! If it does, please tick the answer to accept.