diff --git a/CHANGELOG.md b/CHANGELOG.md index bae3a118..5ce7af6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,25 @@ Entries below v2.5.0 were reconstructed from the release notes and the commit history, so they summarise each release rather than list every change. The `Full Changelog` link on each version gives the complete commit range. +## [Unreleased] + +### Fixed + +- Commands that need a domain print an error when there is none, instead of + segfaulting: `FireNode`, `FireFront`, `startFire`, `goTo`, `save[]`, + `trigger[fuel]`, `trigger[fuelIndice]`, any command scheduled with `@t` or + `@nowplus`, and a `FireDomain[...]` with missing options. A script whose + `loadData` failed used to crash on the next `startFire`. +- `clear[]` followed by a new domain no longer crashes on the first + `startFire`. The destroyed domain's layers stayed in the `DataBroker` + shortcuts, so the new domain never created its own altitude and wind + layers. +- The `BMap` layer holds the arrival times again; its recomputation had been + commented out, so `getDoubleArray("BMap")` returned zeros. +- `plot[...;filename=*.asc]` writes a valid ESRI ASCII grid: one row per y, + north first, at full precision. It used to write one row per x and round + values to six significant digits. + ## [v2.6.0] — 2026-10-26 ### Added @@ -233,6 +252,7 @@ The V2 release: the HTTP interface, and alignment with Meso-NH V4.7.2. Tagged before the sources were moved into `src/`, so that this point in the repository stays easy to return to. +[Unreleased]: https://github.com/forefireAPI/forefire/compare/v2.6.0...dev [v2.6.0]: https://github.com/forefireAPI/forefire/releases/tag/v2.6.0 [v2.5.0]: https://github.com/forefireAPI/forefire/releases/tag/v2.5.0 [v2.4.2]: https://github.com/forefireAPI/forefire/releases/tag/v2.4.2 diff --git a/src/BurningMapLayer.h b/src/BurningMapLayer.h index c12c9a10..52f14d56 100644 --- a/src/BurningMapLayer.h +++ b/src/BurningMapLayer.h @@ -130,16 +130,14 @@ T BurningMapLayer::getNearestData(FFPoint loc){ template void BurningMapLayer::getMatrix( FFArray** matrix, const double& t){ - // cout << "getting matrix lmayer "<getArrivalTime(i, j); } } latestCall = t; - }*/ + } // Affecting the computed matrix to the desired array *matrix = arrivalTimes; } diff --git a/src/Command.cpp b/src/Command.cpp index 56352509..83f5bd81 100644 --- a/src/Command.cpp +++ b/src/Command.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" @@ -254,6 +255,8 @@ namespace libforefire int Command::startFire(const string &arg, size_t &numTabs) { + if (!domainExists("startFire")) + return error; double t = getDomain()->getTime(); SimulationParameters *simParam = SimulationParameters::GetInstance(); @@ -676,6 +679,8 @@ namespace libforefire int Command::createFireFront(const string &arg, size_t &numTabs) { + if (!domainExists("FireFront")) + return error; size_t n = argCount(arg); if (n >= 1) @@ -731,6 +736,8 @@ namespace libforefire int Command::addFireNode(const string &arg, size_t &numTabs) { + if (!domainExists("FireNode")) + return error; if (lastReadLoc == 0) lastReadLoc = new FFPoint(-numeric_limits::infinity(), -numeric_limits::infinity(), 0); @@ -977,6 +984,8 @@ namespace libforefire int Command::goTo(const string &arg, size_t &numTabs) { + if (!domainExists("goTo")) + return error; /* Advancing simulation to the prescribed time */ endTime = getFloat("t", arg); @@ -1930,6 +1939,8 @@ namespace libforefire } else { + if (!domainExists("save")) + return error; getDomain()->saveArrivalTimeNC(); // Default save operation if no arguments provided } @@ -2160,6 +2171,8 @@ namespace libforefire if (tmpArgs[0] == "fuel") { + if (!domainExists("trigger[fuel]")) + return error; if (getDomain()->getDataBroker() != 0) { @@ -2180,6 +2193,8 @@ namespace libforefire } if (tmpArgs[0] == "fuelIndice") { + if (!domainExists("trigger[fuelIndice]")) + return error; if (getDomain()->getDataBroker() != 0) { FFPoint loc = getPoint("loc", arg); @@ -2991,7 +3006,8 @@ namespace libforefire delete currentSession.fd; currentSession.fd =nullptr; //delete currentSession.outStrRep; - currentSession.sim->getSchedule()->clear(); + if (currentSession.sim != nullptr) + currentSession.sim->getSchedule()->clear(); // delete currentSession.params; return normal; } @@ -3365,6 +3381,12 @@ namespace libforefire { if (postcmd.size() > 1) { + // Scheduled commands go to the domain's time table. + if (!domainExists(scmd + " scheduled with @")) + { + command.clear(); + return; + } string atCommand = line.substr(0, line.rfind("]") + 1); string whenCommand = line.substr(line.rfind("]") + 1, -1); double whenDouble = getFloat("@t", whenCommand); @@ -3393,6 +3415,9 @@ namespace libforefire } else { + // The domain ID, when there is a domain, prefixes the error messages. + auto where = []() + { return getDomain() ? to_string(getDomain()->getDomainID()) + ": " : string(); }; try { // calling the right function @@ -3401,26 +3426,26 @@ namespace libforefire } catch (BadOption &) { - cout << getDomain()->getDomainID() << ": " + cout << where() << "argument(s) '" << command[1] << "' is (are) not fit for command '" << command[0] << "'" << endl; cout << "type 'man[" << command[0] << "]' for more information" << endl; } catch (MissingOption &mo) { - cout << getDomain()->getDomainID() << ": " + cout << where() << "command '" << command[0] << "' misses " << mo.num << " options." << endl; cout << "type 'man[" << command[0] << "]' for more information" << endl; } catch (MissingTime &) { - cout << getDomain()->getDomainID() << ": " + cout << where() << "you have to specify a time for that command (as in 't=0.')" << endl; } catch (...) { - cout << getDomain()->getDomainID() << ": " + cout << where() << " PROBLEM: Command associated to " << line << " ended in error" << endl; } } @@ -3526,6 +3551,15 @@ namespace libforefire return currentSession.fd; } + bool Command::domainExists(const string &command) + { + if (getDomain() != nullptr) + return true; + cout << "Error: " << command << " needs a domain, create one first with " + << "FireDomain[...] or loadData[...]" << endl; + return false; + } + string Command::dumpString() { return currentSession.outStrRep->outputstr.str(); @@ -3792,9 +3826,10 @@ namespace libforefire return; } - // Determine the number of rows and columns. - size_t nrows = matrix.size(); - size_t ncols = (nrows > 0) ? matrix[0].size() : 0; + // The matrix is indexed [x][y] from the south-west corner, while an + // ASCII grid has one row per y, from north to south. + size_t ncols = matrix.size(); + size_t nrows = (ncols > 0) ? matrix[0].size() : 0; // Compute the cell size. // Here we assume that (NEX - SWX) corresponds to the total width of the matrix. @@ -3808,13 +3843,15 @@ namespace libforefire out << "cellsize " << cellsize << "\n"; out << "NODATA_value -9999\n"; - // Write the matrix data row by row. - for (size_t i = 0; i < nrows; i++) + // Write the matrix data row by row, at full precision. + out.precision(std::numeric_limits::max_digits10); + for (size_t row = 0; row < nrows; row++) { - for (size_t j = 0; j < ncols; j++) + size_t j = nrows - 1 - row; + for (size_t i = 0; i < ncols; i++) { out << matrix[i][j]; - if (j < ncols - 1) + if (i < ncols - 1) out << " "; } out << "\n"; diff --git a/src/Command.h b/src/Command.h index 1f94fddc..80f715fd 100644 --- a/src/Command.h +++ b/src/Command.h @@ -309,6 +309,8 @@ class Command { /*! \brief accessor to the domain */ static FireDomain* getDomain(); + /*! \brief true if a domain exists, otherwise prints why `command` cannot run */ + static bool domainExists(const string& command); /*! \brief command to redirect the ostringstream */ static void setOstringstream(ostringstream*); diff --git a/src/DataBroker.cpp b/src/DataBroker.cpp index 3c30fe8f..86802462 100644 --- a/src/DataBroker.cpp +++ b/src/DataBroker.cpp @@ -40,8 +40,40 @@ namespace libforefire commonInitialization(); } + namespace + { + // Nulls a static layer shortcut that points into `owned`. + template + void forgetIfOwned(L *&shortcut, const list *> &owned) + { + for (DataLayer *layer : owned) + { + if (layer == shortcut) + { + shortcut = 0; + return; + } + } + } + } + DataBroker::~DataBroker() { + // The static shortcuts outlive this broker. Left pointing at the + // layers deleted below, they make the next domain's broker believe + // its altitude and wind layers exist, and skip creating them. + forgetIfOwned(fuelLayer, layers); + forgetIfOwned(moistureLayer, layers); + forgetIfOwned(temperatureLayer, layers); + forgetIfOwned(dummyLayer, layers); + forgetIfOwned(altitudeLayer, layers); + forgetIfOwned(forcedArrivalTimeLayer, layers); + forgetIfOwned(slopeLayer, layers); + forgetIfOwned(windULayer, layers); + forgetIfOwned(windVLayer, layers); + forgetIfOwned(PwindULayer, layers); + forgetIfOwned(PwindVLayer, layers); + // Deleting layers. loadData lists the domain's propagative layer here // too, so it can be looked up, but the domain frees that one (#205). while (!layers.empty()) diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index a973a266..765845b7 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -18,6 +18,7 @@ add_executable(forefire_unit_tests test_topology.cpp test_timetable.cpp test_quit_command.cpp + test_commands.cpp test_data_broker.cpp) target_link_libraries(forefire_unit_tests PRIVATE forefireL) @@ -33,7 +34,7 @@ endif() # doctest groups its cases into suites; registering one CTest entry per suite # keeps `ctest` output useful without needing doctest's CMake integration. -foreach(_suite "model registry" "propagation models" "flux models" "http server" "topology" "fire front" "timetable" "quit command" "data broker") +foreach(_suite "model registry" "propagation models" "flux models" "http server" "topology" "fire front" "timetable" "quit command" "commands" "data broker") string(REPLACE " " "_" _suite_id "${_suite}") add_test(NAME "unit.${_suite_id}" COMMAND forefire_unit_tests --test-suite=${_suite} --no-skipped-summary) diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp new file mode 100644 index 00000000..f31ffc35 --- /dev/null +++ b/tests/unit/test_commands.cpp @@ -0,0 +1,178 @@ +/** + * @file test_commands.cpp + * @brief Commands without a domain, a domain built after clear[], and the + * arrival-time exports. + * @copyright Copyright (C) 2025 ForeFire, Fire Team, SPE, CNRS/Universita di Corsica. + * @license This program is free software; See LICENSE file for details. (See LICENSE file). + * + * Commands that need a domain used to dereference a null one, so a script + * whose loadData had failed segfaulted on the next startFire. They must print + * an error and return instead. As in test_quit_command.cpp, reaching the end + * of the case is the assertion that matters. + * + * A domain built after clear[] used to crash on its first startFire. + * + * The arrival times can be read two ways, and both used to be wrong: the BMap + * layer was never filled, and plot[...;filename=*.asc] wrote one row per x, + * at six significant digits, instead of an ASCII grid. + */ + +#include "doctest/doctest.h" + +#include "Command.h" + +#include +#include +#include +#include +#include +#include + +using libforefire::Command; +using libforefire::FFArray; + +namespace { + +void run(Command& executor, std::string command) { + executor.ExecuteCommand(command); +} + +/* A 2000 x 1000 m domain, 200 x 100 cells at the default 10 m, with a fire + * started off-centre at (300, 800) and run to t = 300. */ +void burnOffCentre(Command& executor) { + run(executor, "clear[]"); + run(executor, "setParameter[bmapLayer=1]"); + run(executor, "FireDomain[sw=(0,0,0);ne=(2000,1000,0);t=0]"); + REQUIRE(Command::getDomain() != nullptr); + REQUIRE(Command::getDomain()->addPropagativeLayer("Iso")); + run(executor, "startFire[loc=(300,800,0)]"); + run(executor, "goTo[t=300]"); +} + +struct AsciiGrid { + size_t ncols = 0, nrows = 0; + double xll = 0, yll = 0, cellsize = 0; + std::vector> rows; /* as written, north first */ +}; + +AsciiGrid readAsciiGrid(const std::string& path) { + AsciiGrid grid; + std::ifstream in(path); + std::string key; + double nodata; + in >> key >> grid.ncols >> key >> grid.nrows >> key >> grid.xll >> key >> grid.yll + >> key >> grid.cellsize >> key >> nodata; + grid.rows.assign(grid.nrows, std::vector(grid.ncols)); + for (auto& row : grid.rows) + for (auto& value : row) + in >> value; + return grid; +} + +} /* anonymous namespace */ + +TEST_SUITE("commands") { + +TEST_CASE("commands that need a domain return without one") { + Command executor; + const char* commands[] = { + "FireNode[loc=(10,10,0);vel=(0,0,0);t=0]", + "FireFront[t=0]", + "startFire[loc=(10,10,0)]", + "goTo[t=10]", + "save[]", + "trigger[fuel;vv_coeff=1]", + "trigger[fuelIndice;loc=(1,1,0);fuelType=1]", + "step[dt=1]@t=10", + "step[dt=1]@nowplus=10", + "FireDomain[sw=(0,0,0)]", + "clear[]", + }; + run(executor, "clear[]"); + for (const char* command : commands) { + CAPTURE(command); + run(executor, command); + CHECK(Command::getDomain() == nullptr); + } +} + +TEST_CASE("a domain built after clear[] burns like the first one") { + // The first domain's deleted layers used to outlive it in the DataBroker + // shortcuts, so the new domain never created its own altitude layer and + // its first startFire dereferenced a null one. + Command executor; + size_t burnt[2] = {0, 0}; + for (size_t& count : burnt) { + burnOffCentre(executor); + auto matrix = Command::getDomain()->getDataMatrix("arrival_time"); + for (const auto& column : matrix) + for (double t : column) + if (std::isfinite(t)) count++; + } + CHECK(burnt[0] > 0); + CHECK(burnt[1] == burnt[0]); +} + +TEST_CASE("the BMap layer holds the domain's arrival times") { + Command executor; + burnOffCentre(executor); + auto* domain = Command::getDomain(); + auto* layer = domain->getDataLayer("BMap"); + REQUIRE(layer != nullptr); + + FFArray* bmap = nullptr; + layer->getMatrix(&bmap, domain->getSimulationTime()); + REQUIRE(bmap != nullptr); + size_t burnt = 0, mismatched = 0; + for (size_t i = 0; i < bmap->getDim("x"); i++) { + for (size_t j = 0; j < bmap->getDim("y"); j++) { + double expected = domain->getArrivalTime(i, j); + if (std::isfinite(expected)) burnt++; + if ((*bmap)(i, j) != expected) mismatched++; + } + } + CHECK(burnt > 0); + CHECK(mismatched == 0); +} + +TEST_CASE("plot writes arrival times as an ASCII grid, north row first") { + Command executor; + burnOffCentre(executor); + const std::string path = "ff_test_arrival_time.asc"; + run(executor, "plot[parameter=arrival_time;filename=" + path + "]"); + AsciiGrid grid = readAsciiGrid(path); + std::remove(path.c_str()); + + CHECK(grid.ncols == 200); + CHECK(grid.nrows == 100); + CHECK(grid.cellsize == doctest::Approx(10.)); + REQUIRE(grid.rows.size() == grid.nrows); + + /* The earliest cell is where the fire started. */ + size_t bestRow = 0, bestCol = 0; + double earliest = std::numeric_limits::infinity(); + for (size_t r = 0; r < grid.nrows; r++) { + for (size_t c = 0; c < grid.ncols; c++) { + double t = std::stod(grid.rows[r][c]); + if (t < earliest) { + earliest = t; + bestRow = r; + bestCol = c; + } + } + } + double x = grid.xll + (bestCol + 0.5) * grid.cellsize; + double y = grid.yll + (grid.nrows - bestRow - 0.5) * grid.cellsize; + CHECK(x == doctest::Approx(300.).epsilon(0.1)); + CHECK(y == doctest::Approx(800.).epsilon(0.1)); + + /* Values round-trip exactly, so no arrival time is rounded. */ + auto matrix = Command::getDomain()->getDataMatrix("arrival_time"); + size_t inexact = 0; + for (size_t r = 0; r < grid.nrows; r++) + for (size_t c = 0; c < grid.ncols; c++) + if (std::stod(grid.rows[r][c]) != matrix[c][grid.nrows - 1 - r]) inexact++; + CHECK(inexact == 0); +} + +} /* TEST_SUITE */