Connected vertices from polygon, how to get the new polygons - javascript

I have a polygon, where some vertices are connected with lines (the startpoint and the endpoint are a vertice of the polygon). For each line (that connects vertices) are 4 rules:
The line doesn't intersect with other lines
The line doesn't intersect with the polygon
The line is completely contained by the polygon
The line isn't an edge of the polygon
Example:
In the image, the red lines are bad lines,
the black lines are polygon edges and the green line is a good line.
Line h is good
Line i is bad, because it intersects the polygon
Line j is bad, because it intersects line h and i
Line k is bad, because it is an edge of the polygon
Line g is bad, because it is not contained by the polygon
I have an array with the vertices of the polygon, and an array with the lines, like this:
polygon = [
{x: ..., y: ...},
...
]
lines = [
{
p1: {x: ..., y: ...},
p2: {x: ..., y: ...}
},
...
]
The lines array contains only valid lines.
How can I get the polygons that are sliced by the lines.
I want something like this:
function getSlicedPolygons(polygon, lines){
// No check for valid lines, they are already valid
// Do the algorithm...
}
What I've tried so far
I start on the first vertex and go next until I reach a connected vertex. From that vertex, I go to the vertex that's connected at the other ending of the line. Now I go next until another vertex that's connected and so on until I reached the vertex where I started. Now I have the first polygon. I couldn't find the others...
Code (implementation, not real code):
function getSlicedPolygons(polygon, line){
var results = []
var ofl = 0; // Overflow counter, to prevent infinite looping
while(lines.length > 0){
// Iterate through polygon
var i = 0;
var r = []; // Array of new indices
var iterations = 0; // An overflow counter again
while(i < polygon.length){
r.push[i]
// findNextConnectionIndex(...) searches for a line
// that connects with this vertex and returns the index of
// the other connected vertex
var n = findNextConnectionIndex(i, polygon, lines) || i+1
i=n;
// Don't loop infinite
iterations++;
if(iterations > 10) break;
}
var result = [];
for(var z = 0; z<r.length; z++){
result.push(polygon[r[z]])
}
results.push(result)
// Now I should do something to get another polygon next
// time ...
// Don't loop infinite
ofl++;
if(ofl >= 10) break;
}
return results;
}
It returns the same polygon 10 times in an array...

Treat the polygon and its intersecting lines as an undirected graph with loops and apply a loop-detection algorithm to it. Since we know the connecting lines, things become a bit more simple and we can actually solve the problem in O(V).
This would be a model that suffices to explain the basic principle. We can transform our polygon into a rectangle that is sliced by the list of lines. Since no lines may intersect, this will also apply to the resulting rectangle. Now one can start in an corner of the graph and travel alongside both edges until on both paths a vertex of degree 3 is reached. Thus we've found our first polygon that results from slicing the original polygon. Go on from the two points reached in the previous step until you reach vertices of degree 3 are reached again. Terminate this step when the two paths meet and you've listed all possible polygons.
A diagram of running a single step of this process:
Finding the "corner" vertex
Start from an arbitrary point in the graph/polygon and traverse the vertices along the polygon in an arbitrary direction until a vertex of degree 3 is reached. Store the corresponding slicing line and proceed along the polygon until the vertex of degree 3 is reached. If it is the same slicing line, you've found a "corner" vertex, else store the new slicing line and repeat.
EDIT
A working implementation in python:
def slice_polygon(poly, part):
# find the "corner point"
last_slice = None
last_pt = None
for pt in poly:
s = [x for x in part if pt in x]
if s:
if last_slice in s:
break
last_slice = s[0]
last_pt = pt
# find slicing starting from border-point
a = poly.index(last_pt)
b = (a + 1) % len(poly) # current positions on the polygon
sliced_poly = [] # current polygon
slicing = [] # list of all polygons that are created by the slicing
while a != b:
if not [x for x in part if poly[a] in x]:
# point doesn't lie on slicing-line => add to current polygon
sliced_poly.insert(0, poly[a]) # prepend point
a = (a - 1 + len(poly)) % len(poly) # advance a by one
elif not [x for x in part if poly[b] in x]:
# point doesn't lie on slicing-line => add to current polygon
sliced_poly.append(poly[b]) # append point
b = (b + 1 + len(poly)) % len(poly) # advance by one
else:
# append points of slicing line
sliced_poly.insert(0, poly[a])
sliced_poly.append(poly[b])
# store created polygon and start over
slicing.append(sliced_poly)
sliced_poly = []
# remove partitioning-line at which the algorithm stopped
part.remove([x for x in part if poly[a] in x and poly[b] in x][0])
# add last point to the current polygon, as it's not yet added to it
sliced_poly.append(poly[a])
# add last polygon to result-set
slicing.append(sliced_poly)
return slicing
# test
polygon = [(150, 110), (270, 40), (425, 90), (560, 150), (465, 290), (250, 290), (90, 220)]
partition = [((270, 40), (250, 290)), ((425, 90), (250, 290))]
print(slice_polygon(polygon, partition))
Output:
[[(425, 90), (560, 150), (465, 290), (250, 290)], [(270, 40), (425, 90), (250, 290)], [(90, 220), (150, 110), (270, 40), (250, 290)]]
Input:
Since there is a total of two "corner-points" (at least), we are guaranteed to find at least one, if we traverse the polygon once.

