Find the largest rectangle that fits inside a polygon - javascript

I need to find the largest rectangle that can fit inside any polygon,
what i tried is dividing the svg to 2d grid and loop the 2d array to see if the current grid cell intersects with the polygon to create a new 2d binary array where intersection is 1 else 0
now i need to find the largest rectangle from that 2d array AND more importantly its location
as example:
if the 2d array is like this, i need to find the largest rect in that array and its x1,y1 (start i,j) and x2,y2 (end i,j).

well you can brute force the location and scan for the size which will be O(n^6) if n is the avg size of side of your map in pixels ...
The location might be speed up by search (accepting not strictly sorted data) for example like this:
How approximation search works
which would lead to ~O(n^4.log^2(n)). But beware the search must be configured properly in order to not skip solution ... The size search can be improved too by using similar technique like I did in here:
2D OBB
Just use different metric so I would create LUT tables of start and end positions for each x and y (4 LUT tables) which will speed up the search leading to ~O(n^2.log^2(n)) while creation of LUT is O(n^2). btw the same LUTs I sometimes use in OCR like here (last 2 images):
OCR and character similarity
Now problem with this approach is it can not handle concave polygon correctly as there might be more edges per x,y than just 2. So to remedy that you would need to have more LUTs and use them based on position in polygon (divide polygon to "convex" areas)
So putting all these together would look something like this:
approx loop (center x) // ~O(log(n))
approx loop (center y) // ~O(log(n))
grow loop (square size to max using) LUT // O(n)
{
grow loop (x size to max while decreasing original square y size) // O(n)
grow loop (y size to max while decreasing original square x size) // O(n)
use bigger from the above 2 rectangles
}
Just do not forget to use area of polygon / area of rectangle as approximation error value. This algo is resulting in ~O(n^2.log^2(n)) which is not great but still doable.
Another option is convert your polygon to squares, and use bin-packing and or graph and or backtracking techniques to grow to biggest rectangle ... but those are not my cup of tea so I am not confident enough to create answer about them.

Related

How can I discard 10*10 pixels from WebGL alternately

I have drawn a square using webgl. I want to make the square checkered board. So What I need to do is I need to discard some 10*10 pixels alternately from the square. How can I use
gl_FragCoord.x and gl_FragCoord.x
To achieve this? Or is there any easy idea?
WARNING: untested.
You could do math on the fragment shader to create the checker board pattern. First do integer division of x and y by 10 and you get the tile coordinates, lets call it i and j. Then add i and j together. If the result of that is odd, discard the fragments, else if even, keep the fragments.

Calculating volume of area within SVG element

