Code Monkey home page Code Monkey logo

box-intersect's Introduction

box-intersect

This modules finds all intersection in a set of n boxes in d-dimensions, or between a pair of sets with n and m boxes respectively. The time taken is O((n+m) log^d(n+m)) and the algorithm uses a temporary scratch memory of size O(n+m). This memory is pooled so that after the first execution no additional memory is allocated. Some possible applications of this library include:

  • Collision detection
  • Polygon clipping
  • Batched box stabbing queries
  • Mesh boolean operations (CSG)

The algorithm in this package is based on the one described in the following paper:

A detailed experimental analysis of the performance of this module as well as comparisons with other libraries for box intersection can be found in the following repository:

For more information on this problem, please see the following series of blog posts:

Example

Detecting overlaps in a set of boxes

Here is how to detect all pairs of overlapping boxes in a single set of boxes:

var boxIntersect = require('box-intersect')

//Boxes are listed as flattened 2*d length arrays
var boxes = [
  [1, 1, 2, 2],   //Interpretation: [minX, minY, maxX, maxY]
  [0, -1, 3, 2],
  [2, 1, 4, 5],
  [0.5, 3, 1, 10]
]

//Default behavior reports list of intersections
console.log('overlaps:', boxIntersect(boxes))

//Note:  Boxes are closed

//Can also use a visitor to report all crossings
var result = boxIntersect(boxes, function(i,j) {
  console.log('overlap:', boxes[i], boxes[j])

  //Can early out by returning any value
  if(i === 2 || j === 2) {
    return 2
  }
})

console.log('early out result:', result)

Output

overlap: [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ] ]
overlap: [ 1, 1, 2, 2 ] [ 0, -1, 3, 2 ]
overlap: [ 1, 1, 2, 2 ] [ 2, 1, 4, 5 ]
early out result: 2

Bipartite intersection

You can also detect all intersections between two different sets of boxes:

var boxIntersect = require('box-intersect')

//Again, boxes are given as flattened lists of coordinates
var red = [
  [0, 0, 0, 8, 1, 1],  //Format: [minX, minY, minZ, maxX, maxY, maxZ]
  [0, 0, 0, 1, 8, 1],
  [0, 0, 0, 1, 1, 8]
]

var blue = [
  [5, 0, 0, 6, 10, 10],
  [0, 5, 0, 10, 6, 10],
  [0, 0, 5, 10, 10, 10]
]

//Report all crossings
console.log('crossings=', boxIntersect(red, blue))

//Again can use a visitor:
boxIntersect(red, blue, function(r, b) {
  console.log('overlap:', red[r], blue[b])
})

Output

crossings= [ [ 0, 0 ], [ 1, 1 ], [ 2, 2 ] ]
overlap: [ 0, 0, 0, 8, 1, 1 ] [ 5, 0, 0, 6, 10, 10 ]
overlap: [ 0, 0, 0, 1, 8, 1 ] [ 0, 5, 0, 10, 6, 10 ]
overlap: [ 0, 0, 0, 1, 1, 8 ] [ 0, 0, 5, 10, 10, 10 ]

Install

Using npm, just run the following command:

npm install box-intersect

This module works in any reasonable CommonJS environment, such as browsersify, iojs or node.js.

API

var boxIntersect = require('box-intersect')

boxIntersect(boxes[, otherBoxes, visit])

Finds all pairs intersections in a set of boxes. There are two basic modes of operation for this function:

  • complete which detects all pairs of intersections within a single set of boxes
  • bipartite which detects pairs of intersections between two different sets of boxes

The parameters to the function are as follows:

  • boxes is a list of boxes. Boxes are represented as length 2*d arrays where the first d-components are the lower bound of the box and then the next d components are the upper bound.
  • otherBoxes is an optional list of boxes which boxes is tested against. If not specified, then the algorithm will report self intersections in boxes
  • visit(i,j) is a callback which is called once for each overlapping pair of boxes. If visit returns any value not equal to undefined, then the search is terminated immediately and this value is returned. If visit is not specified, then a list of intersecting pairs is returned.

Returns If visit was specified, then the last returned value of visit. Otherwise an array of pairs of intersecting boxes.

Note The boxes are treated as cartesian products of closed intervals. For example, the boxes [1,1,2,2] and [0,0,1,1] will be reported as intersecting by this module.

License

(c) 2014 Mikola Lysenko. MIT License

box-intersect's People

Contributors

fenomas avatar mikolalysenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

box-intersect's Issues

Question about polygon clipping

Hi - great library as always. ๐Ÿ‘

One question - in the readme you mention it could be used for polygon clipping. Can you give a hint to how that might work? Or did that refer testing whether polygons overlap a clipping area, as opposed to actually doing the clipping?