Related

How do I plot an area chart in p5.js?

I am trying to recreate this visualization using p5.js. I have some trouble understanding how to create the coordinates for the new points and plot them on my canvas.
The data is a series of negative-positive values that need to be plotted below and above an X-axis respectively (from left to right). This is a sample:
"character","roll_value"
"Daphne Blake",0
"Daphne Blake",-1
"Daphne Blake",-1
"Daphne Blake",-5
"Daphne Blake",-3
"Daphne Blake",2
So I know that I have to map the values between a certain negative and positive height so I've demarcated those heights as follows:
let maxNegativeHeight = sketch.height - 120;
let maxPositiveHeight = sketch.height/4;
For mapping the input I thought of creating a new function called mapToGraph which takes in the roll_value, the old X position, max height and min height. This would map the old values to a new incremented X position and a vertical height:
const mapToGraph = (value, oldXPos, maxHeight, minHeight) => {
const newXPos = oldXPos + 10;
const newYPos = sketch.map(value, 0, maxHeight, minHeight, maxHeight);
return [newXPos, newYPos];
};
In my draw function, I am drawing the points as follows:
sketch.draw = () => {
for(let i = 0; i < data.getRowCount(); i++) {
let character = data.getString(i, "character");
if(character === 'Daphne Blake'){
console.log(character);
// Draw a horizontal line in the middle of the canvas
sketch.stroke('#F18F01');
sketch.line(0, sketch.height/2, sketch.width, sketch.height/2);
// Plot the data points
let value = data.getNum(i, "roll_value");
let [newX, newY] = mapToGraph(value, 0, maxNegativeHeight, maxPositiveHeight);
console.log(newX, newY);
sketch.strokeWeight(0.5);
sketch.point(newX, newY);
}
}
};
However, this does not plot any points. My console.log shows me that I am not processing the numbers correctly, since all of them look like this:
10 -3
cardThree.js:46 Daphne Blake
cardThree.js:55 10 -4
cardThree.js:46 Daphne Blake
cardThree.js:55 10 -4
cardThree.js:46 Daphne Blake
What am I doing wrong? How can I fix this and plot the points like the visualization I linked above?
Here is the full code of what I've tried (live link to editor sketch).
This is the full data
In your code newX is always 10 since you always pass 0 as the second argument to mapToGraph. Additionally the vertical displacement is always very small and often negative. Since you are using newY directly rather than relative to the middle of the screen many of the points are off screen.

Give curved line a deeper arc in turf.js and mapbox

