Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const polys = [];
- body.fixture.forEach(fix => {
- if (fix.polygon) {
- polys.push(fix.vertices);
- }
- });
- // Attempt to merge polys
- // --------------------------------
- // Take first poly, try to merge it with every other remaining poly.
- // On success or if all fail, move to second one and repeat
- // Merged polys are added to the end of the stack
- // Once all polys are checked, all remaining ones cannot be merged and are the final polys
- for (let checkIdx = 0;checkIdx < polys.length;checkIdx++) {
- if (!polys[checkIdx]) continue;
- const poly1 = turf.polygon([[
- ...polys[checkIdx].map(v => [v.x, v.y]),
- [polys[checkIdx][0].x, polys[checkIdx][0].y],
- ]]);
- for (let innerCheckIdx = 0;innerCheckIdx < polys.length;innerCheckIdx++) {
- if (!polys[innerCheckIdx]) continue;
- if (innerCheckIdx === checkIdx) {continue};
- const poly2 = turf.polygon([[
- ...polys[innerCheckIdx].map(v => [v.x, v.y]),
- [polys[innerCheckIdx][0].x, polys[innerCheckIdx][0].y],
- ]]);
- try {
- const union = turf.union(poly1, poly2);
- if (union.geometry.type !== 'MultiPolygon') {
- // Merge was a success!
- polys.push(union.geometry.coordinates[0].map(v => ({ x: v[0], y: v[1] })));
- polys[checkIdx] = undefined;
- polys[innerCheckIdx] = undefined;
- break;
- }
- } catch(e) {}
- }
- }
- const finalPolys = polys.filter(p => typeof p !== 'undefined');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement