Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/Navigation Terrain Following.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ The mode narrates itself on the OSD. In plain terms: **TERRAIN AHEAD!** talks ab
| **TERRAIN NOT READY** | Info | Engagement refused — no usable terrain data yet. | Fly stock cruise; check tiles / SD card if it persists. |
| **TERRAIN LOST - ALT FROZEN** | Caution | The terrain data stopped coming while the mode was holding your height — the altitude target is **frozen at the last good value** (it never descends on dead data). | Never descend blind; navigate out on the frozen altitude (it resumes after a few seconds of good data). |
| **TERRAIN LOOKAHEAD OFF** | Info | The forward scan is unavailable (no heading estimate, or ground speed below 3 m/s). | Only the reactive floor guards you now — do **not** expect the early “TERRAIN AHEAD!” warning while this shows. |
| **TERRAIN: MAP/GPS ALT DIFFER** | Info | The terrain map and the GPS altitude put your take-off spot more than 5 m apart: the map is wrong there, the GPS altitude was off when you armed, or you armed well above the mapped ground. The mode is using the lower of the two, so it errs toward flying higher. | Expect heights above ground to be off by up to that difference. If it shows at one site every time, the map is wrong there. |

> **Where heights are measured from.** Height above ground is your estimated altitude minus how far the terrain under you rises above your take-off spot. The mode fixes that spot when you **arm**: it reads the map where the aircraft stands, and compares it with the GPS altitude there. It uses the **lower** of the two, because a take-off height that is too high would put you closer to the ground than the mode believes. A map error at your take-off spot therefore no longer carries into the whole flight when it reads high; when it reads low, or when you launch from above the mapped ground, the mode flies higher by that amount.
> **Seeing "TERRAIN! PULL UP!" often while riding low? That is the geometry of the floor, not a fault.** The floor (default 60 m) is already the lowest safe height, so the warning band sits only 5 m under it — below a minimum there is no room to spare. And the mode does not glue AGL to the ground 1:1: the climb is rate-limited, so on rising slopes the real height sags a little under the held value, which is exactly when the warning earns its keep. **If you want quiet — hold height in hand:** engage at 80 m and it holds 80; the warning still starts only below 55 m, so you fly with 25 m of calm. Engage below the floor and it simply climbs to ~10 m above it by itself (*TERRAIN AUTO CLIMB TO MIN*), no alarm while the climb is winning.
Expand Down
6 changes: 6 additions & 0 deletions src/main/io/osd.c
Original file line number Diff line number Diff line change
Expand Up @@ -6379,6 +6379,12 @@ textAttributes_t osdGetSystemMessage(char *buff, size_t buff_size, bool isCenter
&& terrainNavHoldGetWarning() != TERRAIN_NAV_HOLD_WARN_NONE) {
ADD_MSG(OSD_MESSAGE_STR(OSD_MSG_TERRAIN_AUTO_CLIMB));
}
/* ADDS MAXIMUM OF 1 MESSAGE TO TOTAL: the map and the GPS altitude
* disagree about the take-off height, so the heights the hold works
* with may be off by that much (the lower reference is in use) */
if (terrainNavHoldIsEngaged() && terrainReferenceReadingsDisagree()) {
ADD_MSG(OSD_MESSAGE_STR(OSD_MSG_TERRAIN_REFERENCE));
}
#endif
if (STATE(AIRPLANE)) { /* ADDS MAXIMUM OF 3 MESSAGES TO TOTAL */
#ifdef USE_FW_AUTOLAND
Expand Down
1 change: 1 addition & 0 deletions src/main/io/osd.h
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
#define OSD_MSG_TERRAIN_NO_HEADING "TERRAIN LOOKAHEAD OFF"
#define OSD_MSG_TERRAIN_AUTO_CLIMB "TERRAIN AUTO CLIMB TO MIN"
#define OSD_MSG_TERRAIN_AHEAD "TERRAIN AHEAD!"
#define OSD_MSG_TERRAIN_REFERENCE "TERRAIN: MAP/GPS ALT DIFFER"
#endif

#ifdef USE_ADSB
Expand Down
155 changes: 120 additions & 35 deletions src/main/terrain/terrain.c
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

#include <math.h>

#include "platform.h"

#ifdef USE_TERRAIN
Expand Down Expand Up @@ -73,15 +75,34 @@ static struct {
.terrainAMSL = 0,
};

static struct {
bool homeAltitudeFound;
float homeAltitudeM;
gpsLocation_t homeLocation;
} terrainHomePos = {
.homeAltitudeFound = false,
.homeAltitudeM = 0.0f,
.homeLocation = {.lat = 0, .lon = 0},
};
/*
* The height reference: the map height that the navigation's altitude zero stands for.
* Height above ground = estimated altitude - (map height here - reference).
*
* The altitude zero is set where the aircraft arms (inav_reset_altitude), which need not be
* where the GPS origin was set by the first fix. So the map is read where the aircraft
* stands while it is disarmed, and kept with the altitude it had there: the reference is
* that map height minus that altitude. Arming keeps the last such point for the flight.
*
* The GPS altitude of the altitude zero (the GPS origin's altitude) is a second reading of
* the same height, on the same datum as the map. The two differ by the map's error at the
* take-off spot, the GPS altitude error and the height of the aircraft above the ground when
* it armed. The lower of the two is used: a reference that is too high puts the ground too
* low and the aircraft closer to it than it believes, a reference that is too low only
* makes it fly higher. So a map that is too high at the take-off spot no longer lowers the
* whole flight, and a GPS altitude that reads high changes nothing.
*/
typedef struct {
bool located; // a position and altitude have been recorded
gpsLocation_t location;
float altitudeCm; // estimated altitude at that position, local frame
bool heightFound; // the map has answered for that position
float heightM;
bool gpsUsable; // the GPS altitude was good enough there to be the second reading
} terrainGroundPoint_t;

static terrainGroundPoint_t groundDisarmed; // follows the aircraft while it is disarmed
static terrainGroundPoint_t groundFlight; // the point of the flight, taken at arming

/**
* @brief Get the height above mean sea level (AMSL) in meters for a given GPS location.
Expand Down Expand Up @@ -136,11 +157,92 @@ void terrainInit(void)
{
}

// Arming hands the disarmed point over to the flight. An emergency re-arm in the air keeps
// the flight's point, as the estimator keeps its altitude zero
static terrainGroundPoint_t *terrainGroundPointInUse(void)
{
static bool wasArmed = false;

const bool armed = ARMING_FLAG(ARMED);
if (armed && !wasArmed && !(STATE(IN_FLIGHT_EMERG_REARM) && groundFlight.located)) {
groundFlight = groundDisarmed;
}
wasArmed = armed;

return armed ? &groundFlight : &groundDisarmed;
}

static void terrainGroundPointUpdate(void)
{
terrainGroundPoint_t *point = terrainGroundPointInUse();

if (!ARMING_FLAG(ARMED) && posControl.flags.estPosStatus >= EST_USABLE) {
const fpVector3_t *pos = &navGetCurrentActualPositionAndVelocity()->pos;
gpsLocation_t here;
if (geoConvertLocalToGeodetic(&here, &posControl.gpsOrigin, pos)) {
point->located = true;
point->location = here;
point->altitudeCm = pos->z;
point->heightFound = false;
point->gpsUsable = STATE(GPS_FIX) && gpsSol.fixType == GPS_FIX_3D
&& gpsSol.epv < positionEstimationConfig()->max_eph_epv;
}
}

// In flight only a point whose block was not loaded at arming is still asked for
if (point->located && !point->heightFound) {
const float heightM = getHeightAmslMeters(&point->location);
if (heightM != TERRAIN_STATUS_NO_AMSL_DATA) {
point->heightFound = true;
point->heightM = heightM;
}
}
}

// The two readings of the height reference: from the map, and from the GPS altitude
static bool terrainReferenceReadings(float *mapM, bool *gpsUsable, float *gpsM)
{
const terrainGroundPoint_t *point = terrainGroundPointInUse();
if (!point->located || !point->heightFound) {
return false;
}

*mapM = point->heightM - point->altitudeCm * 0.01f;
*gpsUsable = point->gpsUsable && posControl.gpsOrigin.valid;
*gpsM = posControl.gpsOrigin.alt * 0.01f;
return true;
}

bool terrainGetReferenceHeightM(float *heightM)
{
float mapM;
float gpsM;
bool gpsUsable;
if (!terrainReferenceReadings(&mapM, &gpsUsable, &gpsM)) {
return false;
}

*heightM = (gpsUsable && gpsM < mapM) ? gpsM : mapM;
return true;
}

bool terrainReferenceReadingsDisagree(void)
{
float mapM;
float gpsM;
bool gpsUsable;
if (!terrainReferenceReadings(&mapM, &gpsUsable, &gpsM) || !gpsUsable) {
return false;
}

return fabsf(mapM - gpsM) > TERRAIN_REFERENCE_DISAGREE_M;
}

/**
* @brief Update the terrain subsystem.
*
* This function checks the status of the SD card and attempts to load terrain data into the cache.
* It also tries to determine the home altitude based on the GPS origin if it hasn't been found yet.
* It also keeps the height reference: the map height where the aircraft stands before it arms.
*/
void terrainUpdateTask(timeUs_t currentTimeUs)
{
Expand All @@ -154,39 +256,22 @@ void terrainUpdateTask(timeUs_t currentTimeUs)
return;
}

if(ARMING_FLAG(ARMED) && terrainHomePos.homeAltitudeFound == false){
//vehicle is armed and we don't have loaded values for home position, don't try load from SD card durting flight if we are not sure SD it's possible to load data
return;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////
//try to find home altitude to home offset
if(terrainHomePos.homeAltitudeFound == false && posControl.gpsOrigin.valid && (posControl.gpsOrigin.lat != terrainHomePos.homeLocation.lat || posControl.gpsOrigin.lon != terrainHomePos.homeLocation.lon)) {

gpsLocation_t homeLoc = {
.lat = posControl.gpsOrigin.lat,
.lon = posControl.gpsOrigin.lon,
};
terrainGroundPointUpdate();

float heightASLHome = getHeightAmslMeters(&homeLoc);

if(heightASLHome != TERRAIN_STATUS_NO_AMSL_DATA){
terrainHomePos.homeAltitudeFound = true;
terrainHomePos.homeAltitudeM = heightASLHome;
terrainHomePos.homeLocation.lat = posControl.gpsOrigin.lat;
terrainHomePos.homeLocation.lon = posControl.gpsOrigin.lon;
}
float referenceM;
if (ARMING_FLAG(ARMED) && !terrainGetReferenceHeightM(&referenceM)) {
// armed without a height reference: the block under the take-off point was not
// loaded. That point is still asked for above; nothing else is read from the card
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////////////////////
if(terrainHomePos.homeAltitudeFound)
if(terrainGetReferenceHeightM(&referenceM))
{
float heightASL = getHeightAmslMeters(&gpsSol.llh);
if(heightASL != TERRAIN_STATUS_NO_AMSL_DATA){
terrainHeight.terrainAMSL = (int32_t)(heightASL * 100.0f);
terrainHeight.terrainAGL = MAX(0, ((int32_t)getEstimatedActualPosition(Z) + (int32_t)(terrainHomePos.homeAltitudeM * 100.0f)) - terrainHeight.terrainAMSL);
terrainHeight.terrainAGL = MAX(0, ((int32_t)getEstimatedActualPosition(Z) + (int32_t)(referenceM * 100.0f)) - terrainHeight.terrainAMSL);
terrainHeight.lastUpdate = millis();
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/main/terrain/terrain.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

#define TERRAIN_TASK_RATE_HZ 5
#define TERRAIN_NO_DATA_DELAY_MS 1000
// The map and the GPS altitude are said to disagree about the take-off height beyond this
#define TERRAIN_REFERENCE_DISAGREE_M 5.0f

#define TERRAIN_TER_FILE_FORMAT_VERSION 50
#define TERRAIN_SPACING 30
Expand Down Expand Up @@ -166,4 +168,12 @@ int32_t terrainGetLastAMSL(void);
// TERRAIN_STATUS_NO_AMSL_DATA when the block is not loaded yet (a read gets scheduled)
float getHeightAmslMeters(const gpsLocation_t *loc);
int32_t terrainGetLastDistanceCm(void);
// The map height (m) that the navigation's altitude zero stands for: the map where the
// aircraft stood when it armed, less its altitude there, or the GPS altitude of the altitude
// zero when that is lower. False until the map has answered
bool terrainGetReferenceHeightM(float *heightM);
// True when the map and the GPS altitude put the take-off spot more than
// TERRAIN_REFERENCE_DISAGREE_M apart: the map is wrong there, the GPS altitude is, or the
// aircraft armed well above the mapped ground. The lower one is in use either way
bool terrainReferenceReadingsDisagree(void);

59 changes: 11 additions & 48 deletions src/main/terrain/terrain_nav.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,6 @@
// at 30 m cover ~1.9 km ahead, well beyond a practical climb-planning horizon
#define TERRAIN_NAV_LOOKAHEAD_MAX_SAMPLES 64

// Home terrain height, latched once the GPS origin is known and re-latched if
// the origin moves - the same relative datum the data layer uses for its own
// AGL, so map-datum errors cancel (docs: C-2)
static bool homeHeightValid;
static float homeHeightM;
static int32_t homeHeightLat;
static int32_t homeHeightLon;

static bool terrainNavUpdateHomeHeight(void)
{
if (!posControl.gpsOrigin.valid) {
homeHeightValid = false;
return false;
}
if (homeHeightValid && homeHeightLat == posControl.gpsOrigin.lat && homeHeightLon == posControl.gpsOrigin.lon) {
return true;
}
float heightM;
homeHeightValid = terrainNavGetHomeTerrainHeight(&heightM);
if (homeHeightValid) {
homeHeightM = heightM;
homeHeightLat = posControl.gpsOrigin.lat;
homeHeightLon = posControl.gpsOrigin.lon;
}
return homeHeightValid;
}

// The aircraft's position as the estimator sees it (not the raw GPS fix), so
// the layer follows whatever INAV trusts for position
static bool terrainNavCurrentLocation(gpsLocation_t *llh)
Expand All @@ -88,8 +61,10 @@ static bool terrainNavCurrentLocation(gpsLocation_t *llh)
}

// Healthy = terrain enabled, the SD reader alive, a usable position estimate
// and the home terrain height known. Per-sample data availability is answered
// by the height queries themselves (no data = block not loaded yet)
// and the height reference known (terrainGetReferenceHeightM: the same relative
// datum the data layer uses for its own AGL, so map-datum errors cancel).
// Per-sample data availability is answered by the height queries themselves
// (no data = block not loaded yet)
bool terrainNavIsHealthy(void)
{
if (!terrainConfig()->terrainEnabled || isTerrainIoFailure()) {
Expand All @@ -98,7 +73,8 @@ bool terrainNavIsHealthy(void)
if (posControl.flags.estPosStatus < EST_USABLE) {
return false;
}
return terrainNavUpdateHomeHeight();
float referenceM;
return terrainGetReferenceHeightM(&referenceM);
}

bool terrainNavGetAGLCm(int32_t *aglCm)
Expand All @@ -109,13 +85,15 @@ bool terrainNavGetAGLCm(int32_t *aglCm)

gpsLocation_t here;
float heightHereM;
if (!terrainNavCurrentLocation(&here) || !terrainNavGetHeightAtLocation(&here, &heightHereM)) {
float referenceM;
if (!terrainNavCurrentLocation(&here) || !terrainNavGetHeightAtLocation(&here, &heightHereM)
|| !terrainGetReferenceHeightM(&referenceM)) {
return false;
}

// AGL = estimated altitude above home minus the terrain rise above home
// AGL = estimated altitude minus the terrain's rise above the height reference
const int32_t agl = (int32_t)navGetCurrentActualPositionAndVelocity()->pos.z
- (int32_t)((heightHereM - homeHeightM) * 100.0f);
- (int32_t)((heightHereM - referenceM) * 100.0f);
*aglCm = MAX(0, agl);
return true;
}
Expand All @@ -137,21 +115,6 @@ bool terrainNavGetHeightAtLocation(const gpsLocation_t *loc, float *heightM)
return true;
}

bool terrainNavGetHomeTerrainHeight(float *heightM)
{
if (!posControl.gpsOrigin.valid) {
return false;
}

const gpsLocation_t homeLoc = {
.lat = posControl.gpsOrigin.lat,
.lon = posControl.gpsOrigin.lon,
.alt = 0,
};

return terrainNavGetHeightAtLocation(&homeLoc, heightM);
}

bool terrainNavLookahead(float bearingDeg, float distanceM, float climbRatio, float escapeRatio, terrainNavLookaheadResult_t *result)
{
if (result == NULL || !terrainNavIsHealthy()) {
Expand Down
3 changes: 0 additions & 3 deletions src/main/terrain/terrain_nav.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,6 @@ bool terrainNavGetAGLCm(int32_t *aglCm);
// miss the block is scheduled for loading and the call fails - retry later.
bool terrainNavGetHeightAtLocation(const gpsLocation_t *loc, float *heightM);

// Terrain height (map datum, meters) at the GPS origin (home)
bool terrainNavGetHomeTerrainHeight(float *heightM);

// Walk the map from the current position along bearingDeg for distanceM,
// accumulating achievable climb (climbRatio = m of climb per m travelled),
// and report the worst height deficit found. A descending path (negative
Expand Down
Loading