GLSL cube signed distance field implementation explanation? - geometry

I've been looking at and trying to understand the following bit of code
float sdBox( vec3 p, vec3 b )
{
vec3 d = abs(p) - b;
return min(max(d.x,max(d.y,d.z)),0.0) +
length(max(d,0.0));
}
I understand that length(d) handles the SDF case where the point is off to the 'corner' (ie. all components of d are positive) and that max(d.x, d.y, d.z) gives us the proper distance in all other cases. What I don't understand is how these two are combined here without the use of an if statement to check the signs of d's components.
When all of the d components are positive, the return expression can be reduced to length(d) because of the way min/max will evaluate - and when all of the d components are negative, we get max(d.x, d.y, d.z). But how am I supposed to understand the in-between cases? The ones where the components of d have mixed signs?
I've been trying to graph it out to no avail. I would really appreciate it if someone could explain this to me in geometrical/mathematical terms. Thanks.

If you like to know how It works It's better do the following steps:
1.first of all you should know definitions of shapes
2.It's always better to consider 2D shape of them, because three dimensions may be complex for you.
so let me to explain some shapes:
Circle
A circle is a simple closed shape. It is the set of all points in a plane that are at a given distance from a given point, the center.
You can use distance(), length() or sqrt() to calculate the distance to the center of the billboard.
The book of shaders - Chapter 7
Square
In geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles (90-degree angles).
I describe 2D shapes In before section now let me to describe 3D definition.
Sphere
A sphere is a perfectly round geometrical object in three-dimensional space that is the surface of a completely round ball.
Like a circle, which geometrically is an object in two-dimensional space, a sphere is defined mathematically as the set of points that are all at the same distance r from a given point, but in three-dimensional space.
Refrence - Wikipedia
Cube
In geometry, a cube is a three-dimensional solid object bounded by six square faces, facets or sides, with three meeting at each vertex.
Refrence : Wikipedia
Modeling with distance functions
now It's time to understanding modeling with distance functions
Sphere
As mentioned In last sections.In below code length() used to calculate the distance to the center of the billboard , and you can scale this shape by s parameter.
//Sphere - signed - exact
/// <param name="p">Position.</param>
/// <param name="s">Scale.</param>
float sdSphere( vec3 p, float s )
{
return length(p)-s;
}
Box
// Box - unsigned - exact
/// <param name="p">Position.</param>
/// <param name="b">Bound(Scale).</param>
float udBox( vec3 p, vec3 b )
{
return length(max(abs(p)-b,0.0));
}
length() used like previous example.
next we have max(x,0) It called Positive and negative parts
this is mean below code is equivalent:
float udBox( vec3 p, vec3 b )
{
vec3 value = abs(p)-b;
if(value.x<0.){
value.x = 0.;
}
if(value.y<0.){
value.y = 0.;
}
if(value.z<0.){
value.z = 0.;
}
return length(value);
}
step 1
if(value.x<0.){
value.x = 0.;
}
step 2
if(value.y<0.){
value.y = 0.;
}
step 3
if(value.z<0.){
value.z = 0.;
}
step 4
next we have absolution function.It used to remove additional parts.
Absolution Steps
Absolution step 1
if(value.x < -1.){
value.x = 1.;
}
Absolution step 2
if(value.y < -1.){
value.y = 1.;
}
Absolution step 3
if(value.z < -1.){
value.z = 1.;
}
Also you can make any shape by using Constructive solid geometry.
CSG is built on 3 primitive operations: intersection ( ∩ ), union ( ∪ ), and difference ( - ).
It turns out these operations are all concisely expressible when combining two surfaces expressed as SDFs.
float intersectSDF(float distA, float distB) {
return max(distA, distB);
}
float unionSDF(float distA, float distB) {
return min(distA, distB);
}
float differenceSDF(float distA, float distB) {
return max(distA, -distB);
}

