Skip to content

UEMapServe Interface Documentation

Introduction

Overview: This file provides the UEMapServe class for interfacing with Unreal Engine map services, enabling communication and interaction between the RflySim simulation environment and Unreal Engine’s high-definition terrain maps.

This module serves as the core interactive component of the RflySimSDK for connecting to the Unreal Engine simulation environment. It primarily supports visualization of 3D map environments for drone simulation missions. It handles the invocation of map resources on the Unreal Engine side, synchronization of simulation states, and supports developers in RflySim to utilize high-precision geographic maps and custom scene maps generated by Unreal Engine. It is suitable for simulation development scenarios requiring high-definition visual 3D environments, such as large-scale terrain inspection and urban drone mission simulation. It decouples simulation computation logic from realistic visual rendering, ensuring simulation runtime efficiency while delivering high-quality visual simulation effects.

Quick Start

Minimal working example; copy and modify minimal configuration to run.

import sys
import os
from RflySimSDK.ue import UEMapServe

if __name__ == "__main__":
    # Initialize UE map service, passing in the map name to load (without extension; example uses default map "example")
    map_serve = UEMapServe(name="example")
    # Load PNG elevation map data; automatically locates file path
    elev_array, map_info = map_serve.LoadPngData(name="example")

    # Print map information for verification
    print("Map extent info:", map_info)
    print("Elevation data shape:", elev_array.shape)
    print("Loading completed; use elev_array for subsequent tasks such as path planning")

Environment and Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: copy, cv2, numpy, os, socket, struct, sys, threading, time
  • Prerequisites: Before calling this interface, ensure the UE simulation environment is ready and RflySimSDK has been initialized.

Core Interface Description

The module UEMapServe.py includes configuration variables, helper functions, and the core business class.

Global Constants and Enumerations

This section lists all globally accessible constants and enumerations defined in the module.

Standalone Constants

None


Global/Standalone Functions

None


UEMapServe Class

Used to load and parse terrain elevation data from the Unreal Engine simulation environment. Supports querying terrain height at specified coordinates and generating full terrain point data. Commonly used in drone terrain simulation and path planning scenarios.


__init__(name="")

Function Description: Initializes an instance of the UEMapServe map service class.
Arguments (Args):

Parameter Name Type Required Default Description
name str No "" Prefix of the terrain data file name to load (excluding file extension)

Return Value (Returns):

  • UEMapServe instance object

Exceptions (Raises):

  • None

LoadPngData(name)

Function Description: Loads and parses the specified terrain PNG elevation data and parameter configuration file. Automatically searches the current working directory and the default PX4PSP terrain directory, computes coordinate scaling and offset parameters, and stores results as class attributes.
Arguments (Args):

Parameter Name Type Required Default Description
name str Yes Prefix of the terrain data file name (excluding .png/.txt extensions)

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

Example:

from RflySimSDK.ue import UEMapServe
map_serve = UEMapServe()
# Load terrain data named "terrain_sample"
map_serve.LoadPngData("terrain_sample")

getTerrainAltData(xin, yin)

Function Description: Computes the terrain height at the given planar coordinates using bilinear interpolation.
Arguments (Args):

Parameter Name Type Required Default Description
xin float Yes X-coordinate (in meters) of the query point
yin float Yes Y-coordinate (in meters) of the query point

Return Value (Returns):

  • float: Terrain height (in meters) corresponding to the input coordinates

Exceptions (Raises):

  • None

Example:

# Query terrain altitude at coordinate (10, 20)
altitude = map_serve.getTerrainAltData(10, 20)
print(f"Terrain altitude at (10, 20): {altitude} meters")

outTerrainPoint()

Function Description: Iterates through all grid cells of the entire terrain mesh, computes the actual coordinates and terrain height for each cell, and generates a list containing all terrain point coordinates and heights.
Arguments (Args):
None
Return Value (Returns):

  • list[tuple[float, float, float]]: List of all terrain points; each element is an (x, y, h) tuple, where x and y are planar coordinates and h is terrain height.

