Debian Codegraph @

src/main/org/h2/util/geometry/EWKBUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util.geometry;
7
8 import static org.h2.util.geometry.GeometryUtils.DIMENSION_SYSTEM_XYM;
9 import static org.h2.util.geometry.GeometryUtils.DIMENSION_SYSTEM_XYZ;
10 import static org.h2.util.geometry.GeometryUtils.DIMENSION_SYSTEM_XYZM;
11 import static org.h2.util.geometry.GeometryUtils.GEOMETRY_COLLECTION;
12 import static org.h2.util.geometry.GeometryUtils.LINE_STRING;
13 import static org.h2.util.geometry.GeometryUtils.MAX_X;
14 import static org.h2.util.geometry.GeometryUtils.MAX_Y;
15 import static org.h2.util.geometry.GeometryUtils.MIN_X;
16 import static org.h2.util.geometry.GeometryUtils.MIN_Y;
17 import static org.h2.util.geometry.GeometryUtils.MULTI_LINE_STRING;
18 import static org.h2.util.geometry.GeometryUtils.MULTI_POINT;
19 import static org.h2.util.geometry.GeometryUtils.MULTI_POLYGON;
20 import static org.h2.util.geometry.GeometryUtils.POINT;
21 import static org.h2.util.geometry.GeometryUtils.POLYGON;
22 import static org.h2.util.geometry.GeometryUtils.checkFinite;
23 import static org.h2.util.geometry.GeometryUtils.toCanonicalDouble;
24
25 import java.io.ByteArrayOutputStream;
26
27 import org.h2.util.Bits;
28 import org.h2.util.StringUtils;
29 import org.h2.util.geometry.GeometryUtils.Target;
30
31 /**
32 * EWKB format support for GEOMETRY data type.
33 *
34 * <p>
35 * This class provides limited support of EWKB. EWKB is based on Well-known
36 * Binary Representation (WKB) from OGC 06-103r4 and includes additional PostGIS
37 * extensions. This class can read dimension system marks in both OGC WKB and
38 * EWKB formats, but always writes them in EWKB format. SRID support from EWKB
39 * is implemented. As an addition POINT EMPTY is stored with NaN values as
40 * specified in <a href="https://www.geopackage.org/spec/">OGC 12-128r15</a>.
41 * </p>
42 */
43 public final class EWKBUtils {
44
45 /**
46 * Converter output target that writes a EWKB.
47 */
48 public static final class EWKBTarget extends Target {
49
50 private final ByteArrayOutputStream output;
51
52 private final int dimensionSystem;
53
54 private final byte[] buf = new byte[8];
55
56 private int type;
57
58 private int srid;
59
60 /**
61 * Creates a new EWKB output target.
62 *
63 * @param output
64 * output stream
65 * @param dimensionSystem
66 * dimension system to use
67 */
68 public EWKBTarget(ByteArrayOutputStream output, int dimensionSystem) {
69 this.output = output;
70 this.dimensionSystem = dimensionSystem;
71 }
72
73 @Override
74 protected void init(int srid) {
75 this.srid = srid;
76 }
77
78 @Override
79 protected void startPoint() {
80 writeHeader(POINT);
81 }
82
83 @Override
84 protected void startLineString(int numPoints) {
85 writeHeader(LINE_STRING);
86 writeInt(numPoints);
87 }
88
89 @Override
90 protected void startPolygon(int numInner, int numPoints) {
91 writeHeader(POLYGON);
92 if (numInner == 0 && numPoints == 0) {
93 /*
94 * Representation of POLYGON EMPTY is not defined is
95 * specification. We store it as a polygon with 0 rings, as
96 * PostGIS does.
97 */
98 writeInt(0);
99 } else {
100 writeInt(numInner + 1);
101 writeInt(numPoints);
102 }
103 }
104
105 @Override
106 protected void startPolygonInner(int numInner) {
107 writeInt(numInner);
108 }
109
110 @Override
111 protected void startCollection(int type, int numItems) {
112 writeHeader(type);
113 writeInt(numItems);
114 }
115
116 private void writeHeader(int type) {
117 this.type = type;
118 switch (dimensionSystem) {
119 case DIMENSION_SYSTEM_XYZ:
120 type |= EWKB_Z;
121 break;
122 case DIMENSION_SYSTEM_XYZM:
123 type |= EWKB_Z;
124 //$FALL-THROUGH$
125 case DIMENSION_SYSTEM_XYM:
126 type |= EWKB_M;
127 }
128 if (srid != 0) {
129 type |= EWKB_SRID;
130 }
131 output.write(0);
132 writeInt(type);
133 if (srid != 0) {
134 writeInt(srid);
135 // Never write SRID in inner objects
136 srid = 0;
137 }
138 }
139
140 @Override
141 protected Target startCollectionItem(int index, int total) {
142 return this;
143 }
144
145 @Override
146 protected void addCoordinate(double x, double y, double z, double m, int index, int total) {
147 boolean check = type != POINT || !Double.isNaN(x) || !Double.isNaN(y) || !Double.isNaN(z)
148 || !Double.isNaN(m);
149 if (check) {
150 checkFinite(x);
151 checkFinite(y);
152 }
153 writeDouble(x);
154 writeDouble(y);
155 if ((dimensionSystem & DIMENSION_SYSTEM_XYZ) != 0) {
156 writeDouble(check ? checkFinite(z) : z);
157 } else if (check && !Double.isNaN(z)) {
158 throw new IllegalArgumentException();
159 }
160 if ((dimensionSystem & DIMENSION_SYSTEM_XYM) != 0) {
161 writeDouble(check ? checkFinite(m) : m);
162 } else if (check && !Double.isNaN(m)) {
163 throw new IllegalArgumentException();
164 }
165 }
166
167 private void writeInt(int v) {
168 Bits.writeInt(buf, 0, v);
169 output.write(buf, 0, 4);
170 }
171
172 private void writeDouble(double v) {
173 v = toCanonicalDouble(v);
174 Bits.writeDouble(buf, 0, v);
175 output.write(buf, 0, 8);
176 }
177
178 }
179
180 /**
181 * Helper source object for EWKB reading.
182 */
183 private static final class EWKBSource {
184 private final byte[] ewkb;
185
186 private int offset;
187
188 /**
189 * Whether current byte order is big-endian.
190 */
191 boolean bigEndian;
192
193 /**
194 * Creates new instance of EWKB source.
195 *
196 * @param ewkb
197 * EWKB
198 */
199 EWKBSource(byte[] ewkb) {
200 this.ewkb = ewkb;
201 }
202
203 /**
204 * Reads one byte.
205 *
206 * @return next byte
207 */
208 byte readByte() {
209 return ewkb[offset++];
210 }
211
212 /**
213 * Reads a 32-bit integer using current byte order.
214 *
215 * @return next 32-bit integer
216 */
217 int readInt() {
218 int result = bigEndian ? Bits.readInt(ewkb, offset) : Bits.readIntLE(ewkb, offset);
219 offset += 4;
220 return result;
221 }
222
223 /**
224 * Reads a 64-bit floating point using current byte order.
225 *
226 * @return next 64-bit floating point
227 */
228 double readCoordinate() {
229 double v = bigEndian ? Bits.readDouble(ewkb, offset) : Bits.readDoubleLE(ewkb, offset);
230 offset += 8;
231 return toCanonicalDouble(v);
232 }
233
234 @Override
235 public String toString() {
236 String s = StringUtils.convertBytesToHex(ewkb);
237 int idx = offset * 2;
238 return new StringBuilder(s.length() + 3).append(s, 0, idx).append("<*>").append(s, idx, s.length())
239 .toString();
240 }
241
242 }
243
244 /**
245 * Geometry type mask that indicates presence of dimension Z.
246 */
247 public static final int EWKB_Z = 0x8000_0000;
248
249 /**
250 * Geometry type mask that indicates presence of dimension M.
251 */
252 public static final int EWKB_M = 0x4000_0000;
253
254 /**
255 * Geometry type mask that indicates presence of SRID.
256 */
257 public static final int EWKB_SRID = 0x2000_0000;
258
259 /**
260 * Converts any supported EWKB to EWKB representation that is used by this
261 * class. Reduces dimension system to minimal possible and uses EWKB flags
262 * for dimension system indication. May also perform other changes.
263 *
264 * @param ewkb
265 * source EWKB
266 * @return canonical EWKB, may be the same as the source
267 */
268 public static byte[] ewkb2ewkb(byte[] ewkb) {
269 return ewkb2ewkb(ewkb, getDimensionSystem(ewkb));
270 }
271
272 /**
273 * Converts any supported EWKB to EWKB representation that is used by this
274 * class. Reduces dimension system to minimal possible and uses EWKB flags
275 * for dimension system indication. May also perform other changes.
276 *
277 * @param ewkb
278 * source EWKB
279 * @param dimensionSystem
280 * dimension system
281 * @return canonical EWKB, may be the same as the source
282 */
283 public static byte[] ewkb2ewkb(byte[] ewkb, int dimensionSystem) {
284 ByteArrayOutputStream output = new ByteArrayOutputStream();
285 EWKBTarget target = new EWKBTarget(output, dimensionSystem);
286 parseEWKB(ewkb, target);
287 return output.toByteArray();
288 }
289
290 /**
291 * Parses a EWKB.
292 *
293 * @param ewkb
294 * EWKB representation
295 * @param target
296 * output target
297 */
298 public static void parseEWKB(byte[] ewkb, Target target) {
299 try {
300 parseEWKB(new EWKBSource(ewkb), target, 0);
301 } catch (ArrayIndexOutOfBoundsException e) {
302 throw new IllegalArgumentException();
303 }
304 }
305
306 /**
307 * Converts geometry type with flags to a dimension system.
308 *
309 * @param type
310 * geometry type with flags
311 * @return dimension system
312 */
313 public static int type2dimensionSystem(int type) {
314 // PostGIS extensions
315 boolean useZ = (type & EWKB_Z) != 0;
316 boolean useM = (type & EWKB_M) != 0;
317 // OGC 06-103r4
318 type &= 0xffff;
319 switch (type / 1_000) {
320 case DIMENSION_SYSTEM_XYZ:
321 useZ = true;
322 break;
323 case DIMENSION_SYSTEM_XYZM:
324 useZ = true;
325 //$FALL-THROUGH$
326 case DIMENSION_SYSTEM_XYM:
327 useM = true;
328 }
329 return (useZ ? DIMENSION_SYSTEM_XYZ : 0) | (useM ? DIMENSION_SYSTEM_XYM : 0);
330 }
331
332 /**
333 * Parses a EWKB.
334 *
335 * @param source
336 * EWKB source
337 * @param target
338 * output target
339 * @param parentType
340 * type of parent geometry collection, or 0 for the root geometry
341 */
342 private static void parseEWKB(EWKBSource source, Target target, int parentType) {
343 // Read byte order of a next geometry
344 switch (source.readByte()) {
345 case 0:
346 source.bigEndian = true;
347 break;
348 case 1:
349 source.bigEndian = false;
350 break;
351 default:
352 throw new IllegalArgumentException();
353 }
354 // Type contains type of a geometry and additional flags
355 int type = source.readInt();
356 // PostGIS extensions
357 boolean useZ = (type & EWKB_Z) != 0;
358 boolean useM = (type & EWKB_M) != 0;
359 int srid = (type & EWKB_SRID) != 0 ? source.readInt() : 0;
360 // Use only top-level SRID
361 if (parentType == 0) {
362 target.init(srid);
363 }
364 // OGC 06-103r4
365 type &= 0xffff;
366 switch (type / 1_000) {
367 case DIMENSION_SYSTEM_XYZ:
368 useZ = true;
369 break;
370 case DIMENSION_SYSTEM_XYZM:
371 useZ = true;
372 //$FALL-THROUGH$
373 case DIMENSION_SYSTEM_XYM:
374 useM = true;
375 }
376 target.dimensionSystem((useZ ? DIMENSION_SYSTEM_XYZ : 0) | (useM ? DIMENSION_SYSTEM_XYM : 0));
377 type %= 1_000;
378 switch (type) {
379 case POINT:
380 if (parentType != 0 && parentType != MULTI_POINT && parentType != GEOMETRY_COLLECTION) {
381 throw new IllegalArgumentException();
382 }
383 target.startPoint();
384 addCoordinate(source, target, useZ, useM, 0, 1);
385 break;
386 case LINE_STRING: {
387 if (parentType != 0 && parentType != MULTI_LINE_STRING && parentType != GEOMETRY_COLLECTION) {
388 throw new IllegalArgumentException();
389 }
390 int numPoints = source.readInt();
391 if (numPoints < 0 || numPoints == 1) {
392 throw new IllegalArgumentException();
393 }
394 target.startLineString(numPoints);
395 for (int i = 0; i < numPoints; i++) {
396 addCoordinate(source, target, useZ, useM, i, numPoints);
397 }
398 break;
399 }
400 case POLYGON: {
401 if (parentType != 0 && parentType != MULTI_POLYGON && parentType != GEOMETRY_COLLECTION) {
402 throw new IllegalArgumentException();
403 }
404 int numRings = source.readInt();
405 if (numRings == 0) {
406 target.startPolygon(0, 0);
407 break;
408 } else if (numRings < 0) {
409 throw new IllegalArgumentException();
410 }
411 numRings--;
412 int size = source.readInt();
413 // Size may be 0 (EMPTY) or 4+
414 if (size < 0 || size >= 1 && size <= 3) {
415 throw new IllegalArgumentException();
416 }
417 if (size == 0 && numRings > 0) {
418 throw new IllegalArgumentException();
419 }
420 target.startPolygon(numRings, size);
421 if (size > 0) {
422 addRing(source, target, useZ, useM, size);
423 for (int i = 0; i < numRings; i++) {
424 size = source.readInt();
425 // Size may be 0 (EMPTY) or 4+
426 if (size < 0 || size >= 1 && size <= 3) {
427 throw new IllegalArgumentException();
428 }
429 target.startPolygonInner(size);
430 addRing(source, target, useZ, useM, size);
431 }
432 target.endNonEmptyPolygon();
433 }
434 break;
435 }
436 case MULTI_POINT:
437 case MULTI_LINE_STRING:
438 case MULTI_POLYGON:
439 case GEOMETRY_COLLECTION: {
440 if (parentType != 0 && parentType != GEOMETRY_COLLECTION) {
441 throw new IllegalArgumentException();
442 }
443 int numItems = source.readInt();
444 if (numItems < 0) {
445 throw new IllegalArgumentException();
446 }
447 target.startCollection(type, numItems);
448 for (int i = 0; i < numItems; i++) {
449 Target innerTarget = target.startCollectionItem(i, numItems);
450 parseEWKB(source, innerTarget, type);
451 target.endCollectionItem(innerTarget, type, i, numItems);
452 }
453 break;
454 }
455 default:
456 throw new IllegalArgumentException();
457 }
458 target.endObject(type);
459 }
460
461 private static void addRing(EWKBSource source, Target target, boolean useZ, boolean useM, int size) {
462 // 0 or 4+ are valid
463 if (size >= 4) {
464 double startX = source.readCoordinate(), startY = source.readCoordinate();
465 target.addCoordinate(startX, startY, //
466 useZ ? source.readCoordinate() : Double.NaN, useM ? source.readCoordinate() : Double.NaN, //
467 0, size);
468 for (int i = 1; i < size - 1; i++) {
469 addCoordinate(source, target, useZ, useM, i, size);
470 }
471 double endX = source.readCoordinate(), endY = source.readCoordinate();
472 /*
473 * TODO OGC 06-103r4 determines points as equal if they have the
474 * same X and Y coordinates. Should we check Z and M here too?
475 */
476 if (startX != endX || startY != endY) {
477 throw new IllegalArgumentException();
478 }
479 target.addCoordinate(endX, endY, //
480 useZ ? source.readCoordinate() : Double.NaN, useM ? source.readCoordinate() : Double.NaN, //
481 size - 1, size);
482 }
483 }
484
485 private static void addCoordinate(EWKBSource source, Target target, boolean useZ, boolean useM, int index,
486 int total) {
487 target.addCoordinate(source.readCoordinate(), source.readCoordinate(),
488 useZ ? source.readCoordinate() : Double.NaN, useM ? source.readCoordinate() : Double.NaN, //
489 index, total);
490 }
491
492 /**
493 * Reads the dimension system from EWKB.
494 *
495 * @param ewkb
496 * EWKB
497 * @return the dimension system
498 */
499 public static int getDimensionSystem(byte[] ewkb) {
500 EWKBSource source = new EWKBSource(ewkb);
501 // Read byte order of a next geometry
502 switch (source.readByte()) {
503 case 0:
504 source.bigEndian = true;
505 break;
506 case 1:
507 source.bigEndian = false;
508 break;
509 default:
510 throw new IllegalArgumentException();
511 }
512 return type2dimensionSystem(source.readInt());
513 }
514
515 /**
516 * Converts an envelope to a WKB.
517 *
518 * @param envelope
519 * envelope, or null
520 * @return WKB, or null
521 */
522 public static byte[] envelope2wkb(double[] envelope) {
523 if (envelope == null) {
524 return null;
525 }
526 byte[] result;
527 double minX = envelope[MIN_X], maxX = envelope[MAX_X], minY = envelope[MIN_Y], maxY = envelope[MAX_Y];
528 if (minX == maxX && minY == maxY) {
529 result = new byte[21];
530 result[4] = POINT;
531 Bits.writeDouble(result, 5, minX);
532 Bits.writeDouble(result, 13, minY);
533 } else if (minX == maxX || minY == maxY) {
534 result = new byte[41];
535 result[4] = LINE_STRING;
536 result[8] = 2;
537 Bits.writeDouble(result, 9, minX);
538 Bits.writeDouble(result, 17, minY);
539 Bits.writeDouble(result, 25, maxX);
540 Bits.writeDouble(result, 33, maxY);
541 } else {
542 result = new byte[93];
543 result[4] = POLYGON;
544 result[8] = 1;
545 result[12] = 5;
546 Bits.writeDouble(result, 13, minX);
547 Bits.writeDouble(result, 21, minY);
548 Bits.writeDouble(result, 29, minX);
549 Bits.writeDouble(result, 37, maxY);
550 Bits.writeDouble(result, 45, maxX);
551 Bits.writeDouble(result, 53, maxY);
552 Bits.writeDouble(result, 61, maxX);
553 Bits.writeDouble(result, 69, minY);
554 Bits.writeDouble(result, 77, minX);
555 Bits.writeDouble(result, 85, minY);
556 }
557 return result;
558 }
559
560 private EWKBUtils() {
561 }
562
563 }