I figured it out a while ago and wrote about this extensively in a blog post here: http://fabricecastel.github.io/blog/2016-02-11/main.html
Here's an excerpt (see the full post for a full explanation):
Consider the four points, A, B, C and D. Let's crudely reduce the distance function to try and get rid of the min/max functions in order to understand their effect (since that's what's puzzling about this function). The notation below is a little sloppy, I'm using square brackets to denote 2D vectors.
// 2D version of the function
d(p) = min(max(p.x, p.y), 0)
+ length(max(p, 0))
---
d(A) = min(max(-1, -1), 0)
+ length(max([-1, -1], 0))
d(A) = -1 + length[0, 0]
---
d(B) = min(max(1, 1), 0)
+ length(max([1, 1], 0))
d(B) = 0 + length[1, 1]
Ok, so far nothing special. When A is inside the square, we essentially get our first distance function based on planes/lines and when B is in the area where our first distance function is inaccurate, it gets zeroed out and we get the second distance function (the length). The trick lies in the other two cases C and D. Let's work them out.
d(C) = min(max(-1, 1), 0)
+ length(max([-1, 1], 0))
d(C) = 0 + length[0, 1]
---
d(D) = min(max(1, -1), 0)
+ length(max([-1, 1], 0))
d(D) = 0 + length[1, 0]
If you look back to the graph above, you'll note C' and D'. Those points have coordinates [0,1] and [1,0], respectively. This method uses the fact that both distance fields intersect on the axes - that D and D' lie at the same distance from the square.
If we zero out all negative component of a vector and take its length we will get the proper distance between the point and the square (for points outside of the square only). This is what max(d,0.0) does; a component-wise max operation. So long as the vector has at least one positive component, min(max(d.x,d.y),0.0) will resolve to 0 leaving us with only the second part of the equation. In the event that the point is inside the square, we want to return the first part of the equation (since it represents our first distance function). If all components of the vector are negative it's easy to see our condition will be met.
This understanding should tranlsate back into 3D seamlessly once you wrap your head around it. You may or may not have to draw a few graphs by hand to really "get" it - I know I did and would encourage you to do so if you're dissatisfied with my explanation.
Working this implementation into our own code, we get this:
float distanceToNearestSurface(vec3 p){
float s = 1.0;
vec3 d = abs(p) - vec3(s);
return min(max(d.x, max(d.y,d.z)), 0.0)
+ length(max(d,0.0));
}
And there you have it.

Related

Determine if an arc represents an reflex or acute angle

I have this seemingly simple but very confusing problem.
Given I have a set of vertices (x1,y1), (x2,y2), (x3,y3)...... representing an arc. The points can either be clockwise or counter clockwise, but are all similarly ordered.
And I know the center of the arc (xc,yc).
How can I tell if the arc subtends an acute/obtuse or reflex angle?
One obvious solution is to take the difference of atan2((last_pt)-(center)) and atan2((first_pt)-(center))). But if the arc goes through the point where PI become -PI, this method breaks down.
Also, since the arc points are derived from a rather noisy pixelated picture, the vertices are not exactly smooth.
Picture of a acute and reflex arc
I cant wrap my brain around solving this problem.
Thanks for your help!
Working with 2D angles is a pain for the reason you described, so it's better to work with vector math instead, which is rotationally invariant.
Define the 2D cross-product, A ^ B = Ax * By - Ay * Bx. This is positive if A is clockwise rotated relative to B, and vice versa.
The logic:
Compute C = (last_pt - center) ^ (first_pt - center)
If C = 0, the arc is either closed or 180-degree (forgot the name for this)
If C > 0, the arc must either be (i) clockwise and acute/obtuse or (ii) anti-clockwise and reflex
If C < 0, the opposite applies
Pseudocode:
int arc_type(Point first, Point last, Point center, bool clockwise)
{
// cross-product
float C = (last.x - center.x) * (first.y - center.y)
- (last.y - center.y) * (first.x - center.x);
if (Math.abs(C) < /* small epsilon */)
return 0; // 180-degree
return ((C > 0) ^ clockwise) ? 1 // reflex
: -1; // acute / obtuse
}
Note that if you don't have prior knowledge of whether the arc is clockwise or anti-, you can use the same cross-product method on adjacent points. You need to ensure that the order of the points is consistent - if not you can, again using the cross-product, sort them by (relative) angle.

Given a list of points of a polygon how do find which ones are part of a concave angle?

I have a list of consecutive points and I need to find the coordinates of a polygon some size larger. I can calculate each of the points in the new polygon if it has convex angles, but I'm not sure how to adjust for when the angles are concave.
Concave angles can be treated in exactly the same way as convex ones: For each vertex you generate lines that are parallel to the two original segments but shifted by your offset value. Then the vertex is replaced with the intersection of these two lines.
The difficulty is that the resulting polygon can have intersections if the original one has one or more concave angles. There are different ways to handle these intersections. Generally they can produce inner contours (holes in the polygon) but maybe you are only interested in the outer contour.
In any case you have to find the intersection points first. If you don't find any, you are finished.
Otherwise find a start point of which you can be sure that it is on the outer contour. In many cases you can take the one with smallest X coordinate for that. Then trace the polygon contour until you get to the first intersection. Add the intersection to the polygon. If you are only interested in the outer contour, then skip all following vertices until you get back to the intersection point. Then continue to add the vertexes to the resulting polygon until you get to the next intersection and so on.
If you also need the inner contours (holes) it gets a bit more complicated, but I guess you can figure this out.
I also need to add that you should pe prepared for special cases like (almost) duplicate edges that cause numerical problems. Generally this is not a trivial task, so if possible, try to find a suitable polygon library.
For this problem I found a relatively simple solution for figuring out whether the calculated point was inside or outside the original polygon. Check to see whether the newly formed line intersects the original polygon's line. A formula can be found here http://www.geeksforgeeks.org/orientation-3-ordered-points/.
Suppose your polygon is given in counter-clockwise order. Let P1=(x1,y1), P2=(x2,y2) and P3=(x3,y3) be consecutive vertices. You want to know if the angle at P2 is “concave” i.e. more than 180 degrees. Let V1=(x4,y4)=P2-P1 and V2=(x5,y5)=P3-P2. Compute the “cross product” V1 x V2 = (x4.y5-x5.y4). This is negative iff the angle is concave.
Here is a code in C# that receives a list of Vector2D representing the ordered points of a polygon and returns a list with the angles of each vertex. It first checks if the points are clockwise or counterclockwise, and then it loops through the points calculating the sign of the cross product (z) for each triple of angles, and compare the value of the cross product to the clockwise function result to check if the calculated angle to that point needs to be the calculated angle or adjusted to 360-angle. The IsClockwise function was obtained in this discussion: How to determine if a list of polygon points are in clockwise order?
public bool IsClockwise(List<Vector2> vertices)
{
double sum = 0.0;
for (int i = 0; i < vertices.Count; i++)
{
Vector2 v1 = vertices[i];
Vector2 v2 = vertices[(i + 1) % vertices.Count];
sum += (v2.x - v1.x) * (v2.y + v1.y);
}
return sum > 0.0;
}
List<float> estimatePolygonAngles(List<Vector2> vertices)
{
if (vertices.Count < 3)
return null;
//1. check if the points are clockwise or counterclockwise:
int clockwise = (IsClockwise(vertices) ? 1 : -1);
List<float> angles = new List<float>();
List<float> crossProductsSigns = new List<float>();
Vector2 v1, v2;
//2. calculate the angles between each triple of vertices (first and last angles are computed separetely because index of the array):
v1 = vertices[vertices.Count - 1] - vertices[0];
v2 = vertices[1] - vertices[0];
angles.Add(Vector2.Angle(v1, v2));
crossProductsSigns.Add(Vector3.Cross(v1, v2).z > 0 ? 1 : -1);
for (int i = 1; i < vertices.Count-1; i++)
{
v1 = vertices[i-1] - vertices[i];
v2 = vertices[i+1] - vertices[i];
angles.Add(Vector2.Angle(v1, v2));
crossProductsSigns.Add(Vector3.Cross(v1, v2).z > 0 ? 1 : -1);
}
v1 = vertices[vertices.Count - 2] - vertices[vertices.Count - 1];
v2 = vertices[0] - vertices[vertices.Count - 1];
angles.Add(Vector2.Angle(v1, v2));
crossProductsSigns.Add(Vector3.Cross(v1, v2).z > 0 ? 1 : -1);
//3. for each computed angle, check if the cross product is the same as the as the direction provided by the clockwise function, if dont, the angle must be adjusted to 360-angle
for (int i = 0; i < vertices.Count; i++)
{
if (crossProductsSigns[i] != clockwise)
angles[i] = 360.0f - angles[i];
}
return angles;
}

How to check for convexity of a 3d mesh?