Exceptions (Raises):

  • None

Example:

# Retrieve coordinates and altitude data for all terrain points
terrain_points = map_serve.outTerrainPoint()

---

## Advanced Usage Examples

> Demonstrates complex composite scenarios (e.g., multi-class collaboration, asynchronous control, batch operations)

```python
import RflySimSDK.ue as rfly_ue
import numpy as np
from concurrent.futures import ThreadPoolExecutor

# Advanced scenario: batch extraction of elevation points across multiple regions—terrain sampling for aerial survey coverage planning
map_server = rfly_ue.UEMapServe()
# Load high-resolution terrain PNG elevation data
map_server.LoadPngData("terrain_highres.png")

# Define batch sampling function for multiple regions
def batch_sample_region(region_bounds):
    lon_min, lon_max, lat_min, lat_max, grid_size = region_bounds
    # Generate a uniform sampling grid
    lon_grid = np.linspace(lon_min, lon_max, grid_size)
    lat_grid = np.linspace(lat_min, lat_max, grid_size)
    region_alt = []
    for lon in lon_grid:
        for lat in lat_grid:
            alt = map_server.outTerrainPoint(lon, lat)
            region_alt.append((lon, lat, alt))
    # Retrieve terrain relief statistics for the region
    _, mean_alt, std_alt = map_server.getTerrainAltData(lon_min, lon_max, lat_min, lat_max)
    return {"region_bounds": region_bounds, "samples": region_alt, "mean_alt": mean_alt, "std_alt": std_alt}

# Asynchronous processing across regions to enhance terrain sampling efficiency in large-scale scenarios
task_regions = [
    (116.0, 116.2, 40.0, 40.2, 50),
    (116.2, 116.4, 40.0, 40.2, 50),
    (116.0, 116.2, 40.2, 40.4, 50),
    (116.2, 116.4, 40.2, 40.4, 50)
]

with ThreadPoolExecutor(max_workers=4) as executor:
    all_region_result = list(executor.map(batch_sample_region, task_regions))

# Merge all region results for subsequent trajectory planning and terrain adaptation
print(f"Completed terrain sampling for {len(all_region_result)} regions; maximum terrain standard deviation: {max([res['std_alt'] for res in all_region_result])}")

Notes and Pitfall Avoidance Guide

  • Elevation PNG Coordinate System Compatibility: The elevation PNG loaded via LoadPngData must match the geographic coordinate system of the current simulation scene. If a coordinate system other than WGS84 is used, coordinate transformation must be performed beforehand; otherwise, elevation values extracted via outTerrainPoint will exhibit systematic offsets.
  • Boundary Coordinate Parameter Range: When calling getTerrainAltData, ensure the input longitude and latitude range falls within the valid geographic extent corresponding to the loaded PNG. If the input range exceeds the boundary, erroneous default elevation values will be returned; thus, input boundaries should be clipped in advance.
  • Thread Safety in Batch Operations: The UEMapServe object itself does not support concurrent modification of its internal elevation cache. During multithreaded batch sampling, only read-only methods such as outTerrainPoint and getTerrainAltData may be invoked; methods like LoadPngData, which modify internal state, must not be called concurrently.
  • Performance Optimization for Large PNGs: Loading elevation PNGs exceeding 4K resolution consumes significant memory. If only single-point elevation extraction is required, consider downsampling the PNG in advance to avoid unnecessary memory overhead.

Changelog

  • 2025-08-07: fix: Resolve Python 3.12 compatibility issue
  • 2024-09-06: fix: Update API
  • 2024-08-29: fix: Update API documentation page
  • 2024-08-29: fix: Add automatic retrieval of Map path for CopterSim
  • 2024-06-13: fix: Update example index
  • 2024-06-12: fix: Update interface comments
  • 2024-06-04: fix: Update interface comments
  • 2024-03-22: fix: Add outTerrainPoint interface
  • 2023-11-15: fix: Fix UEMapServe library file
  • 2023-10-24: feat: Refactor common library folder