spatial index for lines - javascript

I have lots of line segments (that represent various surfaces such as walls, ceilings and floors). I want to efficiently determine which lines are within the player's bounding box.
(Right now I'm cycling through all lines, and whilst correct, it is proving much too slow).
There are several kd-tree and other spatial indices in Javascript but they all store points rather than lines.
I actually only need to query by the x axis; it would suffice with a 1D range tree of some sort.
How can you efficiently store and retrieve shapes such as lines?
Once built, the index would not be added to.

In just 2 dimensions, where you have good control over the total spatial extend (i.e. know min and max, and these won't increase), grid based approaches such as plain grids or quadtrees work incredibly well. In particular, if you know your query radius (the players box size), a grid of exactly this size should work really well.
Many games also used what is called a BSP tree, a binary space partitioning tree. But for good performance, this tree is AFAIK usually precomputed when the level is built, and then just loaded with the map.

Related

visualising changes in a distribution over time

I have a distribution of numbers given as a list of numbers, with duplicates allowed, such as [0, 0.1, 0.1, 0.1, 0.2, 0.5].
This distribution changes over time. Each distribution may have a different number of elements, but should usually be similarly sized
I am trying to visualise this change of distributions in Javascript, but can't find a satisfactory solution. I am using plotly for other visualisations already, so a solution in plotly would be preferred, but is not required.
My current approach is to make a scatterplot with heatmap, and enter data points by giving each new distriubtion a new sequentially generated x coordinate, while treating the entries of the distribution as y coordinates. This works reasonably well when the sequentially generated number is small compared to the number in the distribution, but looks odd otherwise, because I don't know how to tell the scatterplot that the x coordinate is artificial and there can never be a data point between two subsequent x coordinates.
For extra credit, find a way to visualise it nicely even if the distributions can be based on a vastly different number of elements.
I couldn't find a standard solution in Javascript, but I found a way around:
I show a graph with 11 lines. Each line is a 10% quantile of the distribution I am tracking. It's a bit unintuitive at first, but very informative once you are used to it.

Enclose multiple separate sets of points using polygons which stack next to each other

I am working on a data set of coordinate points(many dots in area) either (x,y) or (lat,lon) which fall into multiple categories. What I am trying to do is get polygons of areas from those points which are called concave or non-convex as far as I know, but also those polygons have to be next to each other with no gaps between them.
These are the initial points(example)
This is the approximate result I am aiming for
Real life example would be European geopolitical map, if you had all of the addresses of all countries and wanted to get area of each country as a polygon and end up with a map.
I have come across many questions related to getting polygons from set of points, but were unable to use it in my scenario. If you need any more information please let me know. Thank you for your help.
You could use a Voronoi tesselation of the input space. Instead of having point you have sets of points though. Basically, you take each point in space, and look at the closest point to it. It then gets the same "class" as that point. For smoother outputs you could look at a k majority out of N nearest points. It would mean working with a bitmap image rather than 2D coordinates, but you'd get something workable. You could then use simpler image manipulation tricks (edge detection, binary set operations etc to get just the edges, and then perhaps superimpose those on the image).
As an alternative, you could run a convex hull algorithm on each data set, and then try to fix the overlap areas.

How to detect collision in not easily polygon divided body

Say we are coding something in Javascript and we have a body, say an apple, and want to detect collision of a rock being thrown at it: it's easy because we can simply consider the apple as a circle.
But how about we have, for example, a "very complex" fractal? Then there is no polygon similar to it and we also cannot break it into smaller polygons without a herculean amount of effort. Is there any way to detect perfect collision in this case, as opposed to making something that "kind" of works, like considering the fractal a polygon (not perfect because there will be collision detected even in blank spaces)?
You can use a physics editor
https://www.codeandweb.com/physicseditor
It'll work with most game engines. You'll have to figure how to make it work in JS.
Here's an tutorial from the site using typescript - related to JS
http://www.gamefromscratch.com/post/2014/11/27/Adventures-in-Phaser-with-TypeScript-Physics-using-P2-Physics-Engine.aspx
If you have coordinates of the polygons, you can make an intersection of subject and clip polygons using Javascript Clipper
The question doesn't provide too much information of the collision objects, but usually anything can be represented as polygon(s) to certain precision.
EDIT:
It should be fast enough for real time rendering (depending of complexity of polygons). If the polygons are complex (many self intersections and/or many points), there are many methods to speedup the intersection detection:
reduce the point count using ClipperLib.JS.Lighten(). It removes the points that have no effect to the outline (eg. duplicate points and points on edge)
get first bounding rectangles of polygons using ClipperLib.JS.BoundsOfPath() or ClipperLib.JS.BoundsOfPaths(). If bounding rectangles are not in collision, there is no need to make intersection operation. This function is very fast, because it just gets min/max of x and y.
If the polygons are static (ie their geometry/pointdata doesn't change during animation), you can lighten and get bounds of paths and add polygons to Clipper before animation starts. Then during each frame, you have to do only minimal effort to get the actual intersections.
EDIT2:
If you are worried about the framerate, you could consider using an experimental floating point (double) Clipper, which is 4.15x faster than IntPoint version and when big integers are needed in IntPoint version, the float version is 8.37x faster than IntPoint version. The final speed is actually a bit higher because IntPoint Clipper needs that coordinates are first scaled up (to integers) and then scaled down (to floats) and this scaling time is not taken into account in the above measurements. However float version is not fully tested and should be used with care in production environments.
The code of experimental float version: http://jsclipper.sourceforge.net/6.1.3.4b_fpoint/clipper_unminified_6.1.3.4b_fpoint.js
Demo: http://jsclipper.sourceforge.net/6.1.3.4b_fpoint/main_demo3.html
Playground: http://jsbin.com/sisefo/1/edit?html,javascript,output
EDIT3:
If you don't have polygon point coordinates of your objects and the objects are bitmaps (eg. png/canvas), you have to first trace the bitmaps eg. using Marching Squares algorithm. One implementation is at
https://github.com/sakri/MarchingSquaresJS.
There you get an array of outline points, but because the array consists of huge amount of unneeded points (eg. straight lines can easily be represented as start and end point), you can reduce the point count using eg. ClipperLib.JS.Lighten() or http://mourner.github.io/simplify-js/.
After these steps you have very light polygonal representations of your bitmap objects, which are fast to run through intersection algorithm.
You can create bitmaps that indicate the area occupied by your objects in pixels. If there is intersection between the bitmaps, then there is a collision.

build complete graph with n vertices using javascript

I need to implement an algorithm which involves building a complete graph using JavaScript functions as first step.
Are there any fast ways (like libraries or build-in functions I can use? Or may I get some suggestions on how to set up the data-structures efficiently and easily using JavaScript?
Further more, given n vertices, after building a complete graph,
for each iteration:
Try vertex-cover like thing,(if there'are odd number of vertices, just leave the last one alone) and then store the pairs of vertices for each edge in the vertex cover, and then remove the edges involved in that vertex cover, and then sort the vertices by orders that has biggest number of edges remaining to be removed
and then looping doing so, until no edges been left in the graph.
Thank you very much.

How to generate a treemap using only squares

I am currently experimenting with the gallery treemap of d3.js.
http://bl.ocks.org/4063582
Now I am wondering if I can make the treemap render all items in squares. I can only get it to render rectangles. I tried to use .mode("squarify"); but that doesn't result in the required layout. It doesn't matter that it won't use all the available space. I just want it to render squares.
Squarified Treemaps: http://www.win.tue.nl/~vanwijk/stm.pdf. It looks like a thorough look at the problem and includes solution pseudocode.
Abstract. An extension to the treemap method for the visualization of hierarchical information, such as directory structures and
organization structures, is presented. The standard treemap method
often gives thin, elongated rectangles. As a result, rectangles are
difficult to compare and to select. A new method is presented to
generate lay-outs in which the rectangles approximate squares. To
strenghten the visualization of the structure, shaded frames are used
around groups of related nodes
Additional Resources
Alternatively, you could create your own output based on the data as suggested here: How to use jQuery to render a JSON tree as nested HTML using divs?
Some improvements on the squarified algorithm: http://incise.org/d3-binary-tree-treemap.html
Treemaps for space-constrained visualization of hierarchies shows a history of various treemap algorithms most with the goal of reducing the rectangle ratio to 1. You might find some of the papers helpful.
This page also provides a nice break down of the various treemap algorithms.
Depending on the data, the rectangles can have very different aspect
ratios, making them hard to compare: a thin long rectangle of the same
area as an almost square one looks very different. Bruls, Huizing, and
van Wijk therefore developed Squarified Treemaps, which optimize the
placement of nodes within a level to make them as square as possible.
While that is a great idea to make static treemaps more readable, it
causes problems when treemaps are used to show developments over time.
Ordered Treemap Layouts, developed by Shneiderman and Wattenberg,
solve this problem by conserving the ordering of elements while
seeking to keep nodes as square as possible, and thus produce very
stable layouts.
Conclusion
The brief read at the wikipedia entry provides a good explanation on why a strictly square treemap remains difficult to achieve. Emphasis added.
To create a treemap, one must define a tiling algorithm, that is, a
way to divide a rectangle into sub-rectangles of specified areas.
Ideally, a treemap algorithm would create rectangles of aspect ratio
close to one, furthermore preserve some sense of the ordering in the
input data, and change to reflect changes in the underlying data.
Unfortunately, these properties have an inverse relationship. As the
aspect ratio is optimized, the order of placement becomes less
predictable. As the order becomes more stable, the aspect ratio is
degraded.
After researching this topic further, I agree with Lars Kotthoff that obtaining a treemap strictly with squares does not appear trivial. At least not based on existing implemented treemap algorithms. The easiest way around this might be to create your own code (JS and CSS) to generate nested divs or lis to achieve the desired final treemap look.
Addendum
http://www.koalastothemax.com/ - this demo renders nested circles but it's obvious they all sit within squares. It might take some work but you probably could achieve the desired results using the Koalas to the Max code.
Unfortunately it is not possible to have the treemap render all items in squares, for mathematical reasons.
Here i just give you a counter-example.
Suppose that, at the end of your processing, you end up with 4 categories (A, B, C, D) with the folowing surface area.
A=2
B=2
C=2
D=1
Independently of the position you give to them, it is impossible to have the final treemap with a square or even rectangle shape.
Think: in each of the following patterns you always have a missing corner
AB AC AD BA BC BD CA CB CD DA DB DC
CD BD BC CD AD AC BD AD AB CB AC AB ..there are more
because one of the square has surface area = 1.
So this is not possible to have all squares
From that paper , as mentioned by JSuar we learn that there is an optimized almost-squared representation you can have, implementing the algorithm described in the paper.
But this is an approximation.
I think that all you can do, if you really need ONLY squares, is:
change visualization, using for instance http://bl.ocks.org/4063530
hack the treemap.js code modifying line 12 as follows
ratio = 1;
But in this latter case you could have some empty white spaces or other malfunctioning.

Categories