"""Spray-drone plan for a whole building: every facade, in an order the wind allows, with transits that never cut the building. ``drone_plan.build`` plans ONE flat facade. A building adds three things this module handles: 1. **Wind has a direction.** A wind that pushes the airframe TOWARD the wall (onshore) cuts the margin to the wall, and a wind that blows AWAY from it carries the spray off the wall (thin, uneven film). Each facade gets its wind component along its outward normal; a facade over either limit is DEFERRED (re-plan when the wind shifts), not forced, and the rest of the building still gets a plan. 2. **Facade order and corners.** Facades are flown in footprint order starting from the one nearest the launch point, skipping deferred ones. Between facades the drone follows the building outline at the airframe distance, going round every corner on the bisector (distance d / cos(half the turn)), so a transit from one side to another never cuts across the roof or through a wall. Every transit is checked: its closest approach to every footprint edge must stay at least the airframe distance. 3. **Keep-out zones.** Circles (e, n, radius) the airframe must not enter (a power line pole, a neighbour's courtyard). A facade line or transit that touches one is refused with the reason, never routed around silently. Coordinates: east, north metres from the launch point, corners listed COUNTER-CLOCKWISE seen from above (so the outward normal of an edge A->B is to its right, as in ``drone_plan.facade_frame``). Wind direction is meteorological: the bearing the wind blows FROM, clockwise from north. The wind limits below are explicit, adjustable DEFAULTS for planning, not a safety certification: flight approval, spraying authorisation and the pilot's own go/no-go remain with the operator. """ from __future__ import annotations import math import drone_plan as dp ONTO_WALL_LIMIT_MS = 3.0 # wind component pushing the airframe toward the wall OFF_WALL_LIMIT_MS = 5.0 # wind component blowing the spray away from the wall DISCLAIMER = ("planning aid only: the wind limits are adjustable defaults, not a safety certification. Flight approval, spraying " "authorisation and the pilot's go/no-go remain with the operator.") def signed_area(poly): return 0.5 * sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(poly, poly[1:] + poly[:1])) def _unit(v): n = math.hypot(*v) return (v[0] / n, v[1] / n) def wind_toward(speed_ms, from_deg): """(east, north) velocity of the air for wind blowing FROM ``from_deg`` (clockwise from north).""" r = math.radians(from_deg) return (-speed_ms * math.sin(r), -speed_ms * math.cos(r)) def wind_on_facade(speed_ms, from_deg, out, along): v = wind_toward(speed_ms, from_deg) normal = v[0] * out[0] + v[1] * out[1] # > 0 blows away from the wall return {"onto_wall_ms": round(max(0.0, -normal), 2), "off_wall_ms": round(max(0.0, normal), 2), "along_ms": round(abs(v[0] * along[0] + v[1] * along[1]), 2)} def corner_offset(prev_out, next_out, corner, d): """The point at distance d from both walls meeting at ``corner``, on the outer side (clamped for very sharp corners).""" bis = _unit((prev_out[0] + next_out[0], prev_out[1] + next_out[1])) cos_half = max(0.17, bis[0] * prev_out[0] + bis[1] * prev_out[1]) return (corner[0] + bis[0] * d / cos_half, corner[1] + bis[1] * d / cos_half) def seg_dist(p, q, a, b): """Closest distance between segments pq and ab (2D).""" def point_seg(pt, s0, s1): dx, dy = s1[0] - s0[0], s1[1] - s0[1] L = dx * dx + dy * dy t = 0.0 if L == 0 else max(0.0, min(1.0, ((pt[0] - s0[0]) * dx + (pt[1] - s0[1]) * dy) / L)) return math.hypot(pt[0] - (s0[0] + t * dx), pt[1] - (s0[1] + t * dy)) def cross(o, u, v): return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]) if cross(p, q, a) * cross(p, q, b) < 0 and cross(a, b, p) * cross(a, b, q) < 0: return 0.0 return min(point_seg(p, a, b), point_seg(q, a, b), point_seg(a, p, q), point_seg(b, p, q)) def polyline_clearance(path, footprint): n = len(footprint) return min(seg_dist(p, q, footprint[k], footprint[(k + 1) % n]) for p, q in zip(path[:-1], path[1:]) for k in range(n)) def _hits_keepout(path, zones): return [z for z in zones for p, q in zip(path[:-1], path[1:]) if seg_dist(p, q, (z[0], z[1]), (z[0], z[1])) <= z[2]] def plan_building(footprint, facades, home, spray, standoff_m=0.30, boom_m=0.5, positioning_m=0.02, wind_ms=3.0, wind_from_deg=0.0, flight_min=18.0, tank_l=10.0, max_alt_m=120.0, keep_out=(), onto_wall_limit_ms=ONTO_WALL_LIMIT_MS, off_wall_limit_ms=OFF_WALL_LIMIT_MS): """Plan every facade of a building. ``footprint``: corners (e, n) m counter-clockwise. ``facades``: one entry per edge (corner i -> corner i+1), a dict ``{"strokes_mm", "width_mm", "height_mm"}`` from the facade's robot_planner plan, or None for an edge that is not painted. """ n = len(footprint) if n < 3 or len(facades) != n: raise ValueError(f"{n} corners need {n} facade entries (use None for an edge that is not painted); got {len(facades)}") if signed_area(list(footprint)) <= 0: raise ValueError("list the corners counter-clockwise (seen from above, east = x, north = y): the outward side of each edge " "A->B is its right-hand side") d = standoff_m + boom_m frames = [] for i in range(n): a, b = footprint[i], footprint[(i + 1) % n] along, out, length = dp.facade_frame(a, b) frames.append((a, b, along, out, length)) built, deferred = {}, [] for i, spec in enumerate(facades): if spec is None: continue a, b, along, out, length = frames[i] try: res = dp.build(spec["strokes_mm"], spec["width_mm"], spec["height_mm"], a, b, home, spray, standoff_m, positioning_m, wind_ms, flight_min, tank_l=tank_l, max_alt_m=max_alt_m, boom_m=boom_m) except ValueError as exc: raise ValueError(f"facade {i + 1} (corner {i + 1} to {(i + 1) % n + 1}): {exc}") from exc w = wind_on_facade(wind_ms, wind_from_deg, out, along) reasons = list(res["gate"]["reasons"]) if w["onto_wall_ms"] > onto_wall_limit_ms: reasons.append(f"wind pushes the airframe toward this wall at {w['onto_wall_ms']} m/s (limit {onto_wall_limit_ms}): defer") if w["off_wall_ms"] > off_wall_limit_ms: reasons.append(f"wind blows the spray off this wall at {w['off_wall_ms']} m/s (limit {off_wall_limit_ms}): defer") line = [(a[0] + out[0] * d, a[1] + out[1] * d), (b[0] + out[0] * d, b[1] + out[1] * d)] for z in _hits_keepout(line, keep_out): reasons.append(f"the flight line enters the keep-out zone at ({z[0]}, {z[1]}) r {z[2]} m") built[i] = {"facade": i + 1, "edge": [i + 1, (i + 1) % n + 1], "length_m": round(length, 2), "wind": w, "go": not reasons, "reasons": reasons, "result": res, "flight_line_en": line} if reasons: deferred.append({"facade": i + 1, "reasons": reasons}) flyable = [i for i in built if built[i]["go"]] # Start at the flyable facade whose start corner is nearest the launch point, then follow the outline. order = [] if flyable: start = min(flyable, key=lambda i: math.hypot(*frames[i][0])) order = [i for k in range(n) if (i := (start + k) % n) in flyable] transits, ok = [], True for i, j in zip(order[:-1], order[1:]): a_i, b_i, along_i, out_i, len_i = frames[i] width_m = facades[i]["width_mm"] / 1000 path = [(a_i[0] + along_i[0] * width_m + out_i[0] * d, a_i[1] + along_i[1] * width_m + out_i[1] * d), (b_i[0] + out_i[0] * d, b_i[1] + out_i[1] * d)] k = (i + 1) % n while True: # corners k = i+1 ... j, the last one joins facade j prev_out, next_out = frames[(k - 1) % n][3], frames[k][3] path.append(corner_offset(prev_out, next_out, footprint[k], d)) if k == j: break k = (k + 1) % n path.append((frames[j][0][0] + frames[j][3][0] * d, frames[j][0][1] + frames[j][3][1] * d)) clear = polyline_clearance(path, list(footprint)) hits = _hits_keepout(path, keep_out) transits.append({"from": i + 1, "to": j + 1, "path_en": [[round(x, 2), round(y, 2)] for x, y in path], "length_m": round(sum(math.dist(p, q) for p, q in zip(path[:-1], path[1:])), 1), "min_clearance_m": round(clear, 3), "clearance_ok": clear >= d - 0.02, "keep_out_hits": [list(z) for z in hits]}) ok = ok and clear >= d - 0.02 and not hits sorties = sum(len(built[i]["result"]["sorties"]) for i in order) return { "go": bool(order) and ok, # something is flyable and every transit is clear and outside the zones "sequence": [i + 1 for i in order], "deferred": deferred, "facades": [{k: v for k, v in built[i].items() if k != "result"} | { "sorties": built[i]["result"]["sorties"], "paint_l": built[i]["result"]["paint_l_total"], "gate": built[i]["result"]["gate"]} for i in sorted(built)], "transits": transits, "sorties_total": sorties, "paint_l_total": round(sum(built[i]["result"]["paint_l_total"] for i in order), 2), "airframe_distance_m": round(d, 2), "limits": {"onto_wall_limit_ms": onto_wall_limit_ms, "off_wall_limit_ms": off_wall_limit_ms}, "wind": {"speed_ms": wind_ms, "from_deg": wind_from_deg}, "complete_building": not deferred, # False while any selected facade is deferred (wind, gates, keep-out) "disclaimer": DISCLAIMER, "_built": built, "_frames": frames, }