Skip to content

feat: add find line segment Intersection algorithm #1705

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions Geometry/PlaneSweep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* This class implements a Line Segment Intersection algorithm using the Plane Sweep technique.
* It detects intersections between a set of line segments in a 2D plane.
* @see {@link https://en.wikipedia.org/wiki/Sweep_line_algorithm}
* @class
*/
export default class PlaneSweep {
/** @private */
#segments

/** @private */
#events

/** @private */
#activeSet

/**
* Creates a Line Segment Intersection instance.
* @constructor
* @param {Array<{start: {x: number, y: number}, end: {x: number, y: number}}> } segments - An array of line segments defined by start and end points.
* @throws {Error} Will throw an error if the segments array is empty or invalid.
*/
constructor(segments) {
this.#validateSegments(segments)

this.#segments = segments
this.#events = []
this.#activeSet = new Set()
this.#initializeEvents()
}

/**
* Validates that the input is a non-empty array of segments.
* @private
* @param {Array} segments - The array of line segments to validate.
* @throws {Error} Will throw an error if the input is not a valid array of segments.
*/
#validateSegments(segments) {
if (
!Array.isArray(segments) ||
segments.length === 0 ||
!segments.every((seg) => seg.start && seg.end)
) {
throw new Error(
'segments must be a non-empty array of objects with start and end properties.'
)
}
}

/**
* Initializes the event points for the sweep line algorithm.
* @private
*/
#initializeEvents() {
for (const segment of this.#segments) {
const startEvent = { point: segment.start, type: 'start', segment }
const endEvent = { point: segment.end, type: 'end', segment }

// Ensure start is always before end in terms of x-coordinates
if (
startEvent.point.x > endEvent.point.x ||
(startEvent.point.x === endEvent.point.x &&
startEvent.point.y > endEvent.point.y)
) {
this.#events.push(endEvent)
this.#events.push(startEvent)
} else {
this.#events.push(startEvent)
this.#events.push(endEvent)
}
}

// Sort events by x-coordinate, then by type (start before end)
this.#events.sort((a, b) => {
if (a.point.x === b.point.x) {
return a.type === 'start' ? -1 : 1
}
return a.point.x - b.point.x
})
}

#doSegmentsIntersect(seg1, seg2) {
const ccw = (A, B, C) => {
const val = (C.y - A.y) * (B.x - A.x) - (B.y - A.y) * (C.x - A.x)
if (Math.abs(val) < Number.EPSILON) return 0 // Collinear
return val > 0 ? 1 : -1 // Clockwise or counterclockwise
}

const onSegment = (p, q, r) => {
return (
q.x <= Math.max(p.x, r.x) &&
q.x >= Math.min(p.x, r.x) &&
q.y <= Math.max(p.y, r.y) &&
q.y >= Math.min(p.y, r.y)
)
}

const o1 = ccw(seg1.start, seg1.end, seg2.start)
const o2 = ccw(seg1.start, seg1.end, seg2.end)
const o3 = ccw(seg2.start, seg2.end, seg1.start)
const o4 = ccw(seg2.start, seg2.end, seg1.end)

// General case of intersection
if (o1 !== o2 && o3 !== o4) return true

// Special cases: collinear segments that may touch
if (o1 === 0 && onSegment(seg1.start, seg2.start, seg1.end)) return true
if (o2 === 0 && onSegment(seg1.start, seg2.end, seg1.end)) return true
if (o3 === 0 && onSegment(seg2.start, seg1.start, seg2.end)) return true
return o4 === 0 && onSegment(seg2.start, seg1.end, seg2.end)
}

