I have a polyline composed of multiple line segments. The line is very complex and squiggles all over the place in 3D, so for simplicity's sake let's say it looks something like this
I want to render it in 3D. Currently, I do a very simple process where I just generate a cylinder for each segment:
This is decent, but looks bad where the line changes direction. It is also wasteful - each of the direction changes requires twices as many vertices as is strictly necessary. I would be much happier with an approach that generated shapes like this:
At first I didn't think it would be too hard, but the more I've worked on it the more I've found it to be surprisingly nontrivial. I'm working in C#, and if this were in 2D I would just use Clipper, but I can't find any libraries or resources for how to solve this problem in 3D. It's okay if the solution isn't always perfect or sometimes leads to self-intersections or things of that nature. Anyone have any guidance?
So in a mathematical sense, the intersection of two cylinders is an ellipse. If I give you where the semi-major axis point on the ellipse is and the semi-minor axis you could calculate any number (like numsides) nodes on the ellipse.
Take the node connecting two segments located at a point p and define the two vectors of the ellipse as follows. a is the semi-major axis and b is the semi-minor axis
Each joining line segment has unit directions vectors e_1 and e_2 and the cylinder has radius R.
Then the intersection ellipse would be defined from the vectors a and b:
Then find a point c around the ellipse use the following parameterization with t = 0..1
Here is some C# code that calculates numsides points around the ellipse
// Vectors p, a, b defined
for(int i=0; i<numsides; i++)
{
double t = (1.0*i)/numsides
Vector c = p + a*Math.Cos(2*Math.PI*t) + b*Math.Sin(2*Math.PI*t)
// use/store c as needed for the mesh generation
}
I found this site which had an elegant solution. Starting with some points around the first line segment making up your polyline, you compute the intersection of the line parallel to the current segment that passes through each point and the plane formed by the intersection of the two current line segments.
I'm trying to work on a game mechanic in c# that involves connecting vertices and forming polygons.
There can be any number of 5 - 30 vertices. Each vertice can be connected with a straight line(The lines cannot intersect). When the line closes a polygon the inside of the polygon is colored in a specific color. (You cannot close a polygon if there would be a point inside it during the closing)
For example two pictures below cannot happen:
However, this can:
What i am having trouble with is how to discern the polygon i have just closed and remembering it (in case i close a polygon that shares an edge with it). I can have multiple closed polygons until all lines that can be drawn from each vertice without breaching the intersect rule can be drawn.
I tried remembering lines that were drawn AB, ED, CD, CA etc.. and looking for a cycle, but when i close multiple polygons i need more information to know which polygon has already been closed. But I'm having difficulty figuring out how to do so.
For example (picture below), if the line n was drawn i want to find the polygon that was just made.
Does anyone have any idea how i might achieve this?
Any idea, help, insight would be helpfull.
Possibly a bit simplistic, but you can store a Dictionary<Face,List<Vertex>> which you can interrogate with linq.
You can simplify it by adding the reverse lookup. Dictionary<Vertex, List<Faces>>
Scenario 1: Path touches edges which are part of the same face
To test a new path DC you get the 2 vertices, D and C and find any faces which contain both. Start with D in the List<Vertex> and create the path to C.
Now do the same with C -> D.
You now have 2 paths, D -> E -> C and C -> A -> B -> D both form valid faces using D -> C so now you have to enumerate all the vertices and eliminate any faces which contain an existing vertex.
Scenario 2: Path touches an edge which are not part of any face
This path is open.
Scenario 3: Path touches eges which are part of different faces
Face1: ABDEC
Face2: AGF
Testing the path FC. F is part of Face2 C is part of Face1.
Find intersections: Face1.Face2 == A it's the only point in both lists, this time you get 2 sets of 2 paths.
FA
FGA
AC
ABDEC
To go from F to A, these paths multiply
FAC
FGAC
FABDEC
FGABDEC
These faces can now be tested for validity.
It might be easier for this an more complex scenarios (3 faces touching, faces sharing edges) to also keep a graph of all connected edges, this would give you an easier way to detect possible paths between 2 vertices.
Note that ANY path containing 3 vertices forms a possible face which can be checked for validity
When a player trys to claim a new edge you can:
check that the edge does not cross any of the existing claimed edges;
perform a breadth-first search of the graph formed by the claimed edges (which are not already on the boundary of two polygons) to see if there is an existing path starting at one end of the new edge which reaches the other end of the new edge - in which case a polygon will be formed; and
if a polygon has been formed:
check to see if there are any vertices inside the polygon - in which case the player cannot claim that edge.
Each edge has two sides. The interior of the formed polygon will be on one side of each edge along its boundary - you can track this and then any subsequent polygons which are also bounded by one (or more) of those edges must be on the other side of those edge(s) to be a valid selection within your game. If an edge has claimed polygons on both sides then it cannot be on the boundary of any subsequent polygons.
You may need to generate a convex hull around the points to exclude the exterior polygon so that when players are forming polygons they are restricted to the interior of the convex hull.
I am working on cutting meshes. What am I exactly trying to achieve is that:
Input - two meshes(procedurally generated of course)
Output - three meshes(or more, depends on the given meshes)
A - which is a meshA substract mesh B,
B - which is a common part of meshes A and B,
C - which is a mesh B substract mesh A.
I am using the Triangulator that for the given set of vertices creates triangles for me. All I have to do is to give him those vertices, and here goes the question. Is there any algorithm that would help me to do this? Maybe your brilliant idea that came into your mind at the time you saw this picture? I am working in Unity(C#) so anything related to Unity Tools is helpful aswell. Thanks !
EDIT:
I am using this clipping library: http://sourceforge.net/projects/polyclipping/ and everything works fine untill this case:
I am trying to get the difference A-B and it should look like the one from Picture 2), unfortunately the output is mesh A and mesh B as in the picture 1).
What i do:
Clipper c = new Clipper();
c.AddPath(here goes the vertices of mesh A, polyType.Subject, true);
c.AddPath(here goes the vertices of mesh B, polyType.Clip, true);
c.Execute(ClipType.ctDIfference, a list of lists for my output, PolyFillType.NonZero, PolyFillType.NonZero);
I've already tried to change PolyFillTypes but it changed nothing. And here I am, asking for your advices :)
It is enough to work with mesh boundaries. With that you have two polygons and problem of finding there intersection. Some external library can be used for it, like GPC.
After intersection is found just perform triangulation of these three polygons.
There are a set of points S in n dimensional space. I want to test a given point P is inside the region of S.
Since this is n dimensional space, points should form a polytope. Then the question is to determine whether a given point is inside the convex polytope.
I find this for 3-D polyhedrons but C++ libraries were not meaningful and I couldn't find their definitions. Besides it doesn't check the boundary conditions.
Another algorithm I found is for 2D polygons. I couldn't modify it since it is not clearly written. I can extend it of course but I'm not an expert in this domain so it's better to ask first.
Finally I found an algorithm for triangulation for concave polygon but I don't think it fits to my case.
Not sure what exactly you are asking, it seems you have several problems. First to compute Convex Hull of a point set. In 2d you can use BOOST or CGAL. For 3d CGAL. Not sure if they handle higher dimensions. For interior check, one way is (as the link you posted states) to check the ray intersection from the point of query to a known exterior point. The point of intersection of the ray (for interior point) should lie on a plane with normal pointing in the same direction as your ray. Meaning you are exiting the volume. A more efficient way would be to use something like a Binary Space Partitioning Tree (BSP). There are many links with tutorials on how that works.
From your description, you have established that S is convex. If that is the case you apply the hyperplane separation theorem (http://en.wikipedia.org/wiki/Hyperplane_separation_theorem)
Find the point Q in S that is closest to P.
Construct a hyperplane H that lies on Q and is normal to P-Q
Test all the points in S on which side of H are on.
If they are all either on the plane or on the opposite side of H compared to P, then P is either on or outside of S. If some points are in front of H, and others are behind H, then P is inside S.
I am looking for an algorithm to generate equally distributed points inside a polygon.
Here is the scenario:
I have a polygon specified by the coordinates of the points at the corners (x, y) for each point. And I have the number of points to generate inside the polygon.
For example lets say I have a polygon containing 5 points: (1, 1) ; (1, 2) ; (2, 3) ; (3, 2) ; and (3, 1)
And I need to generate 20 equally distanced points inside that polygon.
Note: Some polygons may not support equally distributed points, but I'm looking to distribute the points in a way to cover all the region of the polygon with as much consistency as possible. (what i mean is I don't want a part with a lot more points than another)
Is there an algorithm to do so? or maybe a library
I am working on a C# application, but any language is ok, since I only need the algorithm and I can translate it.
Thanks a lot for any help
The simple approach I use is:
Triangulate the polygon. Ear clipping is entirely adequate, as all you need is a dissection of the polygon into a set of non-overlapping triangles.
Compute the area of each triangle. Sample from each triangle proportionally to the area of that triangle relative to the whole. This costs only a single uniform random number per sample.
Once a point is determined to have come from a given triangle, sample uniformly over the triangle. This is itself easier than you might think.
So really it all comes down to how do you sample within a triangle. This is easily enough done. A triangle is defined by 3 vertices. I'll call them P1, P2, P3.
Pick ANY edge of the triangle. Generate a point (P4) that lies uniformly along that edge. Thus if P1 and P2 are the coordinates of the corresponding end points, then P will be a uniformly sampled point along that edge, if r has uniform distribution on the interval [0,1].
P4 = (1-r)*P1 + r*P2
Next, sample along the line segment between P3 and P4, but do so non-uniformly. If s is a uniform random number on the interval [0,1], then
P5 = (1-sqrt(s))*P3 + sqrt(s)*P4
r and s are independent pseudo-random numbers of course. Then P5 will be randomly sampled, uniform over the triangle.
The nice thing is it needs no rejection scheme to implement, so long, thin polygons are not a problem. And for each sample, the cost is only in the need to generate three random numbers per event. Since ear clipping is rather simply done and an efficient task, the sampling will be efficient, even for nasty looking polygons or non-convex polygons.
An easy way to do this is this:
Calculate the bounding box
Generate points in that box
Discard all points not in the polygon of interest
This approach generates a certain amount of wasted points. For a triangle, it is never more than 50%. For arbitrary polygons this can be arbitrarily high so you need to see if it works for you.
For arbitrary polys you can decompose the polygon into triangles first which allows you to get to a guaranteed upper bound of wasted points: 50%.
For equally distanced points, generate points from a space-filling curve (and discard all points that are not in the polygon).
You can use Lloyd’s algorithm:
https://en.m.wikipedia.org/wiki/Lloyd%27s_algorithm
You can try the {spatialEco} package (https://cran.r-project.org/web/packages/spatialEco/index.html)
and apply the function sample.poly (https://www.rdocumentation.org/packages/spatialEco/versions/1.3-2/topics/sample.poly)
You can try this code:
library(rgeos)
library(spatialEco)
mypoly = readWKT("POLYGON((1 1,5 1,5 5,1 5,1 1))")
plot(mypoly)
points = sample.poly(mypoly, n= 20, type = "regular")
#points2 = sample.poly(mypoly, n= 20, type = "stratified")
#another type which may answer your problem
plot(points, col="red", add=T)
The easy answer comes from an easier question: How to generate a given number of randomly distributed points from the uniform distribution that will all fit inside a given polygon?
The easy answer is this: find the bounding box of your polygon (let's say it's [a,b] x [c,d]), then keep generating pairs of real numbers, one from U(a,b), the other from U(b,c), until you have n coordinate pairs that fit inside your polygon. This is simple to program, but, if your polygon is very jagged, or thin and skewed, very wasteful and slow.
For a better answer, find the smallest rotated rectangular bounding box, and do the above in transformed coordinates.
Genettic algorithms can do it rather quickly
Reffer to GENETIC ALGORITHMS FOR GRAPH LAYOUTS WITH GEOMETRIC CONSTRAINTS
You can use Force-Directed Graph for that...
Look at http://en.wikipedia.org/wiki/Force-based_algorithms_(graph_drawing)
it defiantly can throw you a bone.
I didn't try it ever,
but i remmember there is a possiblity to set a Fix for some Vertices in the Graph
Your Algorithm will eventually be like
Create a Graph G = Closed Path of the Vertices in V
Fix the Vertecies in place
Add N Verticies to the Graph and Fully connect them with Edges with equal tension value 1.0
Run_force_graph(G)
Scale Graph to bounded Box of
Though it wont be absolute because some convex shapes may produce wiered results (take a Star)
LASTLY: didn't read , but it seems relevant by the title and abstract
take a look at Consistent Graph Layout for Weighted Graphs
Hope this helps...
A better answer comes from a better question. Suppose you want to put a set of n watchtowers to cover a polygon. You could see this as an optimization problem: find the 2n coordinates of the n points that will minimize a cost function (or maximize a value function) that fits your goal. One possible cost function could calculate, for each point, the distance to its closest neighbor or the boundary of the polygon, whichever is less, and calculate the variance of this sequence as a measure of "non-uniformity". You could use a random set of n points, obtained as above, as your initial solution.
I've seen such a "watchtower problem" in some book. Algorithms, calculus, or optimization.
#Youssef: sorry about the delay; a friend came, and a network hiccuped.
#others: have some patience, don't be so trigger-happy.