diff --git a/libs/MeshKernel/src/Polygon.cpp b/libs/MeshKernel/src/Polygon.cpp index 7821cd5ac..838f869de 100644 --- a/libs/MeshKernel/src/Polygon.cpp +++ b/libs/MeshKernel/src/Polygon.cpp @@ -432,6 +432,21 @@ std::vector meshkernel::Polygon::Refine(const size_t startInd std::vector meshkernel::Polygon::LinearRefine(const size_t startIndex, const size_t endIndex) const { + + if (startIndex >= m_nodes.size()) + { + throw ConstraintError("The start index is greater than the number of points in the outer polygon: {} >= {}.", + startIndex, + m_nodes.size()); + } + + if (endIndex >= m_nodes.size()) + { + throw ConstraintError("The end index is greater than the number of points in the outer polygon: {} >= {}.", + startIndex, + m_nodes.size()); + } + if (startIndex == endIndex) { return m_nodes; diff --git a/libs/MeshKernel/tests/src/PolygonsTests.cpp b/libs/MeshKernel/tests/src/PolygonsTests.cpp index 923df61e1..70449915b 100644 --- a/libs/MeshKernel/tests/src/PolygonsTests.cpp +++ b/libs/MeshKernel/tests/src/PolygonsTests.cpp @@ -994,6 +994,36 @@ TEST(Polygons, BasicLinearRefinePolygon) } } +TEST(Polygons, LinearRefinePolygonSameStartEnd) +{ + // Prepare + std::vector nodes; + + nodes.push_back({0.0, 10.0}); + nodes.push_back({1.0, 10.0}); + nodes.push_back({3.0, 10.0}); + nodes.push_back({11.0, 10.0}); + nodes.push_back({11.0, 0.0}); + nodes.push_back({0.0, 0.0}); + nodes.push_back({0.0, 10.0}); + + std::vector expected(nodes); + + meshkernel::Polygons polygons(nodes, meshkernel::Projection::cartesian); + + // Execute + const auto refinedPolygon = polygons.LinearRefinePolygon(0, 1, 1); + + ASSERT_EQ(expected.size(), refinedPolygon.size()); + constexpr double tolerance = 1.0e-8; + + for (size_t i = 0; i < refinedPolygon.size(); ++i) + { + EXPECT_NEAR(expected[i].x, refinedPolygon[i].x, tolerance); + EXPECT_NEAR(expected[i].y, refinedPolygon[i].y, tolerance); + } +} + TEST(Polygons, LinearRefinePolygonSameNodes) { // Prepare @@ -1061,3 +1091,26 @@ TEST(Polygons, LinearRefinePolygonStartGtEnd) EXPECT_NEAR(expected[i].y, refinedPolygon[i].y, tolerance); } } + +TEST(Polygons, LinearRefinePolygonOutOfBoundsCheck) +{ + // Prepare + std::vector nodes; + + nodes.push_back({0.0, 10.0}); + nodes.push_back({1.0, 10.0}); + nodes.push_back({3.0, 10.0}); + nodes.push_back({11.0, 10.0}); + nodes.push_back({11.0, 0.0}); + nodes.push_back({0.0, 0.0}); + nodes.push_back({0.0, 10.0}); + + meshkernel::Polygons polygons(nodes, meshkernel::Projection::cartesian); + + // polygon index incorrect + EXPECT_THROW(auto refinedPolygon = polygons.LinearRefinePolygon(1, 1, 4), meshkernel::ConstraintError); + // polygon start node index incorrect + EXPECT_THROW(auto refinedPolygon = polygons.LinearRefinePolygon(0, 8, 1), meshkernel::ConstraintError); + // polygon end node index incorrect + EXPECT_THROW(auto refinedPolygon = polygons.LinearRefinePolygon(0, 1, 9), meshkernel::ConstraintError); +}