Missions, safety and fleets · 5 MIN READ

Path planning around no-fly zones: A*, line-of-sight pruning and replanning

Rasterize no-fly zones into an inflated grid, find the shortest path with A* and the admissible octile heuristic, prune it to a few waypoints by line of sight, fly it in the simulator and replan when a new restriction appears.

A straight line from take-off to destination is the shortest path until something is in the way: a stay-out zone, a building, a temporary restriction published in the middle of a mission. Planning turns a map of allowed space into waypoints the autopilot can fly. The classic pipeline is a grid, an A* search, smoothing, and a replan whenever the map changes; each stage has a property to protect: the safety margin, optimality and flyability.

drones · A MAP OF THE IDEA

  1. Inflate zones into a grid
  2. A* with octile heuristic
  3. Prune by line of sight
  4. Replan when map changes

Useful when

  • Optimal grid paths with far fewer expansions than Dijkstra.
  • Pruned paths are short lists of flyable waypoints.

Watch out

  • Grid resolution can close narrow gaps or waste space.
  • A straight-line RTL ignores the zones you planned around.

Implementation & operation cost: A rasterized map with an inflation step, a priority-queue search and a replan hook wherever the map can change.

01

From map to grid

Rasterize the area into cells, 5 m here, mark every cell covered by a no-fly zone, then inflate the zones by the safety buffer: the vehicle's size, the position error and the tracking error in wind. Planning on the inflated map lets the planner treat the drone as a point. Cell size is a trade: coarse cells close narrow gaps and waste space, fine cells multiply the work. Altitude can be a third dimension, but small-drone planning is usually 2D at a fixed height, with terrain and ceilings checked separately. ArduPilot does this kind of planning on board: its Dijkstra's object avoidance (OA_TYPE = 2) plans around fences and stay-out zones in Auto, Guided and RTL, and OA_MARGIN_MAX sets how far it stays from them.

02

A* and an admissible heuristic

A* expands the cell with the lowest f = g + h, where g is the cost so far and h estimates the cost to the goal. If h never overestimates (admissible), the first time the goal is expanded its path is optimal; if h is also consistent, no cell is ever expanded twice. On an 8-connected grid where straight moves cost 1 and diagonals sqrt(2), the octile distance max(dx, dy) + (sqrt(2) - 1) min(dx, dy) is the exact cost on an empty map, so it is both. Euclidean distance is admissible but weaker; Manhattan distance overestimates once diagonals are allowed and silently gives up optimality. Forbid diagonals that cut a blocked corner, and break ties deterministically (here by h, then insertion order) so the same map always yields the same path. container/heap provides the priority queue.

03

Plan, prune, fly, replan

The program blocks a 4 by 10 cell zone (a smaller zone grown by one cell), runs A* and Dijkstra's algorithm (A* with h = 0) from home to a goal 95 m east, prunes the cell path by line of sight and flies the waypoints with a 2 m acceptance radius. After the first waypoint a new restriction is published: the program blocks it, replans from the cell the drone is in, prints the new plan and flies it, then lands at the goal. Clearance records the distance from the drone to the nearest blocked cell on every step.

go
package main

import (
	"container/heap"
	"fmt"
	"log"
	"math"
	"strings"

	"gopherforge.app/drone"
)

const (
	W, H = 24, 14 // grid size in cells
	cell = 5.0    // metres per cell
	alt  = 15.0   // flight altitude, m
	sx   = 2      // start cell X
	sy   = 7      // start cell Y (home)
)

type P struct{ X, Y int }

// Grid marks blocked cells: a no-fly zone already grown by a safety buffer.
type Grid [H][W]bool

func (g *Grid) Block(x0, y0, x1, y1 int) {
	for y := y0; y <= y1; y++ {
		for x := x0; x <= x1; x++ {
			g[y][x] = true
		}
	}
}

func (g *Grid) Free(p P) bool { return p.X >= 0 && p.Y >= 0 && p.X < W && p.Y < H && !g[p.Y][p.X] }

// octile distance: the exact cost on an empty 8-connected grid, so it never
// overestimates and A* stays optimal.
func octile(a, b P) float64 {
	dx, dy := math.Abs(float64(a.X-b.X)), math.Abs(float64(a.Y-b.Y))
	return math.Max(dx, dy) + (math.Sqrt2-1)*math.Min(dx, dy)
}

type node struct {
	p    P
	f, h float64
	seq  int
}
type queue []node

func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool {
	if q[i].f != q[j].f {
		return q[i].f < q[j].f
	}
	if q[i].h != q[j].h {
		return q[i].h < q[j].h
	}
	return q[i].seq < q[j].seq
}
func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *queue) Push(x any)   { *q = append(*q, x.(node)) }
func (q *queue) Pop() any {
	old := *q
	n := old[len(old)-1]
	*q = old[:len(old)-1]
	return n
}

