Guest User

Joyrider: Polygon union

a guest
Nov 1st, 2021
66
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const polys = [];
  2. body.fixture.forEach(fix => {
  3.     if (fix.polygon) {
  4.         polys.push(fix.vertices);
  5.     }
  6. });
  7.  
  8. // Attempt to merge polys
  9. // --------------------------------
  10. // Take first poly, try to merge it with every other remaining poly.
  11. // On success or if all fail, move to second one and repeat
  12. // Merged polys are added to the end of the stack
  13. // Once all polys are checked, all remaining ones cannot be merged and are the final polys
  14.  
  15. for (let checkIdx = 0;checkIdx < polys.length;checkIdx++) {
  16.     if (!polys[checkIdx]) continue;
  17.  
  18.     const poly1 = turf.polygon([[
  19.         ...polys[checkIdx].map(v => [v.x, v.y]),
  20.         [polys[checkIdx][0].x, polys[checkIdx][0].y],
  21.     ]]);
  22.  
  23.     for (let innerCheckIdx = 0;innerCheckIdx < polys.length;innerCheckIdx++) {
  24.         if (!polys[innerCheckIdx]) continue;
  25.         if (innerCheckIdx === checkIdx) {continue};
  26.  
  27.         const poly2 = turf.polygon([[
  28.             ...polys[innerCheckIdx].map(v => [v.x, v.y]),
  29.             [polys[innerCheckIdx][0].x, polys[innerCheckIdx][0].y],
  30.         ]]);
  31.  
  32.         try {
  33.             const union = turf.union(poly1, poly2);
  34.  
  35.             if (union.geometry.type !== 'MultiPolygon') {
  36.                 // Merge was a success!
  37.                 polys.push(union.geometry.coordinates[0].map(v => ({ x: v[0], y: v[1] })));
  38.                 polys[checkIdx] = undefined;
  39.                 polys[innerCheckIdx] = undefined;
  40.                 break;
  41.             }
  42.         } catch(e) {}
  43.     }
  44. }
  45.  
  46. const finalPolys = polys.filter(p => typeof p !== 'undefined');
RAW Paste Data