Missions, safety and fleets · 6 MIN READ
Geofencing: inclusion and exclusion polygons, ray casting and predicting a breach
Implement point-in-polygon with an explicit boundary rule, combine inclusion zones, exclusion zones and a ceiling, predict the time to the boundary from velocity, and compare a reactive fence with a predictive guard in the simulator.
A geofence stands between a software bug, a gust or a confused operator and an airspace infringement. Most flight stacks act only once the vehicle is already outside, and a multicopter at 8 m/s needs several metres to stop, so where the fence acts matters as much as where it is drawn. The geometry is short; the edge cases and the physics are where fences fail.
drones · A MAP OF THE IDEA
- Draw inclusion, exclusion
- Check point and ceiling
- Predict time to boundary
- Hold, return or land
Useful when
- Ray casting handles concave polygons in a few lines.
- Prediction stops the vehicle inside the fence, not beyond it.
Watch out
- Points on edges and rays through vertices need explicit rules.
- Position error and tailwind eat into any margin you draw.
Implementation & operation cost: A point-in-polygon test per position update, an intersection per edge for prediction, and a margin chosen from measured braking.
Inclusion, exclusion and ceiling
A fence plan combines inclusion areas the vehicle must stay inside, exclusion areas it must stay out of (an airfield approach, a crowd, a mast) and altitude limits. PX4 and ArduPilot accept polygons and circles of both kinds, uploaded with the MAVLink mission protocol as the fence mission type, next to a simple cylinder around home with a maximum radius and altitude; with several inclusion polygons, ArduPilot lets the vehicle fly only where they all overlap. A position is allowed only if it is inside the inclusion area, outside every exclusion area and below the ceiling. The check runs on the position estimate, so it is only as good as the estimate: a GPS glitch can trigger a false breach, and a fence drawn to the metre needs a margin for position error.
Ray casting and its edge cases
Cast a ray from the point towards +X and count the edges it crosses: an odd count means inside. The condition (a.Y > p.Y) != (b.Y > p.Y) treats each edge as half-open, so a ray through a vertex is counted once, not twice, and horizontal edges are skipped. Points exactly on an edge are the ambiguous case: plain ray casting puts left and bottom edges inside and right and top edges outside, which is fine for drawing and wrong for a safety check, so test for the boundary first and decide explicitly. Concave polygons need nothing special, but self-intersecting ones break the parity rule and a fence editor should reject them. For fences of a few kilometres, local metres around a reference point are accurate enough; over tens of kilometres, project carefully.
Check points, then fly at the fence
The program defines an L-shaped field, a no-fly box around a mast and a 40 m ceiling. Locate is ray casting with an on-segment test first; Allowed combines the three rules and treats the boundary as a breach. Then the drone dashes east at 8 m/s with the simulator's Geofence set: every 2 s the program prints the time to the boundary along the velocity and the stopping distance, the simulator's failsafe switches to RTL on the breach, and the drone overshoots before it stops. Back inside, a careless mission overrides the RTL and sends it out again; the fence has re-armed and catches the second breach. A second flight holds as soon as the stopping distance plus a 3 m margin reaches the boundary, then tries to climb through the ceiling under velocity control.
package main
import (
"fmt"
"log"
"math"
"gopherforge.app/drone"
)
// An L-shaped field (concave), a no-fly box around a mast, and a ceiling.
var (
fence = []drone.Vec3{{X: -40, Y: -40}, {X: 60, Y: -40}, {X: 60, Y: 20}, {X: 10, Y: 20}, {X: 10, Y: 60}, {X: -40, Y: 60}}
mast = []drone.Vec3{{X: -25, Y: 30}, {X: -10, Y: 30}, {X: -10, Y: 45}, {X: -25, Y: 45}}
)
const ceiling = 40.0
func cross(a, b drone.Vec3) float64 { return a.X*b.Y - a.Y*b.X }
// onSegment reports whether p lies on the segment a-b (within 1 cm).
func onSegment(a, b, p drone.Vec3) bool {
ab, ap := b.Sub(a).Horizontal(), p.Sub(a).Horizontal()
if math.Abs(cross(ab, ap)) > 0.01*ab.Len() {
return false
}
dot := ab.X*ap.X + ab.Y*ap.Y
return dot >= 0 && dot <= ab.X*ab.X+ab.Y*ab.Y
}
// Locate is ray casting with an explicit boundary case. A horizontal ray goes
// east from p; an edge counts when one end is strictly above p and the other
// is not, so a ray through a vertex is counted exactly once.
func Locate(poly []drone.Vec3, p drone.Vec3) string {
in := false
for i, j := 0, len(poly)-1; i < len(poly); j, i = i, i+1 {
a, b := poly[i], poly[j]
if onSegment(a, b, p) {
return "boundary"
}
if (a.Y > p.Y) != (b.Y > p.Y) {
x := a.X + (p.Y-a.Y)*(b.X-a.X)/(b.Y-a.Y)
if p.X < x {
in = !in
}
}
}
if in {
return "inside"
}
return "outside"
}
// Allowed applies the whole fence: inclusion polygon, exclusion zone and
// ceiling. A point on the boundary is treated as a breach.
func Allowed(p drone.Vec3) (bool, string) {
switch {
case Locate(fence, p) != "inside":
return false, "outside the field"
case Locate(mast, p) != "outside":
return false, "in the mast zone"
case p.Z > ceiling:
return false, "above the ceiling"
}
return true, "ok"
}
// TimeToBoundary returns how long until p moving at v crosses an edge.
func TimeToBoundary(poly []drone.Vec3, p, v drone.Vec3) float64 {
best := math.Inf(1)
v = v.Horizontal()
for i := range poly {
a, b := poly[i], poly[(i+1)%len(poly)]
e, w := b.Sub(a).Horizontal(), a.Sub(p).Horizontal()
den := cross(v, e)
if den == 0 {
continue // moving parallel to this edge
}
t, u := cross(w, e)/den, cross(w, v)/den
if t >= 0 && u >= 0 && u <= 1 && t < best {
best = t
}
}
return best
}
// stopping distance at speed v: reaction time plus braking at decel m/s^2.
func stopping(v float64) float64 { return v*0.2 + v*v/(2*4.0) }
func takeOff(sim *drone.Sim, d *drone.Drone) {
if err := d.Arm(); err != nil {
log.Fatal(err)
}
if err := d.TakeOff(15); err != nil {
log.Fatal(err)
}
sim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })
}
func newSim() *drone.Sim {
return drone.New(drone.Config{Wind: drone.Vec3{X: 2}, Gust: 0.5, Geofence: fence, Ceiling: ceiling, Seed: 5})
}
func main() {
fmt.Println("point mine drone.Inside allowed")
points := []struct {
name string
p drone.Vec3
}{
{"home", drone.Vec3{}},
{"notch", drone.Vec3{X: 30, Y: 40}},
{"east edge", drone.Vec3{X: 60, Y: 0}},
{"west edge", drone.Vec3{X: -40, Y: 0}},
{"inner corner", drone.Vec3{X: 10, Y: 20}},
{"ray via vertex", drone.Vec3{X: 0, Y: 20}},
{"mast", drone.Vec3{X: -15, Y: 35, Z: 20}},
{"too high", drone.Vec3{X: 0, Y: 10, Z: 45}},
}
for _, c := range points {
ok, why := Allowed(c.p)
fmt.Printf("%-15s %-8s %-12v %v (%s)\n", c.name, Locate(fence, c.p), drone.Inside(fence, c.p), ok, why)
}
// Reactive: dash east at 8 m/s and let the simulator's fence act. Once
// the drone is back inside, a careless mission sends it out again.
sim := newSim()
d := sim.Drone()
takeOff(sim, d)
start := sim.Time()
if err := d.SetVelocity(drone.Vec3{X: 8}, 0); err != nil {
log.Fatal(err)
}
fmt.Println("\nreactive fence: dash east at 8 m/s from home")
breaches, peak, resumed, prev := 0, 0.0, false, d.State().Mode
sim.RunUntil(180, func(t float64) bool {
st := d.State()
peak = math.Max(peak, st.Pos.X)
k := t - start
if breaches == 0 && k > 1 && math.Abs(k-math.Round(k)) < sim.Dt()/2 && int(math.Round(k))%2 == 0 {
speed := st.Vel.Horizontal().Len()
fmt.Printf(" t=%4.1f s x=%5.1f m %4.1f m/s boundary in %5.1f s, stop needs %4.1f m\n",
k, st.Pos.X, speed, TimeToBoundary(fence, st.Pos, st.Vel), stopping(speed))
}
if st.Mode == drone.Returning && prev != drone.Returning {
breaches++
fmt.Printf(" t=%4.1f s x=%5.1f m %4.1f m/s simulator: geofence breach %d, RTL\n",
k, st.Pos.X, st.Vel.Horizontal().Len(), breaches)
}
if breaches == 1 && !resumed && st.Mode == drone.Returning && st.Pos.X < 45 {
resumed = true
fmt.Printf(" t=%4.1f s x=%5.1f m overshoot was %.1f m; mission resumes: go to x=75 m\n", k, st.Pos.X, peak-60)
peak = 0
d.GoTo(drone.Vec3{X: 75, Z: 15}) // overrides the RTL: a bug
}
prev = st.Mode
return st.Landed
})
st := d.State()
fmt.Printf(" second overshoot %.1f m; %s %.1f m from home at t=%.1f s\n", peak-60, st.Mode, st.Pos.Horizontal().Len(), sim.Time()-start)
// Predictive: same dash, but hold when the stopping distance plus a
// margin reaches the boundary along the velocity.
g := newSim()
gd := g.Drone()
takeOff(g, gd)
gd.SetVelocity(drone.Vec3{X: 8}, 0)
held, gmax := false, 0.0
g.Run(20, func(float64) {
st := gd.State()
gmax = math.Max(gmax, st.Pos.X)
speed := st.Vel.Horizontal().Len()
if !held && TimeToBoundary(fence, st.Pos, st.Vel)*speed <= stopping(speed)+3 {
held = true
gd.Hold()
fmt.Printf("\npredictive guard: hold at x=%.1f m, %.1f m/s\n", st.Pos.X, speed)
}
})
fmt.Printf(" closest approach %.1f m inside the fence, mode %s\n", 60-gmax, gd.State().Mode)
// The ceiling holds in every mode, even under velocity control.
gd.SetVelocity(drone.Vec3{Z: 3}, 0)
g.Run(15, nil)
fmt.Printf(" climb at 3 m/s for 15 s: altitude %.1f m under the %.0f m ceiling\n", gd.State().Pos.Z, ceiling)
if err := g.SaveAs("guarded"); err != nil {
log.Fatal(err)
}
if err := sim.Save(); err != nil {
log.Fatal(err)
}
}drone.Inside says false for the east edge and true for the west edge; Locate calls both boundary and Allowed rejects them, like the inner corner of the L. The ray from (0, 20) through the vertex (10, 20) still counts as inside. The mast point is inside the field but in the exclusion zone, and 45 m is above the ceiling. In the dash the boundary is 0.1 s away at t=8.0 s and the first breach comes at 8.1 s at x=60.3 m; the drone overshoots by 4.6 m, half the 9.6 m that the deliberately cautious 4 m/s2 braking figure predicts. Back inside at x=44.9 m the resumed mission overrides the RTL, but the fence has re-armed: the second breach at 16.2 s comes at 11.3 m/s, overshoots by 8.5 m, and the second RTL lands the drone 0.3 m from home. The guard holds at x=47.5 m and stops 8.2 m inside, and a 15 s climb at 3 m/s levels off at 39.0 m, 1 m under the ceiling.
Predict the breach instead of detecting it
The time to the boundary is the smallest t at which p + v t crosses an edge, a ray-segment intersection per edge computed with 2D cross products. Compare the distance along the velocity with the stopping distance v t_react + v squared / (2a): the reaction time covers the telemetry period and command latency, and a is the braking you have measured, not the best case. When the distance falls below that plus a margin for position error and tailwind, hold or turn. PX4's GF_ACTION and ArduPilot's FENCE_ACTION fire only after the breach; newer PX4 adds a contingency geofence (GF_CONT_H_MARGIN, GF_CONT_ACTION) inside the fence and asks for a margin of at least v squared / 2a, and ArduPilot can stop a Copter before the fence in Loiter when object avoidance is set up.
Breach actions
What should happen after a breach depends on what lies beyond the line. Hold stops at once near the boundary and leaves the pilot to decide. Return flies home, usually after climbing to a return altitude, which is wrong if home lies behind an exclusion zone or the climb crosses a ceiling. Land puts the vehicle down outside the fence: acceptable over an empty field, dangerous over a road. Flight termination cuts the motors and is reserved for vehicles with a parachute or for cases where anything else is worse. The simulator's action is RTL on every new breach, re-armed once the drone is back inside, so mission code that overrides the return is caught again; better mission code never overrides a failsafe at all. A real setup chooses the action per fence and checks that the return path stays inside. Log every breach with position, velocity and estimate quality: most breaches turn out to be planning or estimation errors.
Fly it in GopherForge
In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program, keep mission.go and tap Run. Output shows two recordings: flight.gfflight is the reactive run, with the L-shaped fence on the map, both breaches, both overshoots and the return home; guarded.gfflight stops short of the east edge and levels off under the ceiling in the altitude strip. Set the margin to 0 or the dash speed to 12 m/s and watch where the guard stops.
TAKE THIS WITH YOU
Use ray casting with an explicit rule for points on the boundary, combine inclusion, exclusion and ceiling checks, and remember that most breach actions fire after the breach. Predict the boundary from velocity and stopping distance, and keep a margin inside the fence for braking, wind and position error.
Check your understanding
A multicopter flies at 8 m/s straight at a geofence whose action is RTL. Why does it end up several metres outside?
Go to the source
Progress stays in this browser. No account needed.