/**
* Executes the Plane Sweep algorithm to find all intersections.
* @public
* @returns {Array<{segment1: *, segment2: *}>} An array of intersecting segment pairs.
*/
findIntersections() {
const intersections = []

for (const event of this.#events) {
const { type, segment } = event

if (type === 'start') {
this.#activeSet.add(segment)

// Check for intersections with neighboring active segments
const neighbors = Array.from(this.#activeSet).filter(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is this efficient in general? The active set might very well contain linearly many line segments meaning you get quadratic runtime? The crucial point of this algorithm is that active line segments are managed in a sorted set so you only have to check adjacent line segments in the sorted order.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've implemented Bently-Ottmann algorithm and improved the complexity to O((n+k) logn).

(seg) => seg !== segment
)
for (const neighbor of neighbors) {
if (this.#doSegmentsIntersect(neighbor, segment)) {
intersections.push({ segment1: neighbor, segment2: segment })
}
}
} else if (type === 'end') {
// Remove the segment from the active set
this.#activeSet.delete(segment)
}
}

return intersections
}
}
158 changes: 158 additions & 0 deletions Geometry/Test/PlaneSweep.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import PlaneSweep from '../PlaneSweep'

describe('PlaneSweep', () => {
let planeSweep

describe('constructor', () => {
it('should create an instance with valid segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 1, y: 1 } },
{ start: { x: 1, y: 0 }, end: { x: 0, y: 1 } }
]
expect(() => new PlaneSweep(segments)).not.toThrow()
})

it('should throw an error with empty segments array', () => {
expect(() => new PlaneSweep([])).toThrow(
'segments must be a non-empty array'
)
})

it('should throw an error with invalid segments', () => {
const invalidSegments = [{ start: { x: 0, y: 0 } }]
expect(() => new PlaneSweep(invalidSegments)).toThrow(
'segments must be a non-empty array of objects with start and end properties'
)
})
})

describe('findIntersections', () => {
beforeEach(() => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 2, y: 2 } },
{ start: { x: 0, y: 2 }, end: { x: 2, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
})

it('should find intersections between crossing segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 2, y: 2 } },
{ start: { x: 0, y: 2 }, end: { x: 2, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
expect(intersections[0]).toEqual(
expect.objectContaining({
segment1: expect.objectContaining({
start: expect.objectContaining({ x: 0, y: expect.any(Number) }),
end: expect.objectContaining({ x: 2, y: expect.any(Number) })
}),
segment2: expect.objectContaining({
start: expect.objectContaining({ x: 0, y: expect.any(Number) }),
end: expect.objectContaining({ x: 2, y: expect.any(Number) })
})
})
)
})

it('should not find intersections between non-crossing segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 1, y: 1 } },
{ start: { x: 2, y: 2 }, end: { x: 3, y: 3 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(0)
})

it('should handle vertical and horizontal segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 0, y: 2 } }, // Vertical
{ start: { x: -1, y: 1 }, end: { x: 2, y: 1 } } // Horizontal
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})

it('should handle segments with shared endpoints', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 1, y: 1 } },
{ start: { x: 1, y: 1 }, end: { x: 2, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1) // Shared endpoint is considered an intersection
})

it('should handle overlapping segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 2, y: 2 } },
{ start: { x: 1, y: 1 }, end: { x: 3, y: 3 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})
})

describe('edge cases', () => {
it('should handle segments with reversed start and end points', () => {
const segments = [
{ start: { x: 2, y: 2 }, end: { x: 0, y: 0 } },
{ start: { x: 0, y: 2 }, end: { x: 2, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})

it('should handle segments with same x-coordinate but different y-coordinates', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 0, y: 2 } },
{ start: { x: 0, y: 1 }, end: { x: 0, y: 3 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})

it('should handle a large number of touching segments', () => {
const segments = Array.from({ length: 1000 }, (_, i) => ({
start: { x: i, y: 0 },
end: { x: i + 1, y: 1 }
}))
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
// Check if touching points are considered intersections
const touchingPointsAreIntersections = intersections.length > 0
if (touchingPointsAreIntersections) {
expect(intersections).toHaveLength(999) // Each segment touches its neighbor
} else {
expect(intersections).toHaveLength(0) // Touching points are not considered intersections
}
})

it('should detect touching points as intersections', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 1, y: 1 } },
{ start: { x: 1, y: 1 }, end: { x: 2, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})

it('should handle collinear overlapping segments', () => {
const segments = [
{ start: { x: 0, y: 0 }, end: { x: 2, y: 0 } },
{ start: { x: 1, y: 0 }, end: { x: 3, y: 0 } }
]
planeSweep = new PlaneSweep(segments)
const intersections = planeSweep.findIntersections()
expect(intersections).toHaveLength(1)
})
})
})