Skip to content

Commit

Permalink
Merge pull request #2 from intelygenz/fix/lines_intersect
Browse files Browse the repository at this point in the history
Fix line intersection
  • Loading branch information
igzjaviergil authored Nov 14, 2024
2 parents ffcae26 + 0ce8dd9 commit 6679677
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/engine/game/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (e *Game) connectLighthouses(p *player.Player, action *player.Action) error
}

for _, c := range l.Connections {
if xy.DoLinesOverlap(l.Position, c.Position, curLighthousePos, destLighthousePos) && pointIsInLine(l.Position, curLighthousePos, destLighthousePos) {
if linesIntersect(l.Position, c.Position, curLighthousePos, destLighthousePos) || pointIsInLine(l.Position, curLighthousePos, destLighthousePos) {
return fmt.Errorf("connection cannot intersect another connection")
}
}
Expand Down
21 changes: 21 additions & 0 deletions internal/engine/game/geom.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,24 @@ func renderTriangle(t Triangle) []geom.Coord {
func pointIsInLine(p, lineEndpoint1, lineEndpoint2 geom.Coord) bool {
return (p[1]-lineEndpoint1[1])*(lineEndpoint2[0]-lineEndpoint1[0]) == (lineEndpoint2[1]-lineEndpoint1[1])*(p[0]-lineEndpoint1[0])
}

func linesIntersect(line1Start, line1End, line2Start, line2End geom.Coord) bool {
// Unpack the coordinates for easy access
x1, y1 := line1Start.X(), line1Start.Y()
x2, y2 := line1End.X(), line1End.Y()
x3, y3 := line2Start.X(), line2Start.Y()
x4, y4 := line2End.X(), line2End.Y()

// Calculate the direction of the lines
denominator := (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
if denominator == 0 {
return false // Lines are parallel or coincident
}

// Calculate the intersection point using the determinant
t := ((x1-x3)*(y3-y4) - (y1-y3)*(x3-x4)) / denominator
u := ((x1-x3)*(y1-y2) - (y1-y3)*(x1-x2)) / denominator

// If 0 <= t <= 1 and 0 <= u <= 1, there is an intersection
return t >= 0 && t <= 1 && u >= 0 && u <= 1
}

0 comments on commit 6679677

Please sign in to comment.