Is there a fast way to do this? Searching online shows convexity of functions or single polygons. But I need the ability to check this for the whole model. An object can have convex faces but can be concave as a whole like a torus.
Kneejerk: if you build a leafy BSP tree and end up with all your geometry at one node, the object is convex.
Slightly smarter way to approach the same solution: for each polygon, get the hyperplane. Make sure every vertex in the model is behind that hyperplane.
Equivalently: check the line segment between every pair of vertices; if it doesn't intersect any faces then the object is convex.
I guess you could also get the convex hull, via quickhull or whatever, and compare it to the original object. Or, similarly, get the convex hull and check that every vertex of the original object lies on a face of the hull.
For every face, compute the equation of the plane of support and check that all vertices* yield the same sign when plugged in the plane equation.
Will take time O(F.V), for F faces and V vertices.
*For safety, disregard the vertices of the face being processed.
Alternatively, compute the 3D convex hull, in time O(V.Log(V)). If at any stage in the algorithm a vertex gets discarded, then the polyhedron was not convex.
bool IsConvex(std::vector<vec3> &points, std::vector<int> &triangles, float threshold = 0.001)
{
for (unsigned long i = 0; i < triangles.size() / 3; i++)
{
vec3 Atmp = points[triangles[i * 3 + 0]];
vec3 Btmp = points[triangles[i * 3 + 1]];
vec3 Ctmp = points[triangles[i * 3 + 2]];
btVector3 A(Atmp.x, Atmp.y, Atmp.z);
btVector3 B(Btmp.x, Btmp.y, Btmp.z);
btVector3 C(Ctmp.x, Ctmp.y, Ctmp.z);
B -= A;
C -= A;
btVector3 BCNorm = B.cross(C).normalized();
float checkPoint = btVector3(points[0].x - A.x(), points[0].y - A.y(), points[0].z - A.z()).dot(BCNorm);
for (unsigned long j = 0; j < points.size(); j++)
{
float dist = btVector3(points[j].x - A.x(), points[j].y - A.y(), points[j].z - A.z()).dot(BCNorm);
if((std::abs(checkPoint) > threshold) && (std::abs(dist) > threshold) && (checkPoint * dist < 0))
{
return false;
}
}
}
return true;
}
trimesh is a Python library that can load a 3D mesh and evaluates if mesh is convex or not.
import trimesh
mesh = trimesh.load('my_mesh_file')
print(mesh.is_convex)
Code is given here.
It can be run from a command line with the following instructions:
python -m pip install trimesh
python -c "import trimesh; mesh = trimesh.load('my_mesh_file'); print(mesh.is_convex)"
You can accelerate the plane-vertex tests by adding all vertices to a tree structure first, so you can reject whole leaves if their bounds don't intersect the plane.
The BSP idea should actually be identical to testing all triangle planes, as no BSP leaf will be able to subdivide the set of vertices for a convex object.
You probably want to include an epsilon for your plane tests, as both floating point precision and modelling precision for manually created meshes can result in vertices slightly above a plane.

Finding most distant point in circle from point

I'm trying to find the best way to get the most distant point of a circle from a specified point in 2D space. What I have found so far, is how to get the distance between the point and the circle position, but I'm not entirely sure how to expand this to find the most distant point of the circle.
The known variables are:
Point a
Point b (circle position)
Radius r (circle radius)
To find the distance between the point and the circle position, I have found this:
xd = x2 - x1
yd = y2 - y1
Distance = SquareRoot(xd * xd + yd * yd)
It seems to me, this is part of the solution. How would this be expanded to get the position of Point x in the below image?
As an additional but optional part of the question: I have read in some places that it would be possible to get the distance portion without using the Square Root, which is very performance intensive and should be avoided if fast code is necessary. In my case, I would be doing this calculation quite often; Any comments on this within the context of the main question would be welcome too.
What about this?
Calculate A-B.
We now have a vector pointing from the center of the circle towards A (if B is the origin, skip this and just consider point A a vector).
Normalize.
Now we have a well defined length (the length is 1)
If the circle is not of unit radius, multiply by radius. If it is unit radius, skip this.
Now we have the correct length.
Invert sign (can be done in one step with 3., just multiply with the negative radius)
Now our vector points in the correct direction.
Add B (if B is the origin, skip this).
Now our vector is offset correctly so its endpoint is the point we want.
(Alternatively, you could calculate B-A to save the negation, but then you have to do one more operation to offset the origin correctly.)
By the way, it works the same in 3D, except the circle would be a sphere, and the vectors would have 3 components (or 4, if you use homogenous coords, in this case remember -- for correctness -- setting w to 0 when "turning points into vectors" and to 1 at the end when making a point from the vector).
EDIT:
(in reply of pseudocode)
Assuming you have a vec2 class which is a struct of two float numbers with operators for vector subtraction and scalar multiplicaion (pretty trivial, around a dozen lines of code) and a function normalize which needs to be no more than a shorthand for multiplying with inv_sqrt(x*x+y*y), the pseudocode (my pseudocode here is something like a C++/GLSL mix) could look something like this:
vec2 most_distant_on_circle(vec2 const& B, float r, vec2 const& A)
{
vec2 P(A - B);
normalize(P);
return -r * P + B;
}
Most math libraries that you'd use should have all of these functions and types built-in. HLSL and GLSL have them as first type primitives and intrinsic functions. Some GPUs even have a dedicated normalize instruction.