There's no simple curved-line tool in turf.js, nor is there an easy way to do it in mapbox (so far as I can see), so I've created a workaround based on this answer in this thread.
However, the curve it creates isn't very smooth or satisfying or has an inconsistent hump based on angle/length.
Ideally, I'd like an arc that is always in a nice, rounded form.
and drawing a line between them. I then offset the midpoint by distance / 5 and apply a bearing. I then connect up the three points with a turf.bezierSpline.
const start = [parseFloat(originAirport.longitude), parseFloat(originAirport.latitude)];
const end = [
parseFloat(destinationAirport.longitude),
parseFloat(destinationAirport.latitude),
];
const distance = turf.distance(start, end, { units: 'miles' });
const midpoint = turf.midpoint(start, end);
const destination = turf.destination(midpoint, distance / 5, 20, { units: 'miles' });
// curvedLine gets rendered to the page
const curvedLine = turf.bezierSpline(
turf.lineString([start, destination.geometry.coordinates, end]),
);
Desired curvature:
Well, that question was created a very long time ago, but I recently encounter this problem.
If anybody is still wondering - this code is good is general, but you've missed one detail. We can't use hardcoded bearing value 20 in turf.destination method, because it's incorrect for most cases. We need our moved midpoint to be right at the middle of our geometry, so we have to find the right angle.
const bearing = turf.bearing(start, end);
Then - if we want our arc to be on the left side of our line, we need to add 90 degrees to our calculated bearing. If on the right side - substract 90 degrees, so:
const leftSideArc = bearing + 90 > 180 ? -180 + (bearing + 90 - 180) : bearing + 90;
NOTE!!! Bearing is value between -180 and 180 degrees. Our value have to be calculated properly in case it'll exceed this range.
And then we can pass our bearing to destination method:
const destination = turf.destination(midpoint, distance / 5, leftSideArc, { units: 'miles' });
Now we have a perfect arc.

In PaperJS rotating a shape around point is not working properly

