STDP-Dataset / simulation /plugins /SimpleDronePlugin.cc
bfz111's picture
Add reproducible Gazebo simulation environment and English setup documentation
e5f58d9 verified
Raw History Blame Contribute Delete
62.8 kB
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>
#include <gazebo/common/Image.hh>
#include <gazebo/sensors/sensors.hh>
#include <gazebo/sensors/CameraSensor.hh>
#include <gazebo/rendering/Camera.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/math/Pose3.hh>
#include <boost/filesystem.hpp>
#include <vector>
#include <string>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <functional>
#include <sstream>
#include <ctime>
#include <algorithm>
#include <iomanip>
#include <mutex>
#include <cctype>
namespace gazebo
{
class SimpleDronePlugin : public ModelPlugin
{
struct CachedFrame
{
std::vector<unsigned char> data;
unsigned int width = 0;
unsigned int height = 0;
unsigned int depth = 0;
std::string format;
common::Time time;
};
public:
void Load(physics::ModelPtr model, sdf::ElementPtr sdf) override
{
this->model = model;
this->world = model->GetWorld();
this->speed = 0.6;
if (sdf->HasElement("speed"))
this->speed = sdf->Get<double>("speed");
// Where to save the captured RGB frames. The run script sets this env var
// so the model can be reused without hardcoded project paths.
const char *envImageDir = std::getenv("SIMPLE_DRONE_IMAGE_DIR");
if (envImageDir && envImageDir[0] != '\0')
{
this->imageDir = envImageDir;
}
else if (sdf->HasElement("image_dir"))
{
this->imageDir = sdf->Get<std::string>("image_dir");
}
else
{
this->imageDir = "drone_images";
}
// (Legacy <capture_period> is ignored: frames are now captured once per
// waypoint, on arrival, rather than on a fixed time interval.)
this->capturePeriod = 1.0;
if (sdf->HasElement("capture_period"))
this->capturePeriod = sdf->Get<double>("capture_period");
this->datasetMode = false;
this->quitOnFinish = false;
this->rejectGrayImages = true;
this->grayDelta = this->EnvInt("SIMPLE_DRONE_GRAY_DELTA", 3);
this->grayMin = this->EnvInt("SIMPLE_DRONE_GRAY_MIN", 120);
this->grayMax = this->EnvInt("SIMPLE_DRONE_GRAY_MAX", 136);
this->grayMaxRatio = std::min(
0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_MAX_RATIO", 0.12)));
this->grayTileRatio = std::min(
0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_TILE_RATIO", 0.90)));
this->grayScanlineRatio = std::min(
0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_SCANLINE_RATIO", 0.95)));
this->minLumaStd = this->EnvDouble("SIMPLE_DRONE_MIN_LUMA_STD", 4.0);
this->minRgbRange = this->EnvInt("SIMPLE_DRONE_MIN_RGB_RANGE", 12);
this->viewDownTilt = this->EnvDouble("SIMPLE_DRONE_VIEW_DOWN_TILT", 0.55);
this->minValidImageRatio =
this->EnvDouble("SIMPLE_DRONE_MIN_VALID_IMAGE_RATIO", 0.001);
const char *envRejectGrayImages = std::getenv("SIMPLE_DRONE_REJECT_GRAY_IMAGES");
if (envRejectGrayImages && std::string(envRejectGrayImages) == "0")
this->rejectGrayImages = false;
const char *envQuitOnFinish = std::getenv("SIMPLE_DRONE_QUIT_ON_FINISH");
if (envQuitOnFinish && envQuitOnFinish[0] != '\0' &&
std::string(envQuitOnFinish) != "0")
this->quitOnFinish = true;
const char *envDoneFile = std::getenv("SIMPLE_DRONE_DONE_FILE");
if (envDoneFile && envDoneFile[0] != '\0')
this->doneFile = envDoneFile;
const char *envDatasetRoot = std::getenv("SIMPLE_DRONE_DATASET_ROOT");
if (envDatasetRoot && envDatasetRoot[0] != '\0')
{
this->datasetRoot = envDatasetRoot;
this->datasetMode = true;
}
const char *envDatasetTrajectoryFile =
std::getenv("SIMPLE_DRONE_DATASET_TRAJECTORY_FILE");
if (envDatasetTrajectoryFile && envDatasetTrajectoryFile[0] != '\0')
this->datasetTrajectoryFile = envDatasetTrajectoryFile;
// The four viewpoints we want to read. The names must match the
// <sensor> names declared in the model SDF.
this->cameraNames = {"cam_front", "cam_down", "cam_left", "cam_right"};
// Output sub-folder for each viewpoint (decoupled from the sensor name,
// so e.g. cam_front is saved under <image_dir>/front/).
this->folderNames = this->datasetMode
? std::vector<std::string>{"images_front", "images_down", "images_left", "images_right"}
: std::vector<std::string>{"front", "down", "left", "right"};
this->cameras.resize(this->cameraNames.size());
this->imageConnections.resize(this->cameraNames.size());
this->latestFrames.resize(this->cameraNames.size());
if (this->datasetMode)
{
boost::filesystem::create_directories(this->imageDir);
gzmsg << "[SimpleDronePlugin] saving dataset RGB frames under: "
<< this->imageDir
<< "/<trajectory>/{images_front,images_down,images_left,images_right}/"
<< std::endl;
}
else
{
// Each viewpoint gets its own sub-folder, e.g. <image_dir>/front/.
for (const std::string &name : this->folderNames)
boost::filesystem::create_directories(this->imageDir + "/" + name);
gzmsg << "[SimpleDronePlugin] saving RGB frames under: "
<< this->imageDir << "/{" ;
for (size_t i = 0; i < this->folderNames.size(); ++i)
gzmsg << this->folderNames[i]
<< (i + 1 < this->folderNames.size() ? "," : "}/\n");
}
if (!this->datasetMode)
{
// Trajectory log: one row per saved frame set (one per waypoint). The
// `frame` column matches both the image filename and the waypoint index,
// e.g. frame 5 <-> front/000005.png <-> waypoints[5].
const std::string trajPath = this->imageDir + "/trajectory.csv";
this->trajFile.open(trajPath, std::ios::out | std::ios::trunc);
this->trajFile << "frame,sim_time,x,y,z,"
"roll_rad,pitch_rad,yaw_rad,roll_deg,pitch_deg,yaw_deg,"
"qw,qx,qy,qz\n";
gzmsg << "[SimpleDronePlugin] saving trajectory to: " << trajPath << std::endl;
}
if (this->rejectGrayImages)
{
gzmsg << "[SimpleDronePlugin] gray-frame rejection enabled: "
<< "gray_delta=" << this->grayDelta
<< ", gray_range=[" << this->grayMin << ',' << this->grayMax << ']'
<< ", max_gray_ratio=" << this->grayMaxRatio
<< ", max_gray_tile_ratio=" << this->grayTileRatio
<< ", max_gray_scanline_ratio=" << this->grayScanlineRatio
<< ", min_luma_std=" << this->minLumaStd
<< ", min_rgb_range=" << this->minRgbRange
<< std::endl;
}
this->camerasReady = false;
this->frameCounter = 0;
this->commandMode = false;
this->waitingForCommand = false;
this->commandYaw = 0.0;
const char *envCommandFile = std::getenv("SIMPLE_DRONE_COMMAND_FILE");
if (envCommandFile && envCommandFile[0] != '\0')
{
this->commandFile = envCommandFile;
this->commandMode = true;
}
else if (sdf->HasElement("command_file"))
{
this->commandFile = sdf->Get<std::string>("command_file");
this->commandMode = !this->commandFile.empty();
}
this->lastCommandMTime = 0;
if (this->commandMode)
{
if (boost::filesystem::exists(this->commandFile))
{
this->lastCommandMTime = boost::filesystem::last_write_time(this->commandFile);
std::ifstream existing(this->commandFile);
std::ostringstream buf;
buf << existing.rdbuf();
this->lastCommandText = buf.str();
}
gzmsg << "[SimpleDronePlugin] command mode enabled; waiting for: "
<< this->commandFile << std::endl;
}
// Capture happens once per waypoint. Begin in the "settling" state on
// waypoints[0] (the takeoff/start point): the drone is pinned to the exact
// waypoint and we wait for the cameras to render a fresh frame from that
// pose before saving, so the first image+row are the start point and every
// saved image corresponds to its logged coordinate (not one render earlier).
this->settling = true;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
this->captureYaw = 0.0;
this->grayRejectWarnCounter = 0;
this->sweepInProgress = false;
this->sweepPoseSet = false;
this->sweepViewIndex = 0;
this->sweepYawAttempt = 0;
this->sweepTimeoutWarned = false;
this->physicalSequenceInProgress = false;
this->physicalViewIndex = 0;
this->physicalWarned = false;
this->physicalViewArmed = false;
this->physicalBaselineTime = common::Time::Zero;
this->physicalRejectCount = 0;
this->physicalFallbackToSweep = false;
this->returningToStart = false;
this->currentDatasetTrajectory = 0;
if (this->datasetMode)
{
this->trajectoryDir = this->datasetRoot + "/trajectory";
this->LoadDatasetTrajectories();
}
// Tour of the whole 15x10 apartment. Safe envelope: x in [-6.5,6.5],
// y in [-4,4], z in [1.2,1.8] (clear of walls, furniture and ceiling).
// Order: center -> dining -> living -> TV/kitchen front -> bedroom -> back.
if (this->datasetMode)
{
if (!this->BeginDatasetTrajectory(0))
{
gzerr << "[SimpleDronePlugin] no dataset trajectories loaded from "
<< this->trajectoryDir << std::endl;
}
}
else
{
this->waypoints.push_back(ignition::math::Vector3d(-7.0, 0.6, 1.8)); // takeoff: clear strip on left wall, yaw=0 (+x), overview of whole apartment
}
if (!this->commandMode && !this->datasetMode)
{
this->waypoints.push_back(ignition::math::Vector3d(-4.5, -3.0, 1.6)); // dining area
this->waypoints.push_back(ignition::math::Vector3d(-5.8, 0.0, 1.4)); // living-room corner
this->waypoints.push_back(ignition::math::Vector3d(-4.4, 3.3, 1.7)); // sofa / TV wall
this->waypoints.push_back(ignition::math::Vector3d( 0.0, 3.5, 1.5)); // sweep along front wall
this->waypoints.push_back(ignition::math::Vector3d( 4.0, 3.3, 1.4)); // kitchen
this->waypoints.push_back(ignition::math::Vector3d( 5.8, 0.0, 1.6)); // toward bedroom
this->waypoints.push_back(ignition::math::Vector3d( 4.8, -3.0, 1.7)); // bed / wardrobe
this->waypoints.push_back(ignition::math::Vector3d( 0.0, -3.5, 1.5)); // back wall windows
this->waypoints.push_back(ignition::math::Vector3d( 0.0, 0.0, 1.3)); // back to center
}
this->targetIndex = 0;
this->tourComplete = false;
this->lastTime = this->world->SimTime();
this->updateConnection = event::Events::ConnectWorldUpdateBegin(
std::bind(&SimpleDronePlugin::OnUpdate, this));
}
private:
// Look up the four camera sensors by name. Sensors are created after the
// model is loaded, so this is retried each update until all are found.
bool InitCameras()
{
sensors::SensorManager *mgr = sensors::SensorManager::Instance();
if (!mgr || !mgr->SensorsInitialized())
return false;
bool allFound = true;
for (size_t i = 0; i < this->cameraNames.size(); ++i)
{
if (this->cameras[i])
continue;
sensors::SensorPtr s = mgr->GetSensor(this->cameraNames[i]);
sensors::CameraSensorPtr cam =
std::dynamic_pointer_cast<sensors::CameraSensor>(s);
if (cam)
{
cam->SetActive(true);
// Make sure the rendering camera keeps a CPU-side copy of the frame
// so we can read the RGB bytes / save them.
if (cam->Camera())
{
cam->Camera()->SetCaptureData(true);
this->imageConnections[i] = cam->Camera()->ConnectNewImageFrame(
[this, i](const unsigned char *image,
unsigned int width,
unsigned int height,
unsigned int depth,
const std::string &format)
{
if (!image || width == 0 || height == 0 || depth == 0)
return;
CachedFrame frame;
frame.width = width;
frame.height = height;
frame.depth = depth;
frame.format = format;
frame.time = this->world ? this->world->SimTime() : common::Time::Zero;
const size_t bytes =
static_cast<size_t>(width) * static_cast<size_t>(height) * depth;
frame.data.assign(image, image + bytes);
std::lock_guard<std::mutex> lock(this->frameMutex);
if (i < this->latestFrames.size())
this->latestFrames[i] = std::move(frame);
});
}
cam->Update(true);
this->cameras[i] = cam;
}
else
{
allFound = false;
}
}
return allFound;
}
ignition::math::Vector3d RotateYaw(
const ignition::math::Vector3d &v,
const double yaw) const
{
const double c = std::cos(yaw);
const double s = std::sin(yaw);
return ignition::math::Vector3d(
c * v.X() - s * v.Y(),
s * v.X() + c * v.Y(),
v.Z());
}
ignition::math::Pose3d ViewPose(
const ignition::math::Pose3d &base,
const size_t viewIndex) const
{
const ignition::math::Vector3d &p = base.Pos();
const double yaw = base.Rot().Yaw();
ignition::math::Vector3d offset;
double roll = this->viewDownTilt;
double pitch = 0.0;
double viewYaw = yaw;
if (viewIndex == 0) // front
{
offset = this->RotateYaw(ignition::math::Vector3d(0.62, 0.0, 0.0), yaw);
viewYaw = yaw;
}
else if (viewIndex == 1) // down
{
offset = ignition::math::Vector3d(0.0, 0.0, -0.35);
pitch = ignition::math::Angle::HalfPi.Radian();
viewYaw = yaw;
}
else if (viewIndex == 2) // left
{
offset = this->RotateYaw(ignition::math::Vector3d(0.0, 0.62, 0.0), yaw);
viewYaw = yaw + ignition::math::Angle::HalfPi.Radian();
}
else // right
{
offset = this->RotateYaw(ignition::math::Vector3d(0.0, -0.62, 0.0), yaw);
viewYaw = yaw - ignition::math::Angle::HalfPi.Radian();
}
return ignition::math::Pose3d(
p.X() + offset.X(),
p.Y() + offset.Y(),
p.Z() + offset.Z(),
roll,
pitch,
viewYaw);
}
ignition::math::Pose3d SweepModelPose(
const ignition::math::Pose3d &base,
const size_t viewIndex,
const double yawOffset = 0.0) const
{
const ignition::math::Vector3d &p = base.Pos();
const double yaw = base.Rot().Yaw();
double roll = 0.0;
double pitch = 0.0;
double viewYaw = yaw;
// cam_right looks along the model's right side. Rotate the model in place
// so that one known-good physical camera provides all required views.
if (viewIndex == 0) // front
viewYaw = yaw + ignition::math::Angle::HalfPi.Radian();
else if (viewIndex == 1) // down
roll = ignition::math::Angle::HalfPi.Radian();
else if (viewIndex == 2) // left
viewYaw = yaw + M_PI;
else // right
viewYaw = yaw;
viewYaw += yawOffset;
return ignition::math::Pose3d(
p.X(), p.Y(), p.Z(),
roll, pitch, viewYaw);
}
bool RenderViewFrames(
const ignition::math::Pose3d &basePose,
std::vector<CachedFrame> &frames)
{
if (this->cameras.empty())
return false;
// Use cam_right as the capture source. On the target machine this is the
// only physical camera that consistently produces scene pixels; rotating
// the model in place is stable, while moving the Ogre camera directly can
// segfault in gzserver.
const size_t sourceIndex = std::min<size_t>(3u, this->cameras.size() - 1u);
sensors::CameraSensorPtr sensor = this->cameras[sourceIndex];
if (!sensor || !sensor->Camera())
return false;
rendering::CameraPtr renderCam = sensor->Camera();
renderCam->SetCaptureData(true);
sensor->SetActive(true);
frames.assign(this->cameraNames.size(), CachedFrame());
for (size_t i = 0; i < this->cameraNames.size(); ++i)
{
const ignition::math::Pose3d pose = this->SweepModelPose(basePose, i);
this->model->SetWorldPose(pose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
sensor->Update(true);
const unsigned char *data = renderCam->ImageData();
const unsigned int width = renderCam->ImageWidth();
const unsigned int height = renderCam->ImageHeight();
const unsigned int depth = renderCam->ImageDepth();
if (!data || width == 0 || height == 0 || depth < 3)
{
if (!this->captureFailureWarned)
{
gzerr << "[SimpleDronePlugin] movable render camera not ready for "
<< this->cameraNames[i]
<< "; width=" << width
<< ", height=" << height
<< ", depth=" << depth << std::endl;
this->captureFailureWarned = true;
}
return false;
}
CachedFrame frame;
frame.width = width;
frame.height = height;
frame.depth = depth;
frame.format = renderCam->ImageFormat();
frame.time = this->world ? this->world->SimTime() : common::Time::Zero;
const size_t bytes =
static_cast<size_t>(width) * static_cast<size_t>(height) * depth;
frame.data.assign(data, data + bytes);
frames[i] = std::move(frame);
}
this->model->SetWorldPose(basePose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
return true;
}
void ResetSingleCameraSweep()
{
if (this->sweepInProgress)
{
this->model->SetWorldPose(this->sweepBasePose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
}
this->sweepInProgress = false;
this->sweepPoseSet = false;
this->sweepViewIndex = 0;
this->sweepYawAttempt = 0;
this->sweepFrames.clear();
this->sweepTimeoutWarned = false;
}
bool CropGrayBackground(CachedFrame &frame) const
{
if (frame.data.empty() || frame.width == 0 || frame.height == 0 ||
frame.depth != 3)
return false;
unsigned int minX = frame.width;
unsigned int minY = frame.height;
unsigned int maxX = 0;
unsigned int maxY = 0;
size_t validPixels = 0;
for (unsigned int y = 0; y < frame.height; ++y)
{
for (unsigned int x = 0; x < frame.width; ++x)
{
const size_t offset =
(static_cast<size_t>(y) * frame.width + x) * frame.depth;
const bool isGazeboGray =
frame.data[offset] == 128 &&
frame.data[offset + 1] == 128 &&
frame.data[offset + 2] == 128;
if (!isGazeboGray)
{
minX = std::min(minX, x);
minY = std::min(minY, y);
maxX = std::max(maxX, x);
maxY = std::max(maxY, y);
++validPixels;
}
}
}
const size_t totalPixels =
static_cast<size_t>(frame.width) * static_cast<size_t>(frame.height);
const double validRatio =
static_cast<double>(validPixels) / std::max<size_t>(totalPixels, 1u);
if (validRatio < this->minValidImageRatio || minX > maxX || minY > maxY)
return false;
const unsigned int margin = 4;
minX = minX > margin ? minX - margin : 0;
minY = minY > margin ? minY - margin : 0;
maxX = std::min(frame.width - 1, maxX + margin);
maxY = std::min(frame.height - 1, maxY + margin);
const unsigned int cropW = maxX - minX + 1;
const unsigned int cropH = maxY - minY + 1;
if (cropW < 4 || cropH < 4)
return false;
std::vector<unsigned char> resized(
static_cast<size_t>(frame.width) * frame.height * 3u);
for (unsigned int y = 0; y < frame.height; ++y)
{
const unsigned int srcY =
minY + std::min(cropH - 1,
static_cast<unsigned int>(
(static_cast<unsigned long long>(y) * cropH) /
frame.height));
for (unsigned int x = 0; x < frame.width; ++x)
{
const unsigned int srcX =
minX + std::min(cropW - 1,
static_cast<unsigned int>(
(static_cast<unsigned long long>(x) * cropW) /
frame.width));
const size_t src =
(static_cast<size_t>(srcY) * frame.width + srcX) * 3u;
const size_t dst =
(static_cast<size_t>(y) * frame.width + x) * 3u;
resized[dst] = frame.data[src];
resized[dst + 1] = frame.data[src + 1];
resized[dst + 2] = frame.data[src + 2];
}
}
unsigned long long sumR = 0;
unsigned long long sumG = 0;
unsigned long long sumB = 0;
size_t fillSourcePixels = 0;
for (size_t i = 0; i + 2 < resized.size(); i += 3)
{
const bool isGazeboGray =
resized[i] == 128 && resized[i + 1] == 128 && resized[i + 2] == 128;
if (!isGazeboGray)
{
sumR += resized[i];
sumG += resized[i + 1];
sumB += resized[i + 2];
++fillSourcePixels;
}
}
if (fillSourcePixels == 0)
return false;
const unsigned char fillR =
static_cast<unsigned char>(sumR / fillSourcePixels);
const unsigned char fillG =
static_cast<unsigned char>(sumG / fillSourcePixels);
const unsigned char fillB =
static_cast<unsigned char>(sumB / fillSourcePixels);
for (size_t i = 0; i + 2 < resized.size(); i += 3)
{
const bool isGazeboGray =
resized[i] == 128 && resized[i + 1] == 128 && resized[i + 2] == 128;
if (isGazeboGray)
{
resized[i] = fillR;
resized[i + 1] = fillG;
resized[i + 2] = fillB;
}
}
frame.data.swap(resized);
return true;
}
bool NormalizeFrameToRgb(
const CachedFrame &src,
CachedFrame &dst) const
{
if (src.data.empty() || src.width == 0 || src.height == 0 || src.depth < 3)
return false;
std::string format = src.format;
std::transform(format.begin(), format.end(), format.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
const bool bgr =
format.find("b8g8r8") != std::string::npos ||
format.find("bgr") != std::string::npos;
const size_t pixelCount =
static_cast<size_t>(src.width) * static_cast<size_t>(src.height);
dst.data.resize(pixelCount * 3u);
dst.width = src.width;
dst.height = src.height;
dst.depth = 3;
dst.format = "R8G8B8";
dst.time = src.time;
for (size_t i = 0; i < pixelCount; ++i)
{
const size_t in = i * src.depth;
const size_t out = i * 3u;
if (bgr)
{
dst.data[out] = src.data[in + 2];
dst.data[out + 1] = src.data[in + 1];
dst.data[out + 2] = src.data[in];
}
else
{
dst.data[out] = src.data[in];
dst.data[out + 1] = src.data[in + 1];
dst.data[out + 2] = src.data[in + 2];
}
}
return true;
}
bool AdvanceSingleCameraSweep(std::vector<CachedFrame> &frames)
{
if (this->cameras.empty())
return false;
const size_t sourceIndex = std::min<size_t>(3u, this->cameras.size() - 1u);
sensors::CameraSensorPtr sensor = this->cameras[sourceIndex];
if (!sensor || !sensor->Camera())
return false;
if (!this->sweepInProgress)
{
this->sweepBasePose = this->model->WorldPose();
this->sweepFrames.assign(this->cameraNames.size(), CachedFrame());
this->sweepViewIndex = 0;
this->sweepPoseSet = false;
this->sweepInProgress = true;
this->sweepStartTime = this->world ? this->world->SimTime() : common::Time::Zero;
this->sweepTimeoutWarned = false;
}
if (this->sweepViewIndex >= this->cameraNames.size())
{
frames = this->sweepFrames;
this->ResetSingleCameraSweep();
return true;
}
sensor->SetActive(true);
sensor->Camera()->SetCaptureData(true);
const double yawOffset =
static_cast<double>(this->sweepYawAttempt) *
ignition::math::Angle::HalfPi.Radian() * 0.5;
const ignition::math::Pose3d pose =
this->SweepModelPose(this->sweepBasePose, this->sweepViewIndex, yawOffset);
this->model->SetWorldPose(pose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
if (!this->sweepPoseSet)
{
{
std::lock_guard<std::mutex> lock(this->frameMutex);
this->sweepBaselineFrameTime =
sourceIndex < this->latestFrames.size()
? this->latestFrames[sourceIndex].time
: common::Time::Zero;
}
sensor->Update(true);
this->sweepPoseSet = true;
return false;
}
sensor->Update(true);
CachedFrame sourceFrame;
{
std::lock_guard<std::mutex> lock(this->frameMutex);
if (sourceIndex < this->latestFrames.size())
sourceFrame = this->latestFrames[sourceIndex];
}
if (sourceFrame.data.empty() ||
sourceFrame.time <= this->sweepBaselineFrameTime)
{
const common::Time now = this->world ? this->world->SimTime() : common::Time::Zero;
const double wait = (now - this->sweepStartTime).Double();
if (wait > this->settleTimeout && !this->sweepTimeoutWarned)
{
gzerr << "[SimpleDronePlugin] camera sweep timeout at target index "
<< this->targetIndex << "; view=" << this->cameraNames[this->sweepViewIndex]
<< ". Waiting for a fresh frame." << std::endl;
this->sweepTimeoutWarned = true;
}
return false;
}
CachedFrame rgbFrame;
if (!this->NormalizeFrameToRgb(sourceFrame, rgbFrame))
return false;
if (!this->CropGrayBackground(rgbFrame))
{
++this->sweepYawAttempt;
this->sweepPoseSet = false;
if (this->sweepYawAttempt <= 8)
return false;
gzerr << "[SimpleDronePlugin] unable to find non-gray content at target index "
<< this->targetIndex << "; view="
<< this->cameraNames[this->sweepViewIndex] << std::endl;
this->sweepYawAttempt = 0;
return false;
}
this->sweepFrames[this->sweepViewIndex] = std::move(rgbFrame);
++this->sweepViewIndex;
this->sweepYawAttempt = 0;
this->sweepPoseSet = false;
if (this->sweepViewIndex < this->cameraNames.size())
return false;
frames = this->sweepFrames;
this->ResetSingleCameraSweep();
return true;
}
bool ReadPhysicalCameraFrames(std::vector<CachedFrame> &frames)
{
std::lock_guard<std::mutex> lock(this->frameMutex);
frames = this->latestFrames;
return frames.size() == this->cameraNames.size();
}
void ResetPhysicalCameraSequence()
{
this->physicalSequenceInProgress = false;
this->physicalViewIndex = 0;
this->physicalWarned = false;
this->physicalViewArmed = false;
this->physicalBaselineTime = common::Time::Zero;
this->physicalFrames.clear();
}
bool AdvancePhysicalCameraSequence(std::vector<CachedFrame> &frames)
{
if (!this->physicalSequenceInProgress)
{
this->physicalSequenceInProgress = true;
this->physicalViewIndex = 0;
this->physicalWarned = false;
this->physicalViewArmed = false;
this->physicalBaselineTime = common::Time::Zero;
this->physicalFrames.assign(this->cameraNames.size(), CachedFrame());
}
if (this->physicalViewIndex >= this->cameraNames.size())
{
frames = this->physicalFrames;
this->ResetPhysicalCameraSequence();
return true;
}
for (size_t i = 0; i < this->cameras.size(); ++i)
{
if (!this->cameras[i])
continue;
this->cameras[i]->SetActive(i == this->physicalViewIndex);
if (this->cameras[i]->Camera())
this->cameras[i]->Camera()->SetCaptureData(i == this->physicalViewIndex);
if (i == this->physicalViewIndex)
this->cameras[i]->Update(true);
}
if (!this->physicalViewArmed)
{
std::lock_guard<std::mutex> lock(this->frameMutex);
if (this->physicalViewIndex < this->latestFrames.size())
this->physicalBaselineTime = this->latestFrames[this->physicalViewIndex].time;
else
this->physicalBaselineTime = common::Time::Zero;
this->physicalViewArmed = true;
return false;
}
CachedFrame candidate;
{
std::lock_guard<std::mutex> lock(this->frameMutex);
if (this->physicalViewIndex >= this->latestFrames.size())
return false;
candidate = this->latestFrames[this->physicalViewIndex];
}
if (candidate.time <= this->physicalBaselineTime)
return false;
if (candidate.data.empty() || candidate.width == 0 ||
candidate.height == 0 || candidate.depth < 3)
return false;
std::string reason;
if (!this->FrameLooksUsable(
candidate.data.data(),
candidate.width,
candidate.height,
candidate.depth,
reason))
{
if (!this->physicalWarned)
{
gzerr << "[SimpleDronePlugin] waiting for usable physical camera frame at target index "
<< this->targetIndex << "; camera="
<< this->cameraNames[this->physicalViewIndex]
<< "; " << reason << std::endl;
this->physicalWarned = true;
}
this->physicalBaselineTime = candidate.time;
++this->physicalRejectCount;
if (this->physicalRejectCount >= 60)
{
gzerr << "[SimpleDronePlugin] physical cameras stayed unusable at target index "
<< this->targetIndex
<< "; switching the remainder of this trajectory to single-camera sweep."
<< std::endl;
this->physicalFallbackToSweep = true;
this->ResetPhysicalCameraSequence();
}
return false;
}
this->physicalFrames[this->physicalViewIndex] = std::move(candidate);
++this->physicalViewIndex;
this->physicalWarned = false;
this->physicalViewArmed = false;
this->physicalBaselineTime = common::Time::Zero;
return false;
}
// Read the latest RGB frame from each camera and write it to disk as PNG.
// Returns true only when a complete frame set is written, so images and
// trajectory rows stay in one-to-one correspondence (sharing one frame index).
bool CaptureFrames()
{
// Capture only once EVERY camera has a rendered frame this tick. During the
// first few updates the render pipeline is still warming up and ImageData()
// is null; capturing then would advance the frame counter and log a
// trajectory row with no PNG on disk, breaking the image<->trajectory
// pairing. Bail out so this frame index is retried until all views render.
std::vector<CachedFrame> frames;
const char *singleCameraSweep = std::getenv("SIMPLE_DRONE_SINGLE_CAMERA_SWEEP");
const bool useSingleCameraSweep =
this->physicalFallbackToSweep ||
(singleCameraSweep && std::string(singleCameraSweep) != "0");
if (useSingleCameraSweep)
{
if (!this->AdvanceSingleCameraSweep(frames))
return false;
}
else
{
if (!this->AdvancePhysicalCameraSequence(frames))
return false;
}
for (size_t i = 0; i < this->cameras.size(); ++i)
{
if (i >= frames.size() || frames[i].data.empty() ||
frames[i].width == 0 || frames[i].height == 0 || frames[i].depth < 3)
{
if (!this->captureFailureWarned)
{
gzerr << "[SimpleDronePlugin] camera frame not ready at target index "
<< this->targetIndex << "; camera=" << this->cameraNames[i]
<< ", movable_frame=" << (i < frames.size() && !frames[i].data.empty())
<< std::endl;
this->captureFailureWarned = true;
}
return false;
}
}
std::string frameName;
if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
{
const DatasetTrajectory &traj = this->datasetTrajectories[this->currentDatasetTrajectory];
const DatasetPoint &pt = traj.points[this->targetIndex];
std::ostringstream name;
name << traj.name << "_step_" << std::setw(6) << std::setfill('0') << pt.step << ".png";
frameName = name.str();
}
if (this->rejectGrayImages)
{
for (size_t i = 0; i < this->cameras.size(); ++i)
{
const CachedFrame &frame = frames[i];
const unsigned char *data = frame.data.data();
std::string reason;
if (!this->FrameLooksUsable(
data,
frame.width,
frame.height,
frame.depth,
reason))
{
if (this->grayRejectWarnCounter % 100 == 0)
{
gzerr << "[SimpleDronePlugin] rejected gray/unusable frame at target index "
<< this->targetIndex << "; camera=" << this->cameraNames[i]
<< "; " << reason << ". Waiting for a new frame." << std::endl;
}
++this->grayRejectWarnCounter;
if (useSingleCameraSweep)
this->ResetSingleCameraSweep();
else
this->ResetPhysicalCameraSequence();
return false;
}
}
}
// All four views are ready -- save them under the shared frame index.
for (size_t i = 0; i < this->cameras.size(); ++i)
{
const CachedFrame &frame = frames[i];
// `cam->ImageData()` is a tightly packed R8G8B8 buffer of size w * h * 3.
// (Use it here directly if you want to feed it into an algorithm.)
// ----- save the RGB image as PNG into this camera's sub-folder -----
char name[300];
if (this->datasetMode)
{
const DatasetTrajectory &traj =
this->datasetTrajectories[this->currentDatasetTrajectory];
std::snprintf(name, sizeof(name), "%s/%s/%s/%s",
this->imageDir.c_str(),
traj.name.c_str(),
this->folderNames[i].c_str(),
frameName.c_str());
}
else
{
std::snprintf(name, sizeof(name), "%s/%s/%06u.png",
this->imageDir.c_str(),
this->folderNames[i].c_str(),
this->frameCounter);
}
const unsigned char *data = frame.data.data();
if (!data || frame.data.empty())
{
gzerr << "[SimpleDronePlugin] camera image data disappeared before save; camera="
<< this->cameraNames[i] << std::endl;
return false;
}
const size_t pixelCount =
static_cast<size_t>(frame.width) * static_cast<size_t>(frame.height) * 3u;
unsigned int minValue = 255;
unsigned int maxValue = 0;
unsigned long long sumValue = 0;
for (size_t pixel = 0; pixel < pixelCount; ++pixel)
{
const unsigned int value = static_cast<unsigned int>(data[pixel]);
minValue = std::min(minValue, value);
maxValue = std::max(maxValue, value);
sumValue += value;
}
if (std::getenv("SIMPLE_DRONE_DEBUG_CAMERA"))
{
gzmsg << "[SimpleDronePlugin] camera buffer "
<< this->cameraNames[i]
<< " frame=" << this->frameCounter
<< " size=" << frame.width << "x" << frame.height
<< " min=" << minValue
<< " max=" << maxValue
<< " mean=" << (static_cast<double>(sumValue) / std::max<size_t>(pixelCount, 1u))
<< " first_rgb="
<< static_cast<unsigned int>(data[0]) << ','
<< static_cast<unsigned int>(data[1]) << ','
<< static_cast<unsigned int>(data[2])
<< std::endl;
}
common::Image image;
image.SetFromData(
data,
frame.width,
frame.height,
common::Image::RGB_INT8);
image.SavePNG(std::string(name));
}
// ----- log this trajectory point (3D position + orientation) -----
ignition::math::Pose3d pose = this->model->WorldPose();
const ignition::math::Vector3d &p = pose.Pos();
const ignition::math::Quaterniond &q = pose.Rot();
double roll = q.Roll();
double pitch = q.Pitch();
double yaw = q.Yaw();
const double r2d = 180.0 / M_PI;
double t = this->world->SimTime().Double();
if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
{
DatasetPoint &pt =
this->datasetTrajectories[this->currentDatasetTrajectory].points[this->targetIndex];
pt.capturedX = p.X();
pt.capturedY = p.Y();
pt.capturedZ = p.Z();
pt.captureFrame = this->frameCounter;
pt.capturedYawRad = yaw;
pt.capturedYawDeg = yaw * r2d;
pt.imageName = frameName;
pt.captured = true;
}
else if (this->trajFile.is_open())
{
this->trajFile << this->frameCounter << ','
<< t << ','
<< p.X() << ',' << p.Y() << ',' << p.Z() << ','
<< roll << ',' << pitch << ',' << yaw << ','
<< (roll * r2d) << ',' << (pitch * r2d) << ',' << (yaw * r2d) << ','
<< q.W() << ',' << q.X() << ',' << q.Y() << ',' << q.Z() << '\n';
this->trajFile.flush(); // persist even if the sim is Ctrl+C'd
}
gzmsg << "[SimpleDronePlugin] saved frame set #"
<< this->frameCounter << " (front/down/left/right)" << std::endl;
this->grayRejectWarnCounter = 0;
this->physicalRejectCount = 0;
++this->frameCounter;
return true;
}
void OnUpdate()
{
common::Time now = this->world->SimTime();
// Tour finished: hold the drone at the final waypoint and record nothing.
if (this->tourComplete)
{
this->model->SetWorldPose(this->holdPose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
return;
}
// Lazily bind the cameras once the sensor manager has created them.
if (!this->camerasReady)
this->camerasReady = this->InitCameras();
if (!this->camerasReady)
return; // nothing happens (no motion, no capture) until cameras exist
if (this->waypoints.empty())
return;
// ===== settle-then-capture on each waypoint =====
// While settling, the drone is pinned to the EXACT waypoint and we wait for
// every camera to render a brand-new frame from that pinned pose before
// saving. Gazebo renders the cameras *after* this callback, so without the
// wait the saved PNG would be the frame rendered one step earlier (during
// the approach, a few cm short). The wait makes each image truly correspond
// to its logged coordinate. The start point (waypoints[0]) begins settling.
if (this->settling)
{
const ignition::math::Vector3d &wp = this->waypoints[this->targetIndex];
const ignition::math::Pose3d snapped(
wp.X(), wp.Y(), wp.Z(), 0.0, 0.0,
this->datasetMode ? 0.0 : this->captureYaw);
this->model->SetWorldPose(snapped); // re-assert every tick: hold dead still
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
// First tick parked here: latch each camera's current render time as the
// baseline, then yield so the cameras can render from the pinned pose.
if (!this->settleBaselineSet)
{
this->baseRenderTime.resize(this->cameras.size());
for (size_t i = 0; i < this->cameras.size(); ++i)
{
if (this->cameras[i])
{
this->cameras[i]->SetActive(true);
this->cameras[i]->Update(true);
}
this->baseRenderTime[i] = this->cameras[i]
? this->cameras[i]->LastMeasurementTime() : common::Time::Zero;
}
this->settleStartTime = now;
this->settleBaselineSet = true;
this->captureFailureWarned = false;
return;
}
// Hold until EVERY camera has produced a new frame strictly after the
// snap (i.e. rendered from the pinned pose), then capture.
bool allCamerasRerendered = true;
for (size_t i = 0; i < this->cameras.size(); ++i)
{
if (this->cameras[i])
{
this->cameras[i]->SetActive(true);
this->cameras[i]->Update(true);
}
if (!this->cameras[i] ||
this->cameras[i]->LastMeasurementTime() <= this->baseRenderTime[i])
{
allCamerasRerendered = false;
break;
}
}
if (!allCamerasRerendered)
{
const double settleWait = (now - this->settleStartTime).Double();
if (settleWait < this->settleTimeout)
return; // not all cameras have re-rendered yet -- keep waiting
if (!this->settleTimeoutWarned)
{
gzerr << "[SimpleDronePlugin] camera settle timeout after "
<< settleWait << "s at target index " << this->targetIndex
<< "; capturing latest available frames." << std::endl;
this->settleTimeoutWarned = true;
}
}
if (!this->CaptureFrames()) // also guards against null image buffers
return;
this->settling = false;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
this->ResetPhysicalCameraSequence();
if (this->datasetMode)
{
this->settling = false;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
this->AdvanceDatasetAfterCapture(snapped);
return;
}
if (this->commandMode)
{
this->holdPose = snapped;
this->waitingForCommand = true;
this->lastTime = now;
return;
}
// That was the last waypoint -> the single-pass tour is done.
if (this->targetIndex + 1 >= this->waypoints.size())
{
this->FinishTour(snapped);
return;
}
++this->targetIndex; // head for the next waypoint
this->lastTime = now; // keep the first travel dt to one step
return;
}
if (this->commandMode && this->waitingForCommand)
{
this->model->SetWorldPose(this->holdPose);
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
if (!this->TryLoadCommand())
return;
this->waypoints.resize(1);
this->waypoints.push_back(this->commandTarget);
this->targetIndex = 1;
this->waitingForCommand = false;
this->lastTime = now;
return;
}
// ===== fly toward waypoints[targetIndex] =====
double dt = (now - this->lastTime).Double();
this->lastTime = now;
if (dt <= 0.0)
return;
ignition::math::Vector3d pos = this->model->WorldPose().Pos();
ignition::math::Vector3d diff = this->waypoints[this->targetIndex] - pos;
if (diff.Length() < 0.08)
{
if (this->datasetMode && this->returningToStart)
{
size_t nextTrajectory = this->currentDatasetTrajectory + 1;
if (!this->BeginDatasetTrajectoryAtStart(nextTrajectory))
{
this->FinishTour(this->model->WorldPose());
return;
}
return;
}
// Arrived: latch the travel heading and start settling on the waypoint.
if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
this->captureYaw = 0.0;
else
this->captureYaw = this->commandMode ? this->commandYaw
: this->model->WorldPose().Rot().Yaw();
this->settling = true;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
return;
}
ignition::math::Vector3d dir = diff.Normalized();
double yaw = this->datasetMode ? 0.0 : std::atan2(dir.Y(), dir.X());
double travel = this->speed * dt;
ignition::math::Vector3d newPos;
if (travel >= diff.Length())
{
newPos = this->waypoints[this->targetIndex];
}
else
{
newPos = pos + dir * travel;
}
this->model->SetWorldPose(
ignition::math::Pose3d(newPos.X(), newPos.Y(), newPos.Z(), 0.0, 0.0, yaw));
this->model->SetLinearVel(travel >= diff.Length()
? ignition::math::Vector3d::Zero
: dir * this->speed);
}
struct DatasetPoint
{
int step = 0;
double x = 0.0;
double y = 0.0;
double z = 0.0;
double yawRad = 0.0;
double yawDeg = 0.0;
double capturedX = 0.0;
double capturedY = 0.0;
double capturedZ = 0.0;
unsigned int captureFrame = 0;
double capturedYawRad = 0.0;
double capturedYawDeg = 0.0;
std::string imageName;
bool captured = false;
};
int EnvInt(const char *name, int fallback)
{
const char *value = std::getenv(name);
if (!value || value[0] == '\0')
return fallback;
try
{
return std::stoi(value);
}
catch (...)
{
return fallback;
}
}
double EnvDouble(const char *name, double fallback)
{
const char *value = std::getenv(name);
if (!value || value[0] == '\0')
return fallback;
try
{
return std::stod(value);
}
catch (...)
{
return fallback;
}
}
bool FrameLooksUsable(
const unsigned char *data,
unsigned int width,
unsigned int height,
unsigned int depth,
std::string &reason)
{
if (!data || width == 0 || height == 0 || depth < 3)
{
reason = "empty image buffer";
return false;
}
const size_t pixelCount =
static_cast<size_t>(width) * static_cast<size_t>(height);
unsigned int globalMin = 255;
unsigned int globalMax = 0;
size_t grayPixels = 0;
double lumaSum = 0.0;
double lumaSqSum = 0.0;
const unsigned int tilesX = 8;
const unsigned int tilesY = 8;
std::vector<size_t> tilePixels(tilesX * tilesY, 0);
std::vector<size_t> tileGrayPixels(tilesX * tilesY, 0);
std::vector<unsigned int> tileMin(tilesX * tilesY, 255);
std::vector<unsigned int> tileMax(tilesX * tilesY, 0);
std::vector<double> tileLumaSum(tilesX * tilesY, 0.0);
std::vector<double> tileLumaSqSum(tilesX * tilesY, 0.0);
std::vector<size_t> rowBufferPixels(height, 0);
std::vector<size_t> columnBufferPixels(width, 0);
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width; ++x)
{
const size_t offset =
(static_cast<size_t>(y) * static_cast<size_t>(width) + x) * depth;
const unsigned int r = static_cast<unsigned int>(data[offset]);
const unsigned int g = static_cast<unsigned int>(data[offset + 1]);
const unsigned int b = static_cast<unsigned int>(data[offset + 2]);
const unsigned int cmin = std::min(r, std::min(g, b));
const unsigned int cmax = std::max(r, std::max(g, b));
const double luma = (static_cast<double>(r) + g + b) / 3.0;
const unsigned int tileX = std::min((x * tilesX) / width, tilesX - 1);
const unsigned int tileY = std::min((y * tilesY) / height, tilesY - 1);
const size_t tileIndex = static_cast<size_t>(tileY) * tilesX + tileX;
globalMin = std::min(globalMin, cmin);
globalMax = std::max(globalMax, cmax);
lumaSum += luma;
lumaSqSum += luma * luma;
++tilePixels[tileIndex];
tileMin[tileIndex] = std::min(tileMin[tileIndex], cmin);
tileMax[tileIndex] = std::max(tileMax[tileIndex], cmax);
tileLumaSum[tileIndex] += luma;
tileLumaSqSum[tileIndex] += luma * luma;
const bool isGray =
(cmax - cmin <= static_cast<unsigned int>(this->grayDelta)) &&
(luma >= this->grayMin) &&
(luma <= this->grayMax);
if (isGray)
{
++grayPixels;
++tileGrayPixels[tileIndex];
}
if (r == 128u && g == 128u && b == 128u)
{
++rowBufferPixels[y];
++columnBufferPixels[x];
}
}
}
const unsigned int rgbRange = globalMax - globalMin;
const double mean = lumaSum / std::max<size_t>(pixelCount, 1u);
const double variance =
std::max(0.0, lumaSqSum / std::max<size_t>(pixelCount, 1u) - mean * mean);
const double lumaStd = std::sqrt(variance);
const double grayRatio =
static_cast<double>(grayPixels) / std::max<size_t>(pixelCount, 1u);
if (rgbRange < static_cast<unsigned int>(this->minRgbRange))
{
std::ostringstream out;
out << "near-uniform image rgb_range=" << rgbRange
<< " luma_std=" << lumaStd;
reason = out.str();
return false;
}
if (grayRatio > this->grayMaxRatio)
{
std::ostringstream out;
out << "global gray ratio too high ratio=" << grayRatio;
reason = out.str();
return false;
}
for (unsigned int y = 0; y < height; ++y)
{
const double ratio = static_cast<double>(rowBufferPixels[y]) / width;
if (ratio > this->grayScanlineRatio)
{
std::ostringstream out;
out << "gray render-buffer row ratio too high row=" << y
<< " ratio=" << ratio;
reason = out.str();
return false;
}
}
for (unsigned int x = 0; x < width; ++x)
{
const double ratio = static_cast<double>(columnBufferPixels[x]) / height;
if (ratio > this->grayScanlineRatio)
{
std::ostringstream out;
out << "gray render-buffer column ratio too high column=" << x
<< " ratio=" << ratio;
reason = out.str();
return false;
}
}
for (size_t i = 0; i < tilePixels.size(); ++i)
{
if (tilePixels[i] == 0)
continue;
const double tileRatio =
static_cast<double>(tileGrayPixels[i]) / static_cast<double>(tilePixels[i]);
const double tileMean =
tileLumaSum[i] / static_cast<double>(tilePixels[i]);
const double tileVariance =
std::max(0.0,
tileLumaSqSum[i] / static_cast<double>(tilePixels[i]) -
tileMean * tileMean);
const double tileStd = std::sqrt(tileVariance);
const unsigned int tileRange = tileMax[i] - tileMin[i];
if (tileRatio > this->grayTileRatio &&
tileStd < this->minLumaStd &&
tileRange < static_cast<unsigned int>(this->minRgbRange))
{
std::ostringstream out;
out << "gray tile ratio too high tile=" << i
<< " ratio=" << tileRatio
<< " tile_range=" << tileRange
<< " tile_luma_std=" << tileStd;
reason = out.str();
return false;
}
}
return true;
}
struct DatasetTrajectory
{
std::string name;
std::string path;
std::vector<DatasetPoint> points;
};
std::vector<std::string> SplitCsvLine(const std::string &line)
{
std::vector<std::string> cols;
std::string col;
std::istringstream ss(line);
while (std::getline(ss, col, ','))
cols.push_back(col);
return cols;
}
void LoadDatasetTrajectories()
{
this->datasetTrajectories.clear();
std::vector<std::string> csvFiles;
if (!this->datasetTrajectoryFile.empty())
{
if (boost::filesystem::exists(this->datasetTrajectoryFile))
csvFiles.push_back(this->datasetTrajectoryFile);
}
else
{
if (!boost::filesystem::exists(this->trajectoryDir))
return;
boost::filesystem::directory_iterator end;
for (boost::filesystem::directory_iterator it(this->trajectoryDir); it != end; ++it)
{
if (boost::filesystem::is_regular_file(it->path()) && it->path().extension() == ".csv")
csvFiles.push_back(it->path().string());
}
std::sort(csvFiles.begin(), csvFiles.end());
}
for (const std::string &path : csvFiles)
{
std::ifstream in(path);
std::string line;
if (!std::getline(in, line))
continue;
DatasetTrajectory traj;
boost::filesystem::path p(path);
traj.name = p.stem().string();
traj.path = path;
while (std::getline(in, line))
{
if (line.empty())
continue;
std::vector<std::string> cols = this->SplitCsvLine(line);
if (cols.size() < 5)
continue;
DatasetPoint pt;
try
{
pt.step = std::stoi(cols[0]);
pt.x = std::stod(cols[1]);
pt.y = std::stod(cols[2]);
pt.z = std::stod(cols[3]);
pt.yawRad = std::stod(cols[4]);
pt.yawDeg = cols.size() > 5 ? std::stod(cols[5]) : pt.yawRad * 180.0 / M_PI;
}
catch (...)
{
continue;
}
traj.points.push_back(pt);
}
if (!traj.points.empty())
this->datasetTrajectories.push_back(traj);
}
gzmsg << "[SimpleDronePlugin] loaded " << this->datasetTrajectories.size()
<< " dataset trajector"
<< (this->datasetTrajectories.size() == 1 ? "y" : "ies")
<< " from "
<< (this->datasetTrajectoryFile.empty()
? this->trajectoryDir
: this->datasetTrajectoryFile)
<< std::endl;
}
bool BeginDatasetTrajectory(size_t index)
{
if (index >= this->datasetTrajectories.size())
return false;
this->currentDatasetTrajectory = index;
this->waypoints.clear();
const DatasetTrajectory &traj = this->datasetTrajectories[index];
for (const DatasetPoint &pt : traj.points)
this->waypoints.push_back(ignition::math::Vector3d(pt.x, pt.y, pt.z));
this->targetIndex = 0;
this->returningToStart = false;
this->captureYaw = 0.0;
this->settling = true;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
this->physicalRejectCount = 0;
this->physicalFallbackToSweep = false;
this->lastTime = this->world->SimTime();
gzmsg << "[SimpleDronePlugin] dataset trajectory "
<< (index + 1) << "/" << this->datasetTrajectories.size()
<< ": " << traj.name << " (" << traj.points.size()
<< " points)" << std::endl;
for (const std::string &folder : this->folderNames)
boost::filesystem::create_directories(this->imageDir + "/" + traj.name + "/" + folder);
return true;
}
bool BeginDatasetTrajectoryAtStart(size_t index)
{
if (index >= this->datasetTrajectories.size())
return false;
const DatasetPoint &start = this->datasetTrajectories[index].points.front();
this->model->SetWorldPose(
ignition::math::Pose3d(start.x, start.y, start.z, 0.0, 0.0, 0.0));
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
return this->BeginDatasetTrajectory(index);
}
void AdvanceDatasetAfterCapture(const ignition::math::Pose3d &snapped)
{
if (this->currentDatasetTrajectory >= this->datasetTrajectories.size())
return;
DatasetTrajectory &traj = this->datasetTrajectories[this->currentDatasetTrajectory];
this->RewriteDatasetTrajectoryCsv(traj);
if (this->targetIndex + 1 < traj.points.size())
{
++this->targetIndex;
this->captureYaw = 0.0;
this->settling = true;
this->settleBaselineSet = false;
this->captureFailureWarned = false;
this->settleTimeoutWarned = false;
this->physicalRejectCount = 0;
this->lastTime = this->world->SimTime();
return;
}
this->FinishTour(snapped);
}
void RewriteDatasetTrajectoryCsv(const DatasetTrajectory &traj)
{
std::ofstream out(traj.path, std::ios::out | std::ios::trunc);
out << "step,x,y,z,yaw_rad,yaw_deg,"
"capture_frame,captured_yaw_rad,captured_yaw_deg,"
"front_image,down_image,left_image,right_image\n";
for (const DatasetPoint &pt : traj.points)
{
out << pt.step << ','
<< (pt.captured ? pt.capturedX : pt.x) << ','
<< (pt.captured ? pt.capturedY : pt.y) << ','
<< (pt.captured ? pt.capturedZ : pt.z) << ','
<< pt.yawRad << ','
<< pt.yawDeg << ',';
if (pt.captured)
{
out << pt.captureFrame << ','
<< pt.capturedYawRad << ','
<< pt.capturedYawDeg << ','
<< pt.imageName << ','
<< pt.imageName << ','
<< pt.imageName << ','
<< pt.imageName << '\n';
}
else
{
out << ",,,,,,\n";
}
}
out.flush();
gzmsg << "[SimpleDronePlugin] updated dataset trajectory CSV: "
<< traj.path << std::endl;
}
bool TryLoadCommand()
{
if (this->commandFile.empty() || !boost::filesystem::exists(this->commandFile))
return false;
std::time_t mtime = boost::filesystem::last_write_time(this->commandFile);
std::ifstream in(this->commandFile);
std::ostringstream buf;
buf << in.rdbuf();
std::string commandText = buf.str();
if (mtime <= this->lastCommandMTime && commandText == this->lastCommandText)
return false;
std::string line;
std::istringstream lines(commandText);
while (std::getline(lines, line))
{
if (line.empty() || line.find("x") != std::string::npos)
continue;
for (char &c : line)
{
if (c == ',')
c = ' ';
}
std::istringstream ss(line);
double x = 0.0, y = 0.0, z = 0.0, yaw = 0.0;
if (!(ss >> x >> y >> z >> yaw))
continue;
this->commandTarget = ignition::math::Vector3d(
std::max(-7.0, std::min(6.5, x)),
std::max(-4.0, std::min(4.0, y)),
std::max(1.2, std::min(1.8, z)));
this->commandYaw = yaw;
this->lastCommandMTime = mtime;
this->lastCommandText = commandText;
gzmsg << "[SimpleDronePlugin] command target: "
<< this->commandTarget.X() << ", "
<< this->commandTarget.Y() << ", "
<< this->commandTarget.Z() << ", yaw="
<< this->commandYaw << std::endl;
return true;
}
this->lastCommandMTime = mtime;
this->lastCommandText = commandText;
gzerr << "[SimpleDronePlugin] command file changed but no valid x,y,z,yaw found: "
<< this->commandFile << std::endl;
return false;
}
// Called once the final waypoint has been captured. The frame for the last
// waypoint is already saved by the capture-on-arrival branch, so this only
// closes the trajectory file and latches the tour as complete (no further
// motion or recording).
void FinishTour(const ignition::math::Pose3d &finalPose)
{
if (this->trajFile.is_open())
this->trajFile.close();
this->holdPose = finalPose;
this->model->SetLinearVel(ignition::math::Vector3d::Zero);
this->tourComplete = true;
gzmsg << "[SimpleDronePlugin] trajectory complete: visited "
<< this->waypoints.size() << " waypoints, saved "
<< this->frameCounter << " frame sets. Recording stopped."
<< std::endl;
if (this->quitOnFinish)
{
if (!this->doneFile.empty())
{
std::ofstream done(this->doneFile, std::ios::out | std::ios::trunc);
done << "done\n";
done.flush();
gzmsg << "[SimpleDronePlugin] wrote done file: "
<< this->doneFile << std::endl;
}
gzmsg << "[SimpleDronePlugin] SIMPLE_DRONE_QUIT_ON_FINISH set; shutdown requested."
<< std::endl;
gazebo::shutdown();
}
}
private:
physics::ModelPtr model;
physics::WorldPtr world;
event::ConnectionPtr updateConnection;
// Cameras (front / down / left / right).
std::vector<std::string> cameraNames; // sensor names, must match the SDF
std::vector<std::string> folderNames; // output sub-folder per camera
std::vector<sensors::CameraSensorPtr> cameras;
std::vector<event::ConnectionPtr> imageConnections;
bool camerasReady;
std::string imageDir;
double capturePeriod; // legacy, unused (capture is per-waypoint now)
common::Time lastCaptureTime; // legacy, unused
unsigned int frameCounter;
std::ofstream trajFile;
std::vector<ignition::math::Vector3d> waypoints;
unsigned int targetIndex;
// Settle-then-capture state: while parked on a waypoint we wait for the
// cameras to re-render from the pinned pose before saving, so each image
// matches its logged coordinate exactly.
bool settling; // true while parked on a waypoint awaiting capture
bool settleBaselineSet; // have we latched the pre-settle render times?
bool captureFailureWarned; // avoid spamming camera readiness diagnostics
bool settleTimeoutWarned; // avoid spamming settle timeout diagnostics
double captureYaw; // heading to hold while settling (travel heading)
std::vector<common::Time> baseRenderTime; // per-camera render time at snap moment
common::Time settleStartTime;
const double settleTimeout = 10.0;
double speed;
common::Time lastTime;
// One-shot tour state: once the last waypoint is reached the drone hovers
// at `holdPose` and stops capturing.
bool tourComplete;
ignition::math::Pose3d holdPose;
// Dataset trajectory mode. Trajectories are read from
// <datasetRoot>/trajectory/*.csv. Captures are saved into
// <datasetRoot>/images/<trajectory_name>/images_{front,down,left,right}/.
bool datasetMode;
bool quitOnFinish;
std::string doneFile;
bool returningToStart;
std::string datasetRoot;
std::string trajectoryDir;
std::string datasetTrajectoryFile;
std::vector<DatasetTrajectory> datasetTrajectories;
size_t currentDatasetTrajectory;
// File-based Python control mode. After each captured frame set, the drone
// holds position until Python writes x,y,z,yaw to commandFile.
bool commandMode;
bool waitingForCommand;
std::string commandFile;
std::string lastCommandText;
std::time_t lastCommandMTime;
ignition::math::Vector3d commandTarget;
double commandYaw;
bool rejectGrayImages;
int grayDelta;
int grayMin;
int grayMax;
double grayMaxRatio;
double grayTileRatio;
double grayScanlineRatio;
double minLumaStd;
int minRgbRange;
double viewDownTilt;
double minValidImageRatio;
unsigned int grayRejectWarnCounter;
std::mutex frameMutex;
std::vector<CachedFrame> latestFrames;
bool physicalSequenceInProgress;
size_t physicalViewIndex;
bool physicalWarned;
bool physicalViewArmed;
common::Time physicalBaselineTime;
unsigned int physicalRejectCount;
bool physicalFallbackToSweep;
std::vector<CachedFrame> physicalFrames;
bool sweepInProgress;
bool sweepPoseSet;
size_t sweepViewIndex;
unsigned int sweepYawAttempt;
bool sweepTimeoutWarned;
common::Time sweepStartTime;
common::Time sweepBaselineFrameTime;
ignition::math::Pose3d sweepBasePose;
std::vector<CachedFrame> sweepFrames;
};
GZ_REGISTER_MODEL_PLUGIN(SimpleDronePlugin)
}