Best fit square to quadrilateral

I've got a shape consisting of four points, A, B, C and D, of which the only their position is known. The goal is to transform these points to have specific angles and offsets relative to each other.
For example: A(-1,-1) B(2,-1) C(1,1) D(-2,1), which should be transformed to a perfect square (all angles 90) with offsets between AB, BC, CD and AD all being 2. The result should be a square slightly rotated counter-clockwise.
What would be the most efficient way to do this?
I'm using this for a simple block simulation program.
As Mark alluded, we can use constrained optimization to find the side 2 square that minimizes the square of the distance to the corners of the original.
We need to minimize f = (a-A)^2 + (b-B)^2 + (c-C)^2 + (d-D)^2 (where the square is actually a dot product of the vector argument with itself) subject to some constraints.
Following the method of Lagrange multipliers, I chose the following distance constraints:
g1 = (a-b)^2 - 4
g2 = (c-b)^2 - 4
g3 = (d-c)^2 - 4
and the following angle constraints:
g4 = (b-a).(c-b)
g5 = (c-b).(d-c)
A quick napkin sketch should convince you that these constraints are sufficient.
We then want to minimize f subject to the g's all being zero.
The Lagrange function is:
L = f + Sum(i = 1 to 5, li gi)
where the lis are the Lagrange multipliers.
The gradient is non-linear, so we have to take a hessian and use multivariate Newton's method to iterate to a solution.
Here's the solution I got (red) for the data given (black):
This took 5 iterations, after which the L2 norm of the step was 6.5106e-9.
While Codie CodeMonkey's solution is a perfectly valid one (and a great use case for the Lagrangian Multipliers at that), I believe that it's worth mentioning that if the side length is not given this particular problem actually has a closed form solution.
We would like to minimise the distance between the corners of our fitted square and the ones of the given quadrilateral. This is equivalent to minimising the cost function:
f(x1,...,y4) = (x1-ax)^2+(y1-ay)^2 + (x2-bx)^2+(y2-by)^2 +
(x3-cx)^2+(y3-cy)^2 + (x4-dx)^2+(y4-dy)^2
Where Pi = (xi,yi) are the corners of the fitted square and A = (ax,ay) through D = (dx,dy) represent the given corners of the quadrilateral in clockwise order. Since we are fitting a square we have certain contraints regarding the positions of the four corners. Actually, if two opposite corners are given, they are enough to describe a unique square (save for the mirror image on the diagonal).
Parametrization of the points
This means that two opposite corners are enough to represent our target square. We can parametrise the two remaining corners using the components of the first two. In the above example we express P2 and P4 in terms of P1 = (x1,y1) and P3 = (x3,y3). If you need a visualisation of the geometrical intuition behind the parametrisation of a square you can play with the interactive version.
P2 = (x2,y2) = ( (x1+x3-y3+y1)/2 , (y1+y3-x1+x3)/2 )
P4 = (x4,y4) = ( (x1+x3+y3-y1)/2 , (y1+y3+x1-x3)/2 )
Substituting for x2,x4,y2,y4 means that f(x1,...,y4) can be rewritten to:
f(x1,x3,y1,y3) = (x1-ax)^2+(y1-ay)^2 + ((x1+x3-y3+y1)/2-bx)^2+((y1+y3-x1+x3)/2-by)^2 +
(x3-cx)^2+(y3-cy)^2 + ((x1+x3+y3-y1)/2-dx)^2+((y1+y3+x1-x3)/2-dy)^2
a function which only depends on x1,x3,y1,y3. To find the minimum of the resulting function we then set the partial derivatives of f(x1,x3,y1,y3) equal to zero. They are the following:
df/dx1 = 4x1-dy-dx+by-bx-2ax = 0 --> x1 = ( dy+dx-by+bx+2ax)/4
df/dx3 = 4x3+dy-dx-by-bx-2cx = 0 --> x3 = (-dy+dx+by+bx+2cx)/4
df/dy1 = 4y1-dy+dx-by-bx-2ay = 0 --> y1 = ( dy-dx+by+bx+2ay)/4
df/dy3 = 4y3-dy-dx-2cy-by+bx = 0 --> y3 = ( dy+dx+by-bx+2cy)/4
You may see where this is going, as simple rearrangment of the terms leads to the final solution.
Final solution

Resources