I am trying to recreate the game Asteroids. This is a sample of the code for the Ship object constructor (I am using a constructor function and not an object literal because this doesn't work properly when referring to variables in a literal):
function Ship(pos) {
var position = pos ? pos : view.center;
var segments = [
new Point(position) + new Point(0, -7.5), // Front of ship
new Point(position) + new Point(-5, 7.5), // Back left
new Point(position) + new Point(0, 3.5), // Rear exhaust indentation
new Point(position) + new Point(5, 7.5) // Back right
]
this.shipPath = new Path.Line({
segments: segments,
closed: true,
strokeColor: '#eee',
strokeWidth: 2
});
this.velocity = new Point(0, -1);
this.steering = new Point(0, -1);
this.rot = function(ang) {
this.steering.angle += ang;
this.shipPath.rotate(ang, this.shipPath.position);
}
this.drive = function() {
this.shipPath.position += this.velocity;
}
}
var ship = new Ship();
var path = new Path({
strokeColor: '#ddd',
strokeWidth: 1
});
function onFrame(event) {
path.add(ship.shipPath.position);
ship.drive();
}
I've left out the key handlers which is how the ship is steered, but basically what they do is call the this.rot() function with different angles depending whether the right or left buttons were clicked.
Basically my problem is that according to this, when steering the ship, the ship should rotate around its shipPath.position, which would leave that point travelling in a straight line as the ship revolves around it. Instead this is happening:
The curly bit in the path is from when I continuously steered the ship for a few seconds. Why is this happening? If the ship is revolving around its position, why should the position judder sideways as the ship rotates?
Here is a link to where I've got this working on my own website: http://aronadler.com/asteroid/
I would have loved to put this on jsbin or codepen but despite hours work I have never been able to actually get the paperscript working in javascript.
Here is a sketch. Because for some reason Sketch won't let arrow keys being detected I've given it an automatic constant rotation. The effect is the same.
The reason for this is that path.bounds.center is not the center of the triangle. The default center for rotation is path.bounds.center. See sketch. The red dots are bounds.center, the green rectangles are the bounds rectangle.
You want to rotate around the triangle center (technically centroid) which can be calculated by finding the point 2/3 of the way from a vertex to the midpoint of the opposite side.
Here's some code to calculate the centroid of your triangle:
function centroid(triangle) {
var segments = triangle.segments;
var vertex = segments[0].point;
var opposite = segments[1].point - (segments[1].point - segments[2].point) / 2;
var c = vertex + (opposite - vertex) * 2/3;
return c;
}
And an updated sketch showing how the center doesn't move, relative to your triangle, as it is rotated, when calculating the centroid.
And I've updated your sketch to use the centroid rather than position. It now moves in a straight line.

SVG find rotation angle of a path

I've a problem with my SVG map.
I use jVectorMap to create a custom map and I need to write the name of every field in the center of the field.
The example is: JSFiddle Example (zoom in the right side to see the text)
I can find the center of every field with this function:
jvm.Map.prototype.getRegionCentroid = function(region){
if(typeof region == "string")
region = this.regions[region.toUpperCase()];
var bbox = region.element.shape.getBBox(),
xcoord = (bbox.x + bbox.width/2),
ycoord = (bbox.y + bbox.height/2);
return [xcoord, ycoord];
};
but my problem is that I want to rotate the text for align it with the top line of the relative field.
I've tried with getCTM() function but it give me always the same values for every field.
How can I find the right rotation angle of every field?
Thank you to all!
Looks like squeamish ossifrage has beaten me to this one, and what they've said would be exactly my approach too...
Solution
Essentially find the longest line segment in each region's path and then orient your text to align with that line segment whilst trying to ensure that the text doesn't end up upside-down(!)
Example
Here's a sample jsfiddle
In the $(document).ready() function of the fiddle I'm adding labels to all the regions but you will note that some of the regions have centroids that aren't within the area or non-straight edges that cause problems - Modifying your map slightly might be the easiest fix.
Explanation
Here are the 3 functions I've written to demonstrate the principles:
addOrientatedLabel(regionName) - adds a label to the named region of the map.
getAngleInDegreesFromRegion(regionName) - gets the angle of the longest edge of the region
getLengthSquared(startPt,endPt) - gets length squared of line seg (more efficient than getting length).
addOrientatedLabel() places the label at the centroid using a translate transform and rotates the text to the same angle as the longest line segment in the region. In SVG transforms are resolved right to left so:
transform="translate(x,y) rotate(45)"
is interpreted as rotate first, then translate. This ordering is important!
It also uses text-anchor="middle" and dominant-baseline="middle" as explained by squeamish ossifrage. Failing to do this will cause the text to be misaligned within its region.
getAngleInDegreesFromRegion() is where all the work is done. It gets the SVG path of the region with a selector, then loops through every point in the path. Whenever a point is found that is part of a line segment (rather than a Move-To or other instruction) it calculates the squared length of the line segment. If the squared length of the line segment is the longest so far it stores its details. I use squared length because that saves performing a square root operation (its only used for comparison purposes, so squared length is fine).
Note that I initialise the longestLine data to a horizontal one so that if the region has no line segments at all you'll at least get horizontal text.
Once we have the longest line, I calculate its angle relative to the x axis with Math.atan2, and convert it from radians to degrees for SVG with (angle / Math.PI) * 180. The final trick is to identify if the angle will rotate the text upside down, and if so, to rotate another 180 degrees.
Note
I've not used SVG before so my SVG code might not be optimal, but it's tested and it works on all regions that consist mostly of straight line segments - You will need to add error checking for a production application of course!
Code
function addOrientatedLabel(regionName) {
var angleInDegrees = getAngleInDegreesFromRegion(regionName);
var map = $('#world-map').vectorMap('get', 'mapObject');
var coords = map.getRegionCentroid(regionName);
var svg = document.getElementsByTagName('g')[0]; //Get svg element
var newText = document.createElementNS("http://www.w3.org/2000/svg","text");
newText.setAttribute("font-size","4");
newText.setAttribute("text-anchor","middle");
newText.setAttribute("dominant-baseline","middle");
newText.setAttribute('font-family', 'MyriadPro-It');
newText.setAttribute('transform', 'translate(' + coords[0] + ',' + coords[1] + ') rotate(' + angleInDegrees + ')');
var textNode = document.createTextNode(regionName);
newText.appendChild(textNode);
svg.appendChild(newText);
}
Here's my method to find the longest line segment in a given map region path:
function getAngleInDegreesFromRegion(regionName) {
var svgPath = document.getElementById(regionName);
/* longest edge will default to a horizontal line */
/* (in case the shape is degenerate): */
var longestLine = { startPt: {x:0, y:0}, endPt: {x:100,y:0}, lengthSquared : 0 };
/* loop through all the points looking for the longest line segment: */
for (var i = 0 ; i < svgPath.pathSegList.numberOfItems-1; i++) {
var pt0 = svgPath.pathSegList.getItem(i);
var pt1 = svgPath.pathSegList.getItem(i+1);
if (pt1.pathSegType == SVGPathSeg.PATHSEG_LINETO_ABS) {
var lengthSquared = getLengthSquared(pt0, pt1);
if( lengthSquared > longestLine.lengthSquared ) {
longestLine = { startPt:pt0, endPt:pt1, lengthSquared:lengthSquared};
}
}/* end if dealing with line segment */
}/* end loop through all pts in svg path */
/* determine angle of longest line segement relative to x axis */
var dY = longestLine.startPt.y - longestLine.endPt.y;
var dX = longestLine.startPt.x - longestLine.endPt.x;
var angleInDegrees = ( Math.atan2(dY,dX) / Math.PI * 180.0);
/* if text would be upside down, rotate through 180 degrees: */
if( (angleInDegrees > 90 && angleInDegrees < 270) || (angleInDegrees < -90 && angleInDegrees > -270)) {
angleInDegrees += 180;
angleInDegrees %= 360;
}
return angleInDegrees;
}
Note that my getAngleInDegreesFromRegion() method will only consider the longest straight line in a path if it is created with the PATHSEG_LINETO_ABS SVG command... You'll need more functionality to handle regions which don't consist of straight lines. You could approximate by treating curves as straight lines with:
if (pt1.pathSegType != SVGPathSeg.PATHSEG_MOVETO_ABS )
But there will be some corner cases, so modifying your map data might be the easiest approach.
And finally, here's the obligatory squared distance method for completeness:
function getLengthSquared(startPt, endPt ) {
return ((startPt.x - endPt.x) * (startPt.x - endPt.x)) + ((startPt.y - endPt.y) * (startPt.y - endPt.y));
}
Hope that is clear enough to help get you started.
Querying getCTM() won't help. All that gives you is a transformation matrix for the shape's coordinate system (which, as you discovered, is the same for every shape). To get a shape's vertex coordinates, you'll have to examine the contents of region.element.shape.pathSegList.
This can get messy. Although a lot of the shapes are drawn using simple "move-to" and "line-to" commands with absolute coordinates, some use relative coordinates and other types of line. I noticed at least one cubic curve. It might be worth looking for an SVG vertex manipulation library to make life easier.
But in general terms, what you need to do is fetch the list of coordinates for each shape (converting relative coordinates to absolute where necessary), and find the segment with the longest length. Be aware that this may be the segment between the two end points of the line. You can easily find the orientation of this segment from Math.atan2(y_end-y_start,x_end-x_start).
When rotating text, make life easy for yourself by using a <g> element with a transform=translate() attribute to move the coordinate origin to where the text needs to be. Then the text won't shoot off into the distance when you add a transform=rotate() attribute to it. Also, use text-anchor="middle" and dominant-baseline="middle" to centre the text where you want it.
Your code should end up looking something like this:
var svg = document.getElementsByTagName('g')[0]; //Get svg element
var shape_angle = get_orientation_of_longest_segment(svg.pathSegList); //Write this function
var newGroup = document.createElementNS("http://www.w3.org/2000/svg","g");
var newText = document.createElementNS("http://www.w3.org/2000/svg","text");
newGroup.setAttribute("transform", "translate("+coords[0]+","+coords[1]+")");
newText.setAttribute("font-size","4");
newText.setAttribute("text-anchor","middle");
newText.setAttribute("dominant-baseline","middle");
newText.setAttribute("transform","rotate("+shape_angle+")");
newText.setAttribute('font-family', 'MyriadPro-It');
var textNode = document.createTextNode("C1902");
newText.appendChild(textNode);
newGroup.appendChild(newText);
svg.appendChild(newGroup);

Drawing irregular concentric circles using Google Maps

I have a bit of a problem. I am trying to do the following using Javascript & the Google Maps API v2:
I can draw individual circles just fine using formulas found all over the Internet. The problem I am facing is that the circles must:
A. Be concentric, and
B. Must have different radius for each "quadrant", i.e., NE, NW, SE & SW
I've searched almost everywhere I can think of on the Internet, and have come up with no way on how to do this. Clearly someone has done this before, and thus why I'm asking in a forum of programmers. :)
Thanks!
UPDATE: I have drawn out, using the following code, what I think the coordinates for each of the points would be. for the drawing below:
This was obtained using the following JS:
http://gist.github.com/181290
NOTE: This javascript is from (slightly modified) the following site, which may hold more answers in terms of what the algorithm may end up being: http://www.movable-type.co.uk/scripts/latlong.html
UPDATE 2: I was able to get this in Google Maps:
Created using the following code:
var NEQ = [0, 90];
var SEQ = [90, 180];
var SWQ = [180, 270];
var NWQ = [270, 0];
// var centrePoint = new LatLon(25.0, -83.1);
// pointsForWindQuadrant(NEQ, centrePoint, 50);
function pointsForWindQuadrant(quadrantDegrees, centrePoint, radius){
var points = [];
// Points must be pushed into the array in order
points.push(new google.maps.LatLng(centrePoint.lat, centrePoint.lon));
for(i = quadrantDegrees[0]; i <= quadrantDegrees[1]; i++){
var point = centrePoint.destPoint(i, radius * 1.85);
points.push(new google.maps.LatLng(point.lat, point.lon)); // Radius should be in nautical miles from NHC
}
points.push(new google.maps.LatLng(centrePoint.lat, centrePoint.lon));
return points;
}
UPDATE 3: I should probably also point out that this is for a geographic coordinate system (as this whole thing is for tropical cyclone wind radii), not the Cartesian coordinate system. Thanks!
Basically, calculate the circle as the x,y = (cos(a), sin(a)), and then multiple this (both terms) by a radius that's the appropriate function of the angle. I don't know Javascript well, or Google maps, so I'll do this in Python, hopefully it's clear enough from this.
from pylab import *
def Rscale(a):
if a>3*pi/2: # lower right, and then work CW around the circle
return 1.
elif a>pi: # lower left
return .9
elif a>pi/2: # upper left
return .8
else: # upper right
return 1.
def step_circle(R):
return array([(R*Rscale(a))*array([cos(a), sin(a)]) for a in arange(0, 2*pi, .001)])
for R in (.5, .7, .9): # make three concentric circles
c = step_circle(R)
plot(c[:,0], c[:,1])
show()
Which gives
I couldn't really follow your sketch, so I just guessed at the numbers. Also, I made the two rightmost quadrants to be the same since that's what your plot looked like, but that is, of course, optional.
I figured it out. Here is the final code. Maybe it can be refactored a bit?
// Returns points for a wind field for a cyclone. Requires
// a LatLon centre point, and an array of wind radii, starting
// from the northeast quadrant (NEQ), i.e., [200, 200, 150, 175]
//
// Returns points to be used in a GPolyline object.
function pointsForWindQuadrant(centrePoint, radii){
if(radii.length != 4){ return false; }
var points = [];
var angles = [0, 90, 180, 270];
// For each angle 0, 90, 180, 270...
for(a = 0; a < angles.length; a++){
// For each individual angle within the range, create a point...
for(i = angles[a]; i <= angles[a] + 90; i++){
var point = centrePoint.destPoint(i, radii[a] * 1.85); // Radius should be in nautical miles from NHC
points.push(new google.maps.LatLng(point.lat, point.lon));
}
}
// Add the first point again, to be able to close the GPolyline
var point = centrePoint.destPoint(0, radii[0] * 1.85);
points.push(new google.maps.LatLng(point.lat, point.lon));
return points;
}
This results in the following:

Categories