diff --git a/CHANGELOG.md b/CHANGELOG.md index d3143b8b..80a78a45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- Fix the bounding box of a `GeometryCollection` in the TWKB output. The + sub-geometries of a collection are written by their own writers, so their + coordinates never reached the bounding box of the collection, and a + collection was written with an all-zero box. A consumer that filters a + TWKB stream by its bounding boxes never found a collection. + - Fix quadratic time and memory (in the nesting depth) when building nested `GeometryCollection`s, including when parsing them from WKB, WKT, GeoJSON and TWKB. diff --git a/geom/twkb_test.go b/geom/twkb_test.go index 8ecc3cf7..5c8e37f5 100644 --- a/geom/twkb_test.go +++ b/geom/twkb_test.go @@ -342,6 +342,27 @@ var TWKBTestCases = []struct { hasIDList: true, listedIDs: []int64{0, 1}, }, + { + description: "geometry collection with bbox", + twkbHex: "0701010003000101000103", + wkt: "GEOMETRYCOLLECTION(POINT(-1 -2))", + hasBBox: true, + listedBBox: [2]string{"POINT(-1 -2)", "POINT(-1 -2)"}, + }, + { + description: "geometry collection with bbox widened on both sides by a later child", + twkbHex: "0701001400140201000a0a02000200001414", + wkt: "GEOMETRYCOLLECTION(POINT(5 5),LINESTRING(0 0,10 10))", + hasBBox: true, + listedBBox: [2]string{"POINT(0 0)", "POINT(10 10)"}, + }, + { + description: "nested geometry collection with bbox", + twkbHex: "07010004000402010002020700020100000001000404", + wkt: "GEOMETRYCOLLECTION(POINT(1 1),GEOMETRYCOLLECTION(POINT(0 0),POINT(2 2)))", + hasBBox: true, + listedBBox: [2]string{"POINT(0 0)", "POINT(2 2)"}, + }, } func TestTWKBUnmarshalMarshalValid(t *testing.T) { diff --git a/geom/twkb_write.go b/geom/twkb_write.go index e27a4aea..cdf4e4f8 100644 --- a/geom/twkb_write.go +++ b/geom/twkb_write.go @@ -448,12 +448,32 @@ func (w *twkbWriter) writeGeometryCollection(gc GeometryCollection) error { if err := subWriter.writeGeometry(g); err != nil { return err } + w.widenBBox(subWriter) subTWKB := subWriter.formTWKB() w.twkbContents = append(w.twkbContents, subTWKB...) } return nil } +// widenBBox widens the bounding box of the writer with the bounding box of +// the given writer. The sub-geometries of a collection are written by their +// own writers, so their coordinates do not reach the box of the collection +// otherwise. +func (w *twkbWriter) widenBBox(other *twkbWriter) { + if !other.bboxValid { + return + } + for d := 0; d < w.dimensions; d++ { + if !w.bboxValid || other.bboxMin[d] < w.bboxMin[d] { + w.bboxMin[d] = other.bboxMin[d] + } + if !w.bboxValid || other.bboxMax[d] > w.bboxMax[d] { + w.bboxMax[d] = other.bboxMax[d] + } + } + w.bboxValid = true +} + func (w *twkbWriter) writeTypeAndPrecision(kind twkbGeometryType) { w.kind = kind w.writeHeaderByte(byte(encodeZigZagInt64(int64(w.precXY))<<4) | byte(w.kind))