Search code examples
c#nettopologysuite

NetTopologySuite said that geometry is not valid, but Sql Server said that it's valid


I have polygon:

polygon((0 0, 1 0.1, 1 1, 0.5 1, 0.5 1.5, 1 1, 1.5 1.5, 1.5 1, 1 1, 1.5 0.5, 1 0.1, 2 0, 2 2,0 2, 0 0))

enter image description here

For sure it's not looks normal, but Sql Server 2017 said that it's valid.
But when i tried to read it with NTE it's say that it is not valid. Here is simple code:

var wkt = @"polygon((0 0, 1 0.1, 1 1, 0.5 1, 0.5 1.5, 1 1, 1.5 1.5, 1.5 1, 1 1, 1.5 0.5, 1 0.1, 2 0, 2 2,0 2, 0 0))";
var wktReader2 = new WKTReader();
var initialGeometry = wktReader2.Read(wkt);
var t = initialGeometry.IsValid;

I tried to 'play' with PrecisionModels but no result. Any advise?


Solution

  • You need to use IsValidOp explicitly and set SelfTouchingRingFormingHoleValid = true:

    var ivo = new NetTopologySuite.Operation.Valid.IsValidOp(initialGeometry);
    ivo.SelfTouchingRingFormingHoleValid = true;
    bool t = ivo.IsValid;
    

    Your polygon only has one ring defining shell and holes, not seperate. To have it valid in NTS the polygon's WKT would be

    POLYGON ((0 0, 0 2, 2 2, 2 0, 1 0.1, 0 0), (1 0.1, 1.5 0.5, 1 1, 1 0.1), 
             (1 1, 1.5 1, 1.5 1.5, 1 1), (1 1, 0.5 1.5, 0.5 1, 1 1))