// AStar returns the cheapest 8-connected path and how many cells it
// expanded. With useH false it is Dijkstra's algorithm.
func AStar(g *Grid, start, goal P, useH bool) ([]P, int) {
	h := func(p P) float64 {
		if useH {
			return octile(p, goal)
		}
		return 0
	}
	cost := map[P]float64{start: 0}
	from := map[P]P{}
	closed := map[P]bool{}
	q := &queue{{p: start, f: h(start), h: h(start)}}
	seq, expanded := 0, 0
	for q.Len() > 0 {
		cur := heap.Pop(q).(node)
		if closed[cur.p] {
			continue
		}
		closed[cur.p] = true
		expanded++
		if cur.p == goal {
			path := []P{goal}
			for p := goal; p != start; {
				p = from[p]
				path = append([]P{p}, path...)
			}
			return path, expanded
		}
		for dy := -1; dy <= 1; dy++ {
			for dx := -1; dx <= 1; dx++ {
				n := P{cur.p.X + dx, cur.p.Y + dy}
				if (dx == 0 && dy == 0) || !g.Free(n) || closed[n] {
					continue
				}
				// no corner cutting: a diagonal needs both side cells free
				if dx != 0 && dy != 0 && (!g.Free(P{cur.p.X + dx, cur.p.Y}) || !g.Free(P{cur.p.X, cur.p.Y + dy})) {
					continue
				}
				c := cost[cur.p] + math.Hypot(float64(dx), float64(dy))
				if old, ok := cost[n]; ok && old <= c {
					continue
				}
				cost[n], from[n] = c, cur.p
				seq++
				heap.Push(q, node{p: n, f: c + h(n), h: h(n), seq: seq})
			}
		}
	}
	return nil, expanded
}

// Visible samples the straight segment between two cell centres.
func Visible(g *Grid, a, b P) bool {
	n := int(math.Ceil(math.Hypot(float64(b.X-a.X), float64(b.Y-a.Y)) * 4))
	for i := 0; i <= n; i++ {
		t := float64(i) / float64(max(n, 1))
		x := float64(a.X) + t*float64(b.X-a.X)
		y := float64(a.Y) + t*float64(b.Y-a.Y)
		if !g.Free(P{int(math.Round(x)), int(math.Round(y))}) {
			return false
		}
	}
	return true
}

// Prune keeps a cell only when the next one is not in line of sight from
// the last kept cell.
func Prune(g *Grid, path []P) []P {
	out := []P{path[0]}
	for i := 1; i < len(path)-1; i++ {
		if !Visible(g, out[len(out)-1], path[i+1]) {
			out = append(out, path[i])
		}
	}
	return append(out, path[len(path)-1])
}

func length(path []P) float64 {
	sum := 0.0
	for i := 1; i < len(path); i++ {
		sum += math.Hypot(float64(path[i].X-path[i-1].X), float64(path[i].Y-path[i-1].Y)) * cell
	}
	return sum
}

func toWorld(p P) drone.Vec3 {
	return drone.Vec3{X: float64(p.X-sx) * cell, Y: float64(p.Y-sy) * cell, Z: alt}
}
func toCell(v drone.Vec3) P {
	return P{int(math.Round(v.X/cell)) + sx, int(math.Round(v.Y/cell)) + sy}
}

// Clearance is the distance from a position to the nearest blocked cell.
func Clearance(g *Grid, v drone.Vec3) float64 {
	best := math.Inf(1)
	for y := 0; y < H; y++ {
		for x := 0; x < W; x++ {
			if !g[y][x] {
				continue
			}
			c := toWorld(P{x, y})
			dx := math.Max(0, math.Abs(v.X-c.X)-cell/2)
			dy := math.Max(0, math.Abs(v.Y-c.Y)-cell/2)
			best = math.Min(best, math.Hypot(dx, dy))
		}
	}
	return best
}

func draw(g *Grid, path, wps []P) {
	rows := make([][]byte, H)
	for y := range rows {
		rows[y] = []byte(strings.Repeat(".", W))
		for x := 0; x < W; x++ {
			if g[y][x] {
				rows[y][x] = '#'
			}
		}
	}
	for _, p := range path {
		rows[p.Y][p.X] = '*'
	}
	for i, p := range wps {
		rows[p.Y][p.X] = byte('0' + i)
	}
	for y := H - 1; y >= 0; y-- { // north up
		fmt.Println("  " + string(rows[y]))
	}
}