(My motivation here is wondering whether box-intersect could be useful in frustum-culling a 3D scene, faster than with octrees.)

Thanks!

Are you using eval?

I got this:

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'nonce-iEsD2if45rrVbpVQzGD2Cw=='".

advice on efficient usage with highly dynamic boxes?

I'd love to use this module for spatial partitioning in a simulation I'm working on.

@mikolalysenko One challenge in my case is many boxes are created/destroyed at simulation time, and the api accepts a fixed list of boxes.

I worry inserting/splicing many array items will create a lot of memory gc pressure.

Would it be better to keep a fixed list of boxes, and just set some to empty? This would effectively be a pool I suppose.

gpu.js

I think your Library is amazing. I also think gpu.js is pretty great too. Your library is already incredibly fast, I'm wondering if there's opportunity to make it even faster with GPU.js

Some thoughts

  • looks like we could send the abbs as 2 variables as 2 dimensional arrays
    • variable a is red boxes and b is blue boxes
    • dimension one is the boxes
    • dimension two is the individual boxes mins and maxes at each dimension
  • the output would be a 1 dimensional array
    • first dimension would be the maximum amount of possible collisions
      • for red vs blue I believe red.length * blue.length
      • for red vs red I believe red.length * (red.length - 1)
    • within that array is a 2 dimensional array featuring box a and box b

A few issues

  • I'm not sure how your handling it now but we want to avoid each red box from coloring with itself
    • so perhaps there's two kernels
    • one for red vs red and one for red vs blue
    • this would also decrease the possible collisions to be (red.length * (red.length - 1)) if my brief calculations are correct
  • I'm not sure it's possible that this cannot be achieved without brute force.
    • I don't know how your handling the the intersections, your code is pretty clean but my mind doesn't fully understand it.
    • but I imagine there are ways to optimize it by sorting the boxes so you can find them so that you don't have to iterate over each.
    • I'm not confident that's possible. There's a setImmutable function but I'm not sure how you able to achieve the Speeds you get. Perhaps your using something like bucket sort to keep track. But with how many possible values a box can have I'm not confident that is still going to achieve the Speeds you did
  • Another issue is that this returns a full list despite not necessarily needing a full list

Some unworking code

V1

const gpu = new GPU();
const kernel = gpu.createKernel(function(red, blue) {
  // We start at red[0]
  // Continue for until we reach blue length - 1
  // We should never reach blue.length unless we go to the next item
  // Then when we reach blue length we should be at red[1]
  // Again until we reach blue.length + blue.length - 1
  // At 2 * bLen we should be at red[2]
  const bLen = this.constants.bLen;
  const rI = Math.floor(this.thread.x/bLen)
  const bI = this.thread.x%bLen
  If(intersects(red[rI], blue[bI])) return [rI, bI]
  return []
  }, { dynamic arguments: true, dynamicOutput: true });

function intersectBoxes(red, blue){
  kernel.setOutput([red.length * blue.length])
  kernal.setConstants({ blen: blue.length })
  // Bad because we reiterate after already iterating
  return kernal(red, blue).filter((boxes)=>(boxes.length))
}

Here's version 2 with maybe less filtering but still concacting and I'm not confident we want to iterate when we are using the GPU. Maybe they are doing some interesting compilation on the other side. In addition I don't know if it's possible to create arrays while in the gpu

const gpu = new GPU();
const kernel = gpu.createKernel(function(red, blue) {
  const intersections = []
  const bLen = this.constants.bLen;
  const rItem = red[this thread.x];
  for(var i = 0; I < bLen; I++){
    If(intersects(red[this.thread.x], blue[i])){
      intersections[intersections length] = [this thread.x, I]
    }
  }
  return intersections
  }, { dynamic arguments: true, dynamicOutput: true });

function intersectBoxes(red, blue){
  kernel.setOutput([red.length])
  kernal.setConstants({ blen: blue.length })
  // Bad because we reiterate after already iterating
  return kernal(red, blue).reduce((a,b)=>(a.concat(b)),[])
}

V3 that tries to do 2 dimensional but ends up just being the same as version 1 so I'm not confident it's much better

const gpu = new GPU();
const kernel = gpu.createKernel(function(red, blue) {
  const rBox = red[this thread.x];
  const bBox = blue[this.thread.y]
  if(intersects(rBox, bBox)) return [this.thread.x, this thread.y]
  return []
  }, { dynamic arguments: true, dynamicOutput: true });

function intersectBoxes(red, blue){
  kernel.setOutput([red.length, blue length])
  kernal.setConstants({ blen: blue.length })
  // Bad because we reiterate after already iterating
  return kernal(red, blue)
  .reduce((a,b)=>(a.concat(b)),[])
  .filter((boxes)=>(boxes.length))
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.