Given an SVG such as this fish bowl, I'm trying to calculate the volume of the area defined in pink as a percentage of the area between the "fill level" and "empty level".
I can't do a a simple percentage from top to bottom, as the fish bowl is irregularly shaped, and this will throw off the calculation by at least a few percentage points. I need to do this for many fish bowls of different shapes, so an algorithm is needed to determine the volume of each bowl.
Is there any way I can do this with javascript on an SVG element, and if so, is there any way I can go about figuring this out within element areas as a percentage?
Update: Uploaded sample SVG to jsfiddle
First you need to parse the SVG path to lines. Since they all don't cross
the Y axis, this reduces to finding the area under the curve caused by the fish bowl,
also known as the integral.
Let {x_0, x_1, ..., x_n} be the absolute value of the X coordinates of the line segments.
The function representing the graph of the fishbowl is the piecewise function:
f(x) =
{ (x - x_0)/(x_1 - x_0) if x_0 <= x < x_1
{ (x - x_1)/(x_2 - x_1) if x_1 <= x < x_2
{ ...
{ (x - x_(n-1))/(x_n - x_(n-1)) if x_(n-1) <= x < x_(n)
Then the volume of the fishbowl equals the integral of πf(x)2 (the solid of revolution formed by that function).
Let e be the empty level, v the fill level, and w the water level.
Then the ratio of the filled portion of the fishbowl is:
(∫ew πf(x)2 dx) / (∫ev πf(x)2 dx)
If instead your fishbowl is generated by the graph of a function, use that function as f(x) and then calculate the integral given above.
An integral can be approximated using numerical integration techniques such as Simpson's rule or
a Newton-Cotes method.
A I needed a solution to this that isn't prohibitive in terms of computational cost and I wasn't in the mood to write optimized code, I ended up rendering it against transparent background, converted to raster and then counted pixels. I'm sure someone with experience in graphics and geometry can come up with cleaner solutions, but I my optimized code in a high level language is unlikely to run faster than that of someone that's dedicated their lives to this and write in assembly.
Depending on the complexity of the geometry of your fish bowl you might need to up the rendering resolution of course.
[2021 addition]
This SO answer calculates the area of one <path> using the brute-force method described above: Scaling the filling portion of an SVG path

How to do javascript online k-means clustering for many dimensions

I found many examples of javascript online k-means clustering, but all of the are for 2 dimensions.
If I have 56 dimensions (for example), how can I do the clustering?
Bonus question:
Could it be possible, having some new data, to predict some value looking the clusters (like, 76% of belonging to cluster x, so the value should be y)
k-means algorithm should be easy to port to any number of dimensions. It looks like this:
Randomly choose centers of clusters.
For each point check, what is the nearest cluster.
Compute new cluster center by computing avarage from all points.
Repeat until cluster centers don't change.
In 2d, you check the distance between (x1, x2) and (y1, y2) in 2. like this (x1-x2)^2 + (y1-y2)^2 (you don't need to use square root, if you are using distance only to compare it with another distance). In 56 dimensions, you just have 56 components.
In 2d, you compute cluster center by taking avarage of all points. Take the first dimension of all points and take the average avg1, take all the second dimensions avg2 up to 56 and your new cluster center will be (avg1, avg2, avg3 ... avg56).
What is not easy is that it is very expensive. Check out algorithms for dimensionality reduction (feature extraction) like PCA.
Also make sure, that all freatures are normalized. For example - they have ranges between (-100, 100).
If you need more information, check out Machine Learning course at coursera.
Week 8 is all about clustering and its traps.

Determine if a 2D point is within a quadrilateral

I'm working on a JS program which I need to have determine if points are within four corners in a coordinate system.
Could somebody point me in the direction of an answer?
I'm looking at what I think is called a convex quadrilateral. That is, four pretty randomly chosen corner positions with all angles smaller than 180°.
Thanks.
There are two relatively simple approaches. The first approach is to draw a ray from the point to "infinity" (actually, to any point outside the polygon) and count how many sides of the polygon the ray intersects. The point is inside the polygon if and only if the count is odd.
The second approach is to go around the polygon in order and for every pair of vertices vi and vi+1 (wrapping around to the first vertex if necessary), compute the quantity (x - xi) * (yi+1 - yi) - (xi+1 - xi) * (y - yi). If these quantities all have the same sign, the point is inside the polygon. (These quantities are the Z component of the cross product of the vectors (vi+1 - vi) and (p - vi). The condition that they all have the same sign is the same as the condition that p is on the same side (left or right) of every edge.)
Both approaches need to deal with the case that the point is exactly on an edge or on a vertex. You first need to decide whether you want to count such points as being inside the polygon or not. Then you need to adjust the tests accordingly. Be aware that slight numerical rounding errors can give a false answer either way. It's just something you'll have to live with.
Since you have a convex quadrilateral, there's another approach. Pick any three vertices and compute the barycentric coordinates of the point and of the fourth vertex with respect to the triangle formed by the three chosen vertices. If the barycentric coordinates of the point are all positive and all less than the barycentric coordinates of the fourth vertex, then the point is inside the quadrilateral.
P.S. Just found a nice page here that lists quite a number of strategies. Some of them are very interesting.
You need to use winding, or the ray trace method.
With winding, you can determine whether any point is inside any shape built with line segments.
Basically, you take the cross product of each line segment with the point, then add up all the results. That's the way I did it to decide if a star was in a constellation, given a set of constellation lines. I can see that there are other ways..
http://en.wikipedia.org/wiki/Point_in_polygon
There must be some code for this in a few places.
It is MUCH easier to see if a point lies within a triangle.
Any quadrilateral can be divided into two triangles.
If the point is in any of the two triangles that comprise the quadrilateral, then the point is inside the quadrilateral.

Click detection in a 2D isometric grid?

I've been doing web development for years now and I'm slowly getting myself involved with game development and for my current project I've got this isometric map, where I need to use an algorithm to detect which field is being clicked on. This is all in the browser with Javascript by the way.
The map
It looks like this and I've added some numbers to show you the structure of the fields (tiles) and their IDs. All the fields have a center point (array of x,y) which the four corners are based on when drawn.
As you can see it's not a diamond shape, but a zig-zag map and there's no angle (top-down view) which is why I can't find an answer myself considering that all articles and calculations are usually based on a diamond shape with an angle.
The numbers
It's a dynamic map and all sizes and numbers can be changed to generate a new map.
I know it isn't a lot of data, but the map is generated based on the map and field sizes.
- Map Size: x:800 y:400
- Field Size: 80x80 (between corners)
- Center position of all the fields (x,y)
The goal
To come up with an algorithm which tells the client (game) which field the mouse is located in at any given event (click, movement etc).
Disclaimer
I do want to mention that I've already come up with a working solution myself, however I'm 100% certain it could be written in a better way (my solution involves a lot of nested if-statements and loops), and that's why I'm asking here.
Here's an example of my solution where I basically find a square with corners in the nearest 4 known positions and then I get my result based on the smallest square between the 2 nearest fields. Does that make any sense?
Ask if I missed something.
Here's what I came up with,
function posInGrid(x, y, length) {
xFromColCenter = x % length - length / 2;
yFromRowCenter = y % length - length / 2;
col = (x - xFromColCenter) / length;
row = (y - yFromRowCenter) / length;
if (yFromRowCenter < xFromColCenter) {
if (yFromRowCenter < (-xFromColCenter))--row;
else++col;
} else if (yFromRowCenter > xFromColCenter) {
if (yFromRowCenter < (-xFromColCenter))--col;
else++row;
}
return "Col:"+col+", Row:"+row+", xFC:"+xFromColCenter+", yFC:"+yFromRowCenter;
}
X and Y are the coords in the image, and length is the spacing of the grid.
Right now it returns a string, just for testing.. result should be row and col, and those are the coordinates I chose: your tile 1 has coords (1,0) tile 2 is(3,0), tile 10 is (0,1), tile 11 is (2,1). You could convert my coordinates to your numbered tiles in a line or two.
And a JSFiddle for testing http://jsfiddle.net/NHV3y/
Cheers.
EDIT: changed the return statement, had some variables I used for debugging left in.
A pixel perfect way of hit detection I've used in the past (in OpenGL, but the concept stands here too) is an off screen rendering of the scene where the different objects are identified with different colors.
This approach requires double the memory and double the rendering but the hit detection of arbitrarily complex scenes is done with a simple color lookup.
Since you want to detect a cell in a grid there are probably more efficient solutions but I wanted to mention this one for it's simplicity and flexibility.
This has been solved before, let me consult my notes...
Here's a couple of good resources:
From Laserbrain Studios, The basics of isometric programming
Useful article in the thread posted here, in Java
Let me know if this helps, and good luck with your game!
This code calculates the position in the grid given the uneven spacing. Should be pretty fast; almost all operations are done mathematically, using just one loop. I'll ponder the other part of the problem later.
def cspot(x,y,length):
l=length
lp=length+1
vlist = [ (l*(k%2))+(lp*((k+1)%2)) for k in range(1,y+1) ]
vlist.append(1)
return x + sum(vlist)

Categories

Resources