func main() {
	var g Grid
	g.Block(9, 2, 12, 11) // zone x 10..11, y 3..10 grown by one 5 m cell
	start, goal := P{sx, sy}, P{21, sy}

	path, n := AStar(&g, start, goal, true)
	dpath, nd := AStar(&g, start, goal, false)
	wps := Prune(&g, path)
	fmt.Printf("A*: %d cells, %.1f m, expanded %d cells\n", len(path), length(path), n)
	fmt.Printf("Dijkstra: %d cells, %.1f m, expanded %d cells\n", len(dpath), length(dpath), nd)
	fmt.Printf("pruned to %d waypoints, %.1f m\n", len(wps), length(wps))
	draw(&g, path, wps)

	sim := drone.New(drone.Config{Wind: drone.Vec3{X: -2, Y: 1}, Gust: 1, MaxSpeed: 8, Seed: 3})
	d := sim.Drone()
	if err := d.Arm(); err != nil {
		log.Fatal(err)
	}
	d.TakeOff(alt)
	sim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })

	plan, clearance := 1, math.Inf(1)
	for i := 1; i < len(wps); i++ {
		p := toWorld(wps[i])
		d.GoTo(p)
		last := i == len(wps)-1
		if !sim.RunUntil(90, func(float64) bool {
			clearance = math.Min(clearance, Clearance(&g, d.State().Pos))
			if last {
				return d.Arrived()
			}
			return d.State().Pos.Sub(p).Len() < 2
		}) {
			log.Fatalf("waypoint %d not reached", i)
		}
		fmt.Printf("plan %d, waypoint %d %v at %.1f s\n", plan, i, p, sim.Time())
		if plan == 1 && i == 1 {
			// A new restriction is published: plan again from here.
			plan = 2
			g.Block(16, 4, 18, 13)
			here := toCell(d.State().Pos)
			path, n = AStar(&g, here, goal, true)
			wps = Prune(&g, path)
			i = 0
			fmt.Printf("new zone x 16..18, y 4..13: replan from cell %d,%d: %d waypoints, %.1f m, expanded %d\n",
				here.X, here.Y, len(wps), length(wps), n)
			draw(&g, path, wps)
		}
	}
	// Land at the goal: a straight-line RTL from here would cross the zones.
	d.Land()
	sim.RunUntil(60, func(float64) bool {
		clearance = math.Min(clearance, Clearance(&g, d.State().Pos))
		return d.State().Landed
	})
	fmt.Printf("closest approach to a blocked cell: %.1f m\n", clearance)
	if err := sim.Save(); err != nil {
		log.Fatal(err)
	}
}
Read the code

A* finds a 20-cell, 115.7 m path over the zone after expanding 85 cells; Dijkstra finds a path of the same 115.7 m but expands 274. Pruning keeps 4 waypoints, the start, two corners above the zone and the goal, and cuts the flight to 110.2 m because straight segments replace the 45 degree staircase. The new zone at x 16..18 closes the northern route, so the replan from cell 9,12 runs down the corridor between the zones and under the new one: 5 waypoints, 108.5 m, 79 cells expanded. The drone lands at (95.3, 0.8, 0.0) and came no closer than 0.6 m to a blocked cell, so the buffer absorbed its tracking error.

04

Smoothing and waypoints

Grid paths zigzag in 45 degree steps, and a waypoint per cell would make the autopilot slow down at each one. Line-of-sight pruning (string pulling) keeps a cell only when the next cell cannot be seen in a straight line from the last kept one, checking the segment against the inflated grid; any-angle planners such as Theta* fold the same test into the search. The result is never longer than the grid path and never crosses a blocked cell, though it is not guaranteed shortest in continuous space. Convert cell centres to the vehicle's frame, add the altitude, and keep the acceptance radius smaller than the buffer, or corner cutting near a zone eats the margin; ArduPilot's documentation gives the same advice for its waypoint radius and fence margin.

05

Replanning and the way back

Replan from the vehicle's current cell whenever the map changes: a new restriction, an obstacle seen by a sensor, a wind that makes a leg infeasible. Keep flying the old plan only while it is still clear, and make the switch an explicit event in the log. On grids this small a full A* is cheap enough to rerun; on large or frequently changing maps, incremental planners such as D* Lite reuse the previous search. Plan the way back too: a plain RTL flies a straight line home and in this example would cross both zones, which is why the program lands at the goal. ArduPilot can run its Dijkstra planner in RTL, and its SmartRTL mode retraces the path already flown.

06

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. The console shows both grids; Output replays the flight with every waypoint flown from both plans on the map, the turn at the first waypoint where the replan happened, and the landing at the goal. Move the second zone or switch the heuristic to Manhattan distance and compare the paths and the expanded counts.

TAKE THIS WITH YOU

Inflate no-fly zones by the safety buffer, search the grid with A* and an admissible, consistent heuristic such as the octile distance, prune the path by line of sight into a few waypoints, keep the acceptance radius below the buffer, and replan from the current position whenever the map changes.

Check your understanding

On an 8-connected grid you switch the A* heuristic from octile to Manhattan distance, and some paths get longer. What went wrong?

Go to the source

Progress stays in this browser. No account needed.