Computational geometry basics
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Computational geometry basics are the small tests that let a program reason about points and lines: is a point on the left or right of a line, do two segments cross, how far is one point from another. Everything on maps and drawings is built from them.
Practical use cases
- Web app: Is the user inside the delivery zone?. A food app checks whether a customer's location falls inside a drawn delivery polygon. Counting how many polygon edges a ray from the point crosses answers it, so the order button is enabled or disabled right away. The button state changes instantly as the address is typed, without calling any outside service.
- Web app: Drawing tools that detect overlaps. A floor-plan web editor must warn when two walls drawn by the user cross. A simple left-or-right test on the endpoints tells whether two lines cross, without any heavy maths. The editor shows a red warning the moment a wall crosses another, and the user can fix the drawing straight away.
- Web app: Click detection on a canvas. A browser game or chart decides whether a mouse click landed inside a shape or touched a line, using the same side tests to react correctly. Clicks are matched to the right shape quickly, even on a canvas with hundreds of shapes.
- System: GPS, robots and game collisions. Navigation apps, robot path planners and game engines use these tests thousands of times per second to avoid obstacles and detect hits. Doing these simple checks many times per second keeps characters from walking through walls and robots from hitting obstacles.
The story: Do the Kite Strings Cross?
On Makar Sankranti the whole mohalla flew kites, and Zoya, Aarav and Kabir were in a friendly contest: whose kite string cuts the other's? From the rooftop it was hard to tell whether two strings really crossed, or just came close and passed each other.
Mira, being Mira, drew the strings as two straight lines on paper. "Let's not use measuring tapes. Let's ask one question: if I walk along string one, is a given point on my left or my right?"
If the two ends of the other string are on opposite sides of my string, the other string pokes through the line. But the line goes on forever and the string does not! So she also asked the same thing from the other string's point of view. Only when both checks agree do the strings truly cross.
That one little question, "left, right or straight?", is the building block of computational geometry. It also drives convex hulls, point-in-polygon tests, and collision checks in games.
How to spot this problem, and where you need it
You must decide something about shapes, such as whether a point is inside an area, or two lines or boxes cross, using coordinates.
Signs you need it
- The data is x and y pairs, and the question is "inside", "crosses", "touches", "left of" or "distance".
- You are tempted to use slopes and divisions and then hit bugs on vertical lines or near-zero values.
- Edge cases like points exactly on a line give wrong results.
Where to use it in a project
- Geofencing features like delivery zones, service areas and location-based alerts.
- Canvas or SVG editors that detect clicks, selections and overlapping shapes.
- Game collision, hit detection and path-planning code that runs many times per second.
The solution
Use the cross-product test: for points A, B and C, multiply and subtract their coordinate differences to learn whether C is to the left, to the right, or exactly on the line from A to B. Two segments cross when each segment's endpoints lie on opposite sides of the other. A point is inside a polygon when a ray from it crosses an odd number of edges. This uses only multiplication, so no division bugs.
Payoff: Before: buggy slope maths failing on vertical lines. After: a few multiplications that are always right.
Explain it like I am 8
Stand in the middle of a hallway looking forward. Is the door on your left or right? That is all this is. Computers just do it for dots and lines. If two dots are on opposite sides of your path, the path passes between them.
How it works, step by step
- Turn test: for three points A, B, C decide if walking A → B → C turns left, right or goes straight (the same cross product from the convex hull lesson).
- Opposite sides: C and D are on opposite sides of line A–B if one turn is left and the other is right.
- Segments cross when C and D are on opposite sides of A–B and A and B are on opposite sides of C–D.
- Special case: if a turn is exactly straight (0), the point sits on the line. Check whether it lies between the two ends.
- The same test is a building block for polygons, hulls, closest pairs and sweep-line geometry.
The code in four languages
PHP
<?php
// Turn test for A -> B -> C: positive = left, negative = right, 0 = straight.
function turn(array $a, array $b, array $c): int {
$v = ($b[0] - $a[0]) * ($c[1] - $a[1]) - ($b[1] - $a[1]) * ($c[0] - $a[0]);
return $v <=> 0; // -1, 0 or 1
}
// If c is on the line a-b, is it between a and b?
function onSegment(array $a, array $b, array $c): bool {
return min($a[0], $b[0]) <= $c[0] && $c[0] <= max($a[0], $b[0])
&& min($a[1], $b[1]) <= $c[1] && $c[1] <= max($a[1], $b[1]);
}
// Do segments a-b and c-d touch or cross?
function segmentsCross(array $a, array $b, array $c, array $d): bool {
$d1 = turn($a, $b, $c); $d2 = turn($a, $b, $d);
$d3 = turn($c, $d, $a); $d4 = turn($c, $d, $b);
if ($d1 * $d2 < 0 && $d3 * $d4 < 0) return true; // opposite sides both ways
if ($d1 === 0 && onSegment($a, $b, $c)) return true; // touching cases
if ($d2 === 0 && onSegment($a, $b, $d)) return true;
if ($d3 === 0 && onSegment($c, $d, $a)) return true;
if ($d4 === 0 && onSegment($c, $d, $b)) return true;
return false;
}
var_dump(segmentsCross([1, 1], [6, 5], [1, 5], [6, 1])); // bool(true) the X shape
var_dump(segmentsCross([1, 1], [3, 2], [4, 4], [6, 1])); // bool(false) passes beside
var_dump(segmentsCross([0, 0], [2, 2], [2, 2], [4, 0])); // bool(true) they touch at (2,2)JavaScript
// Turn test for A -> B -> C: positive = left, negative = right, 0 = straight.
function turn(a, b, c) {
const v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
return Math.sign(v); // -1, 0 or 1
}
// If c is on the line a-b, is it between a and b?
function onSegment(a, b, c) {
return Math.min(a[0], b[0]) <= c[0] && c[0] <= Math.max(a[0], b[0]) &&
Math.min(a[1], b[1]) <= c[1] && c[1] <= Math.max(a[1], b[1]);
}
// Do segments a-b and c-d touch or cross?
function segmentsCross(a, b, c, d) {
const d1 = turn(a, b, c), d2 = turn(a, b, d);
const d3 = turn(c, d, a), d4 = turn(c, d, b);
if (d1 * d2 < 0 && d3 * d4 < 0) return true; // opposite sides both ways
if (d1 === 0 && onSegment(a, b, c)) return true; // touching cases
if (d2 === 0 && onSegment(a, b, d)) return true;
if (d3 === 0 && onSegment(c, d, a)) return true;
if (d4 === 0 && onSegment(c, d, b)) return true;
return false;
}
console.log(segmentsCross([1, 1], [6, 5], [1, 5], [6, 1])); // true the X shape
console.log(segmentsCross([1, 1], [3, 2], [4, 4], [6, 1])); // false passes beside
console.log(segmentsCross([0, 0], [2, 2], [2, 2], [4, 0])); // true they touch at (2,2)Java
public class Main {
// Turn test for A -> B -> C: positive = left, negative = right, 0 = straight.
static int turn(int[] a, int[] b, int[] c) {
int v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
return Integer.signum(v); // -1, 0 or 1
}
// If c is on the line a-b, is it between a and b?
static boolean onSegment(int[] a, int[] b, int[] c) {
return Math.min(a[0], b[0]) <= c[0] && c[0] <= Math.max(a[0], b[0])
&& Math.min(a[1], b[1]) <= c[1] && c[1] <= Math.max(a[1], b[1]);
}
// Do segments a-b and c-d touch or cross?
static boolean segmentsCross(int[] a, int[] b, int[] c, int[] d) {
int d1 = turn(a, b, c), d2 = turn(a, b, d);
int d3 = turn(c, d, a), d4 = turn(c, d, b);
if (d1 * d2 < 0 && d3 * d4 < 0) return true; // opposite sides both ways
if (d1 == 0 && onSegment(a, b, c)) return true; // touching cases
if (d2 == 0 && onSegment(a, b, d)) return true;
if (d3 == 0 && onSegment(c, d, a)) return true;
if (d4 == 0 && onSegment(c, d, b)) return true;
return false;
}
public static void main(String[] args) {
System.out.println(segmentsCross(new int[]{1, 1}, new int[]{6, 5}, new int[]{1, 5}, new int[]{6, 1})); // true the X shape
System.out.println(segmentsCross(new int[]{1, 1}, new int[]{3, 2}, new int[]{4, 4}, new int[]{6, 1})); // false passes beside
System.out.println(segmentsCross(new int[]{0, 0}, new int[]{2, 2}, new int[]{2, 2}, new int[]{4, 0})); // true they touch at (2,2)
}
}Go
package main
import "fmt"
type Point struct{ x, y int }
// turn is the test for A -> B -> C: positive = left, negative = right, 0 = straight.
func turn(a, b, c Point) int {
v := (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x)
switch {
case v > 0:
return 1
case v < 0:
return -1
}
return 0 // -1, 0 or 1
}
// onSegment: if c is on the line a-b, is it between a and b?
func onSegment(a, b, c Point) bool {
return min(a.x, b.x) <= c.x && c.x <= max(a.x, b.x) &&
min(a.y, b.y) <= c.y && c.y <= max(a.y, b.y)
}
// segmentsCross reports whether segments a-b and c-d touch or cross.
func segmentsCross(a, b, c, d Point) bool {
d1, d2 := turn(a, b, c), turn(a, b, d)
d3, d4 := turn(c, d, a), turn(c, d, b)
if d1*d2 < 0 && d3*d4 < 0 {
return true // opposite sides both ways
}
if d1 == 0 && onSegment(a, b, c) { // touching cases
return true
}
if d2 == 0 && onSegment(a, b, d) {
return true
}
if d3 == 0 && onSegment(c, d, a) {
return true
}
if d4 == 0 && onSegment(c, d, b) {
return true
}
return false
}
func main() {
fmt.Println(segmentsCross(Point{1, 1}, Point{6, 5}, Point{1, 5}, Point{6, 1})) // true the X shape
fmt.Println(segmentsCross(Point{1, 1}, Point{3, 2}, Point{4, 4}, Point{6, 1})) // false passes beside
fmt.Println(segmentsCross(Point{0, 0}, Point{2, 2}, Point{2, 2}, Point{4, 0})) // true they touch at (2,2)
}Time: O(1) per pair of segments · Extra space: O(1). Just four turn tests and a few comparisons, so it is constant time for any two segments.
Watch out for
- Doing only one of the two "opposite sides" checks. A long line can separate the ends of a short rope even though the rope never reaches it.
- Forgetting the straight (zero) cases: touching ends and overlapping ropes on the same line.
- Using decimals and expecting an exact zero. With floating-point numbers compare against a tiny tolerance, or keep coordinates as whole numbers.
Quick check
- What are we really asking in the turn test?
- Do we turn left, right or go straight at B?
- Is B longer than A?
- Which point is biggest?
- C and D are on opposite sides of line A–B. Do the segments A–B and C–D definitely cross?
- Yes, always
- No, you must also check A and B against line C–D
- Only if they are equal length
- A turn test returns 0. What does it mean?
- An error happened
- A sharp left turn
- The three points are on one straight line