7
mirror of https://gitlab.com/kicad/code/kicad.git synced 2025-04-18 16:09:18 +00:00

Kimath: Squared distance can't be negative

Fixes https://gitlab.com/kicad/code/kicad/-/issues/18473
This commit is contained in:
Lucas Dumont 2024-08-16 20:37:49 +02:00 committed by Seth Hillbrand
parent 00bbe4dbc6
commit f3bbf2b7bd
2 changed files with 19 additions and 1 deletions
libs/kimath/src/geometry
qa/tests/libs/kimath/geometry

View File

@ -412,7 +412,16 @@ SEG::ecoord SEG::SquaredDistance( const VECTOR2I& aP ) const
if( e >= f )
return VECTOR2L( aP.x - B.x, aP.y - B.y ).SquaredEuclideanNorm();
return KiROUND<double, ecoord>( ap.SquaredEuclideanNorm() - ( double( e ) * e ) / f );
const double g = ( double( e ) * e ) / f;
//Squared distance can't be negative
if( g > ap.SquaredEuclideanNorm() )
{
return (ecoord) std::numeric_limits<std::int32_t>::max()
* std::numeric_limits<std::int32_t>::max();
}
return KiROUND<double, ecoord>( ap.SquaredEuclideanNorm() - g );
}

View File

@ -103,6 +103,9 @@ bool SegDistanceCorrect( const SEG& aSegA, const SEG& aSegB, int aExp )
*/
bool SegVecDistanceCorrect( const SEG& aSeg, const VECTOR2I& aVec, int aExp )
{
const SEG::ecoord squaredDistance = aSeg.SquaredDistance( aVec );
BOOST_REQUIRE( std::signbit( squaredDistance ) == false );
const int dist = aSeg.Distance( aVec );
bool ok = ( dist == aExp );
@ -342,6 +345,12 @@ static const std::vector<SEG_VECTOR_DISTANCE_CASE> seg_vec_dist_cases = {
{ 1000 + 200, 200 },
282, // sqrt(200^2 + 200^2) = 282.8, rounded to nearest
},
{
"Issue 18473 (distance negative)",
{ { 187360000, 42510000 }, { 105796472, 42510000 } },
{ 106645000, 42510000 },
std::numeric_limits<std::int32_t>::max(), // maximal distance
}
};
// clang-format on