Compare commits

..
13 Commits
Author SHA1 Message Date
Erica Fischer a34f1ec39e Clip label spirals to the feature bounds 2022-10-07 16:05:08 -07:00
Erica Fischer 7f5f9c775d Checkpoint work on spiral labels 2022-10-07 15:34:13 -07:00
Erica Fischer 75c6abfbdd Revert "Use a label point for the general representative point for polygons"
This reverts commit 2261adf05e.
2022-10-07 14:09:58 -07:00
Erica Fischer 2261adf05e Use a label point for the general representative point for polygons
(Skipping the iteration to find one that is as far as possible from
the borders)

This makes the labels look better in many cases (like France at z1)
but unfortunately ripples into changing the sequence of polygons in
many tests, so the diff is big.
2022-10-07 12:11:12 -07:00
Erica Fischer 2f0c9bf9c8 Checkerboard which tiles labels are generated in, to reduce adjacency 2022-10-07 11:00:09 -07:00
Erica Fischer c34348218f Try a little harder to find an optimal label point 2022-10-06 13:05:38 -07:00
Erica Fischer ffd07befce Don't choose a label point that is too close to a border 2022-10-06 11:46:10 -07:00
Erica Fischer 7127f8af97 If the label point isn't within the polygon, find one that is 2022-10-06 11:27:44 -07:00
Erica Fischer dd43a8d79a Use Turf's center-of-mass algorithm for polygon label points 2022-10-05 19:02:30 -07:00
Erica Fischer ce54668d7c Add --order-smallest-first and --order-largest-first options 2022-10-05 10:43:10 -07:00
Erica Fischer daf5992e3b Revert "Change all these places where I said "extent" but really meant "area""
This reverts commit 403828d2f7.
2022-10-04 16:24:25 -07:00
Erica Fischer 403828d2f7 Change all these places where I said "extent" but really meant "area" 2022-10-04 16:12:33 -07:00
Erica Fischer 1885f989bf Add an option to generate label points in place of polygons 2022-10-04 16:02:31 -07:00
28 changed files with 786 additions and 1864 deletions
-14
View File
@@ -1,21 +1,7 @@
## 2.11.0
* Change sqlite3 schema to deduplicate identical tiles
* Limit guessed maxzoom to avoid spending too many tiles on polygon fill
## 2.10.0
* Upgrade flatbuffers version
## 2.9.1
* Do label generation after simplification, not before.
## 2.9.0
* Add an option to generate label points in place of polygons
* Add --order-smallest-first and --order-largest-first options
* When tiny polygons are being aggregated into dust, keep the attributes of the largest.
## 2.8.1
-2
View File
@@ -19,5 +19,3 @@
#define EXIT_UNLINK 118
#define EXIT_UTF8 119
#define EXIT_WRITE 120
// avoid 124, 125, 126, 127, 137, which are used by GNU timeout
+16 -28
View File
@@ -138,9 +138,9 @@
#endif
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 22
#define FLATBUFFERS_VERSION_MINOR 9
#define FLATBUFFERS_VERSION_REVISION 29
#define FLATBUFFERS_VERSION_MAJOR 2
#define FLATBUFFERS_VERSION_MINOR 0
#define FLATBUFFERS_VERSION_REVISION 5
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
namespace flatbuffers {
@@ -260,12 +260,9 @@ namespace flatbuffers {
#endif // !FLATBUFFERS_HAS_NEW_STRTOD
#ifndef FLATBUFFERS_LOCALE_INDEPENDENT
// Enable locale independent functions {strtof_l, strtod_l,strtoll_l,
// strtoull_l}.
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || \
(defined(__ANDROID_API__) && __ANDROID_API__>= 21) || \
(defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700)) && \
(!defined(__Fuchsia__) && !defined(__ANDROID_API__))
// Enable locale independent functions {strtof_l, strtod_l,strtoll_l, strtoull_l}.
#if ((defined(_MSC_VER) && _MSC_VER >= 1800) || \
(defined(_XOPEN_VERSION) && (_XOPEN_VERSION>=700)) && (!defined(__ANDROID_API__) || (defined(__ANDROID_API__) && (__ANDROID_API__>=21))))
#define FLATBUFFERS_LOCALE_INDEPENDENT 1
#else
#define FLATBUFFERS_LOCALE_INDEPENDENT 0
@@ -273,14 +270,14 @@ namespace flatbuffers {
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
// Suppress Undefined Behavior Sanitizer (recoverable only). Usage:
// - __suppress_ubsan__("undefined")
// - __suppress_ubsan__("signed-integer-overflow")
// - __supress_ubsan__("undefined")
// - __supress_ubsan__("signed-integer-overflow")
#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7))
#define __suppress_ubsan__(type) __attribute__((no_sanitize(type)))
#define __supress_ubsan__(type) __attribute__((no_sanitize(type)))
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)
#define __suppress_ubsan__(type) __attribute__((no_sanitize_undefined))
#define __supress_ubsan__(type) __attribute__((no_sanitize_undefined))
#else
#define __suppress_ubsan__(type)
#define __supress_ubsan__(type)
#endif
// This is constexpr function used for checking compile-time constants.
@@ -331,17 +328,8 @@ typedef uintmax_t largest_scalar_t;
// In 32bits, this evaluates to 2GB - 1
#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(::flatbuffers::soffset_t) * 8 - 1)) - 1)
// The minimum size buffer that can be a valid flatbuffer.
// Includes the offset to the root table (uoffset_t), the offset to the vtable
// of the root table (soffset_t), the size of the vtable (uint16_t), and the
// size of the referring table (uint16_t).
#define FLATBUFFERS_MIN_BUFFER_SIZE sizeof(uoffset_t) + sizeof(soffset_t) + \
sizeof(uint16_t) + sizeof(uint16_t)
// We support aligning the contents of buffers up to this size.
#ifndef FLATBUFFERS_MAX_ALIGNMENT
#define FLATBUFFERS_MAX_ALIGNMENT 32
#endif
#define FLATBUFFERS_MAX_ALIGNMENT 16
/// @brief The length of a FlatBuffer file header.
static const size_t kFileIdentifierLength = 4;
@@ -413,7 +401,7 @@ template<typename T> T EndianScalar(T t) {
template<typename T>
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
__suppress_ubsan__("alignment")
__supress_ubsan__("alignment")
T ReadScalar(const void *p) {
return EndianScalar(*reinterpret_cast<const T *>(p));
}
@@ -427,13 +415,13 @@ T ReadScalar(const void *p) {
template<typename T>
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
__suppress_ubsan__("alignment")
__supress_ubsan__("alignment")
void WriteScalar(void *p, T t) {
*reinterpret_cast<T *>(p) = EndianScalar(t);
}
template<typename T> struct Offset;
template<typename T> __suppress_ubsan__("alignment") void WriteScalar(void *p, Offset<T> t) {
template<typename T> __supress_ubsan__("alignment") void WriteScalar(void *p, Offset<T> t) {
*reinterpret_cast<uoffset_t *>(p) = EndianScalar(t.o);
}
@@ -444,7 +432,7 @@ template<typename T> __suppress_ubsan__("alignment") void WriteScalar(void *p, O
// Computes how many bytes you'd have to pad to be able to write an
// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
// memory).
__suppress_ubsan__("unsigned-integer-overflow")
__supress_ubsan__("unsigned-integer-overflow")
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
return ((~buf_size) + 1) & (scalar_size - 1);
}
+1 -1
View File
@@ -95,7 +95,7 @@ template<typename T> struct IndirectHelper<const T *> {
}
};
/// @brief Get a pointer to the file_identifier section of the buffer.
/// @brief Get a pointer to the the file_identifier section of the buffer.
/// @return Returns a const char pointer to the start of the file_identifier
/// characters in the buffer. The returned char * has length
/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
+37 -74
View File
@@ -18,7 +18,6 @@
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
#include <functional>
#include <initializer_list>
#include "flatbuffers/allocator.h"
#include "flatbuffers/array.h"
@@ -43,15 +42,14 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) {
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
}
template<typename T, typename Alloc = std::allocator<T>>
template<typename T, typename Alloc>
const T *data(const std::vector<T, Alloc> &v) {
// Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
}
template<typename T, typename Alloc = std::allocator<T>>
T *data(std::vector<T, Alloc> &v) {
template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
// Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
@@ -287,7 +285,9 @@ class FlatBufferBuilder {
FieldLoc fl = { off, field };
buf_.scratch_push_small(fl);
num_field_loc++;
if (field > max_voffset_) { max_voffset_ = field; }
if (field > max_voffset_) {
max_voffset_ = field;
}
}
// Like PushElement, but additionally tracks the field this represents.
@@ -358,7 +358,7 @@ class FlatBufferBuilder {
// If you get this assert, a corresponding StartTable wasn't called.
FLATBUFFERS_ASSERT(nested);
// Write the vtable offset, which is the start of any Table.
// We fill its value later.
// We fill it's value later.
auto vtableoffsetloc = PushElement<soffset_t>(0);
// Write a vtable, which consists entirely of voffset_t elements.
// It starts with the number of offsets, followed by a type id, followed
@@ -443,13 +443,12 @@ class FlatBufferBuilder {
// Aligns such that when "len" bytes are written, an object can be written
// after it with "alignment" without padding.
void PreAlign(size_t len, size_t alignment) {
if (len == 0) return;
TrackMinAlign(alignment);
buf_.fill(PaddingBytes(GetSize() + len, alignment));
}
template<typename T> void PreAlign(size_t len) {
AssertScalarT<T>();
PreAlign(len, AlignOf<T>());
PreAlign(len, sizeof(T));
}
/// @endcond
@@ -579,7 +578,7 @@ class FlatBufferBuilder {
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
Offset<String> CreateSharedString(const String *str) {
return str ? CreateSharedString(str->c_str(), str->size()) : 0;
return CreateSharedString(str->c_str(), str->size());
}
/// @cond FLATBUFFERS_INTERNAL
@@ -589,15 +588,11 @@ class FlatBufferBuilder {
return PushElement(static_cast<uoffset_t>(len));
}
void StartVector(size_t len, size_t elemsize, size_t alignment) {
void StartVector(size_t len, size_t elemsize) {
NotNested();
nested = true;
PreAlign<uoffset_t>(len * elemsize);
PreAlign(len * elemsize, alignment); // Just in case elemsize > uoffset_t.
}
template<typename T> void StartVector(size_t len) {
return StartVector(len, sizeof(T), AlignOf<T>());
PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
}
// Call this right before StartVector/CreateVector if you want to force the
@@ -606,14 +601,12 @@ class FlatBufferBuilder {
// This is useful when storing a nested_flatbuffer in a vector of bytes,
// or when storing SIMD floats, etc.
void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
if (len == 0) return;
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
PreAlign(len * elemsize, alignment);
}
// Similar to ForceVectorAlignment but for String fields.
void ForceStringAlignment(size_t len, size_t alignment) {
if (len == 0) return;
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
PreAlign((len + 1) * sizeof(char), alignment);
}
@@ -631,7 +624,7 @@ class FlatBufferBuilder {
// If this assert hits, you're specifying a template argument that is
// causing the wrong overload to be selected, remove it.
AssertScalarT<T>();
StartVector<T>(len);
StartVector(len, sizeof(T));
if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
// clang-format off
#if FLATBUFFERS_LITTLEENDIAN
@@ -649,30 +642,9 @@ class FlatBufferBuilder {
return Offset<Vector<T>>(EndVector(len));
}
/// @brief Serialize an array like object into a FlatBuffer `vector`.
/// @tparam T The data type of the array elements.
/// @tparam C The type of the array.
/// @param[in] array A reference to an array like object of type `T` to
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, class C> Offset<Vector<T>> CreateVector(const C &array) {
return CreateVector(array.data(), array.size());
}
/// @brief Serialize an initializer list into a FlatBuffer `vector`.
/// @tparam T The data type of the initializer list elements.
/// @param[in] v The value of the initializer list.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T>
Offset<Vector<T>> CreateVector(std::initializer_list<T> v) {
return CreateVector(v.begin(), v.size());
}
template<typename T>
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
StartVector<Offset<T>>(len);
StartVector(len, sizeof(Offset<T>));
for (auto i = len; i > 0;) { PushElement(v[--i]); }
return Offset<Vector<Offset<T>>>(EndVector(len));
}
@@ -683,7 +655,7 @@ class FlatBufferBuilder {
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename Alloc = std::allocator<T>>
template<typename T, typename Alloc>
Offset<Vector<T>> CreateVector(const std::vector<T, Alloc> &v) {
return CreateVector(data(v), v.size());
}
@@ -692,7 +664,7 @@ class FlatBufferBuilder {
// an array. Instead, read elements manually.
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
StartVector<uint8_t>(v.size());
StartVector(v.size(), sizeof(uint8_t));
for (auto i = v.size(); i > 0;) {
PushElement(static_cast<uint8_t>(v[--i]));
}
@@ -734,24 +706,21 @@ class FlatBufferBuilder {
return CreateVector(elems);
}
/// @brief Serialize a `std::vector<StringType>` into a FlatBuffer `vector`.
/// whereas StringType is any type that is accepted by the CreateString()
/// overloads.
/// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
/// This is a convenience function for a common case.
/// @param v A const reference to the `std::vector` to serialize into the
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename StringType = std::string,
typename Alloc = std::allocator<StringType>>
template<typename Alloc>
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
const std::vector<StringType, Alloc> &v) {
const std::vector<std::string, Alloc> &v) {
return CreateVectorOfStrings(v.cbegin(), v.cend());
}
/// @brief Serialize a collection of Strings into a FlatBuffer `vector`.
/// This is a convenience function for a common case.
/// @param begin The beginning iterator of the collection
/// @param begin The begining iterator of the collection
/// @param end The ending iterator of the collection
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
@@ -761,12 +730,12 @@ class FlatBufferBuilder {
auto scratch_buffer_usage = size * sizeof(Offset<String>);
// If there is not enough space to store the offsets, there definitely won't
// be enough space to store all the strings. So ensuring space for the
// scratch region is OK, for if it fails, it would have failed later.
// scratch region is OK, for it it fails, it would have failed later.
buf_.ensure_space(scratch_buffer_usage);
for (auto it = begin; it != end; ++it) {
buf_.scratch_push_small(CreateString(*it));
}
StartVector<Offset<String>>(size);
StartVector(size, sizeof(Offset<String>));
for (auto i = 1; i <= size; i++) {
// Note we re-evaluate the buf location each iteration to account for any
// underlying buffer resizing that may occur.
@@ -786,7 +755,7 @@ class FlatBufferBuilder {
/// where the vector is stored.
template<typename T>
Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
StartVector(len * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
if (len > 0) {
PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
}
@@ -872,7 +841,7 @@ class FlatBufferBuilder {
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename Alloc = std::allocator<T>>
template<typename T, typename Alloc>
Offset<Vector<const T *>> CreateVectorOfStructs(
const std::vector<T, Alloc> &v) {
return CreateVectorOfStructs(data(v), v.size());
@@ -888,7 +857,7 @@ class FlatBufferBuilder {
/// to the FlatBuffer struct.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S, typename Alloc = std::allocator<T>>
template<typename T, typename S, typename Alloc>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
const std::vector<S, Alloc> &v, T (*const pack_func)(const S &)) {
return CreateVectorOfNativeStructs<T, S>(data(v), v.size(), pack_func);
@@ -902,7 +871,7 @@ class FlatBufferBuilder {
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S, typename Alloc = std::allocator<S>>
template<typename T, typename S, typename Alloc>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
const std::vector<S, Alloc> &v) {
return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
@@ -923,7 +892,7 @@ class FlatBufferBuilder {
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename Alloc = std::allocator<T>>
template<typename T, typename Alloc>
Offset<Vector<const T *>> CreateVectorOfSortedStructs(
std::vector<T, Alloc> *v) {
return CreateVectorOfSortedStructs(data(*v), v->size());
@@ -937,7 +906,7 @@ class FlatBufferBuilder {
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S, typename Alloc = std::allocator<T>>
template<typename T, typename S, typename Alloc>
Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
std::vector<S, Alloc> *v) {
return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
@@ -953,7 +922,7 @@ class FlatBufferBuilder {
/// where the vector is stored.
template<typename T>
Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
std::stable_sort(v, v + len, StructKeyComparator<T>());
std::sort(v, v + len, StructKeyComparator<T>());
return CreateVectorOfStructs(v, len);
}
@@ -972,7 +941,7 @@ class FlatBufferBuilder {
extern T Pack(const S &);
auto structs = StartVectorOfStructs<T>(len);
for (size_t i = 0; i < len; i++) { structs[i] = Pack(v[i]); }
std::stable_sort(structs, structs + len, StructKeyComparator<T>());
std::sort(structs, structs + len, StructKeyComparator<T>());
return EndVectorOfStructs<T>(len);
}
@@ -1004,7 +973,7 @@ class FlatBufferBuilder {
template<typename T>
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
size_t len) {
std::stable_sort(v, v + len, TableKeyComparator<T>(buf_));
std::sort(v, v + len, TableKeyComparator<T>(buf_));
return CreateVector(v, len);
}
@@ -1015,7 +984,7 @@ class FlatBufferBuilder {
/// offsets to store in the buffer in sorted order.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename Alloc = std::allocator<T>>
template<typename T, typename Alloc>
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
std::vector<Offset<T>, Alloc> *v) {
return CreateVectorOfSortedTables(data(*v), v->size());
@@ -1029,9 +998,9 @@ class FlatBufferBuilder {
/// written to at a later time to serialize the data into a `vector`
/// in the buffer.
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
size_t alignment, uint8_t **buf) {
uint8_t **buf) {
NotNested();
StartVector(len, elemsize, alignment);
StartVector(len, elemsize);
buf_.make_space(len * elemsize);
auto vec_start = GetSize();
auto vec_end = EndVector(len);
@@ -1039,12 +1008,6 @@ class FlatBufferBuilder {
return vec_end;
}
FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]])
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
uint8_t **buf) {
return CreateUninitializedVector(len, elemsize, elemsize, buf);
}
/// @brief Specialized version of `CreateVector` for non-copying use cases.
/// Write the data any time later to the returned buffer pointer `buf`.
/// @tparam T The data type of the data that will be stored in the buffer
@@ -1056,14 +1019,14 @@ class FlatBufferBuilder {
template<typename T>
Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
AssertScalarT<T>();
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
return CreateUninitializedVector(len, sizeof(T),
reinterpret_cast<uint8_t **>(buf));
}
template<typename T>
Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
T **buf) {
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
return CreateUninitializedVector(len, sizeof(T),
reinterpret_cast<uint8_t **>(buf));
}
@@ -1074,7 +1037,7 @@ class FlatBufferBuilder {
Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
AssertScalarT<T>();
AssertScalarT<U>();
StartVector<T>(len);
StartVector(len, sizeof(T));
for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
return Offset<Vector<T>>(EndVector(len));
}
@@ -1111,7 +1074,7 @@ class FlatBufferBuilder {
void SwapBufAllocator(FlatBufferBuilder &other) {
buf_.swap_allocator(other.buf_);
}
/// @brief The length of a FlatBuffer file header.
static const size_t kFileIdentifierLength =
::flatbuffers::kFileIdentifierLength;
@@ -1183,7 +1146,7 @@ class FlatBufferBuilder {
// Allocates space for a vector of structures.
// Must be completed with EndVectorOfStructs().
template<typename T> T *StartVectorOfStructs(size_t vector_size) {
StartVector(vector_size * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
}
+19 -5
View File
@@ -226,13 +226,27 @@ struct TypeTable {
};
// String which identifies the current version of FlatBuffers.
inline const char *flatbuffers_version_string() {
return "FlatBuffers " FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
}
// flatbuffer_version_string is used by Google developers to identify which
// applications uploaded to Google Play are using this library. This allows
// the development team at Google to determine the popularity of the library.
// How it works: Applications that are uploaded to the Google Play Store are
// scanned for this version string. We track which applications are using it
// to measure popularity. You are free to remove it (of course) but we would
// appreciate if you left it in.
// Weak linkage is culled by VS & doesn't work on cygwin.
// clang-format off
#if !defined(_WIN32) && !defined(__CYGWIN__)
extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
volatile __attribute__((weak)) const char *flatbuffer_version_string =
"FlatBuffers "
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
#endif // !defined(_WIN32) && !defined(__CYGWIN__)
#define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
inline E operator | (E lhs, E rhs){\
return E(T(lhs) | T(rhs));\
+44 -45
View File
@@ -26,27 +26,22 @@
#include <memory>
#include <limits>
#ifndef FLATBUFFERS_USE_STD_OPTIONAL
// Detect C++17 compatible compiler.
// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
#if (defined(__cplusplus) && __cplusplus >= 201703L) \
|| (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
#define FLATBUFFERS_USE_STD_OPTIONAL 1
#else
#define FLATBUFFERS_USE_STD_OPTIONAL 0
#endif // (defined(__cplusplus) && __cplusplus >= 201703L) ...
#endif // FLATBUFFERS_USE_STD_OPTIONAL
#if FLATBUFFERS_USE_STD_OPTIONAL
// Detect C++17 compatible compiler.
// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
#if defined(FLATBUFFERS_USE_STD_OPTIONAL) \
|| (defined(__cplusplus) && __cplusplus >= 201703L) \
|| (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L))
#include <optional>
#endif
#ifndef FLATBUFFERS_USE_STD_OPTIONAL
#define FLATBUFFERS_USE_STD_OPTIONAL
#endif
#endif // defined(FLATBUFFERS_USE_STD_OPTIONAL) ...
// The __cpp_lib_span is the predefined feature macro.
#if defined(FLATBUFFERS_USE_STD_SPAN)
#include <span>
#elif defined(__cpp_lib_span) && defined(__has_include)
#if __has_include(<span>)
#include <array>
#include <span>
#define FLATBUFFERS_USE_STD_SPAN
#endif
@@ -133,7 +128,7 @@ namespace flatbuffers {
};
#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
#if FLATBUFFERS_USE_STD_OPTIONAL
#ifdef FLATBUFFERS_USE_STD_OPTIONAL
template<class T>
using Optional = std::optional<T>;
using nullopt_t = std::nullopt_t;
@@ -289,13 +284,13 @@ FLATBUFFERS_CONSTEXPR std::size_t dynamic_extent = static_cast<std::size_t>(-1);
namespace internal {
// This is SFINAE helper class for checking of a common condition:
// > This overload only participates in overload resolution
// > Check whether a pointer to an array of From can be converted
// > to a pointer to an array of To.
// This helper is used for checking of 'From -> const From'.
template<class To, std::size_t Extent, class From, std::size_t N>
struct is_span_convertible {
// > Check whether a pointer to an array of U can be converted
// > to a pointer to an array of E.
// This helper is used for checking of 'U -> const U'.
template<class E, std::size_t Extent, class U, std::size_t N>
struct is_span_convertable {
using type =
typename std::conditional<std::is_convertible<From (*)[], To (*)[]>::value
typename std::conditional<std::is_convertible<U (*)[], E (*)[]>::value
&& (Extent == dynamic_extent || N == Extent),
int, void>::type;
};
@@ -367,9 +362,13 @@ class span FLATBUFFERS_FINAL_CLASS {
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
using Iterator = internal::SpanIterator<T>;
using ConstIterator = internal::SpanIterator<const T>;
Iterator begin() const { return Iterator(data()); }
Iterator end() const { return Iterator(data() + size()); }
ConstIterator cbegin() const { return ConstIterator(data()); }
ConstIterator cend() const { return ConstIterator(data() + size()); }
#endif
// Returns a reference to the idx-th element of the sequence.
@@ -415,7 +414,7 @@ class span FLATBUFFERS_FINAL_CLASS {
// extent == 0 || extent == flatbuffers::dynamic_extent.
// A dummy template argument N is need dependency for SFINAE.
template<std::size_t N = 0,
typename internal::is_span_convertible<element_type, Extent, element_type, (N - N)>::type = 0>
typename internal::is_span_convertable<element_type, Extent, element_type, (N - N)>::type = 0>
FLATBUFFERS_CONSTEXPR_CPP11 span() FLATBUFFERS_NOEXCEPT : data_(nullptr),
count_(0) {
static_assert(extent == 0 || extent == dynamic_extent, "invalid span");
@@ -428,12 +427,12 @@ class span FLATBUFFERS_FINAL_CLASS {
// std::remove_pointer_t<decltype(std::data(arr))>(*)[]
// is convertible to element_type (*)[].
template<std::size_t N,
typename internal::is_span_convertible<element_type, Extent, element_type, N>::type = 0>
typename internal::is_span_convertable<element_type, Extent, element_type, N>::type = 0>
FLATBUFFERS_CONSTEXPR_CPP11 span(element_type (&arr)[N]) FLATBUFFERS_NOEXCEPT
: data_(arr), count_(N) {}
template<class U, std::size_t N,
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
FLATBUFFERS_CONSTEXPR_CPP11 span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
: data_(arr.data()), count_(N) {}
@@ -443,7 +442,7 @@ class span FLATBUFFERS_FINAL_CLASS {
// : data_(arr.data()), count_(N) {}
template<class U, std::size_t N,
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
FLATBUFFERS_CONSTEXPR_CPP11 span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
: data_(arr.data()), count_(N) {}
@@ -453,7 +452,7 @@ class span FLATBUFFERS_FINAL_CLASS {
// if extent == std::dynamic_extent || N == extent is true and U (*)[]
// is convertible to element_type (*)[].
template<class U, std::size_t N,
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
FLATBUFFERS_CONSTEXPR_CPP11 span(const flatbuffers::span<U, N> &s) FLATBUFFERS_NOEXCEPT
: span(s.data(), s.size()) {
}
@@ -463,45 +462,45 @@ class span FLATBUFFERS_FINAL_CLASS {
private:
// This is a naive implementation with 'count_' member even if (Extent != dynamic_extent).
pointer const data_;
size_type count_;
const size_type count_;
};
#endif // defined(FLATBUFFERS_USE_STD_SPAN)
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<ElementType, Extent> make_span(ElementType(&arr)[Extent]) FLATBUFFERS_NOEXCEPT {
return span<ElementType, Extent>(arr);
flatbuffers::span<U, N> make_span(U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
return span<U, N>(arr);
}
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<const ElementType, Extent> make_span(const ElementType(&arr)[Extent]) FLATBUFFERS_NOEXCEPT {
return span<const ElementType, Extent>(arr);
flatbuffers::span<const U, N> make_span(const U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
return span<const U, N>(arr);
}
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<ElementType, Extent> make_span(std::array<ElementType, Extent> &arr) FLATBUFFERS_NOEXCEPT {
return span<ElementType, Extent>(arr);
flatbuffers::span<U, N> make_span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
return span<U, N>(arr);
}
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<const ElementType, Extent> make_span(const std::array<ElementType, Extent> &arr) FLATBUFFERS_NOEXCEPT {
return span<const ElementType, Extent>(arr);
flatbuffers::span<const U, N> make_span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
return span<const U, N>(arr);
}
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<ElementType, dynamic_extent> make_span(ElementType *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
return span<ElementType, dynamic_extent>(first, count);
flatbuffers::span<U, dynamic_extent> make_span(U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
return span<U, dynamic_extent>(first, count);
}
template<class ElementType, std::size_t Extent>
template<class U, std::size_t N>
FLATBUFFERS_CONSTEXPR_CPP11
flatbuffers::span<const ElementType, dynamic_extent> make_span(const ElementType *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
return span<const ElementType, dynamic_extent>(first, count);
flatbuffers::span<const U, dynamic_extent> make_span(const U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
return span<const U, dynamic_extent>(first, count);
}
#endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
+5 -7
View File
@@ -112,22 +112,20 @@ class Table {
// Verify a particular field.
template<typename T>
bool VerifyField(const Verifier &verifier, voffset_t field,
size_t align) const {
bool VerifyField(const Verifier &verifier, voffset_t field) const {
// Calling GetOptionalFieldOffset should be safe now thanks to
// VerifyTable().
auto field_offset = GetOptionalFieldOffset(field);
// Check the actual field.
return !field_offset || verifier.VerifyField<T>(data_, field_offset, align);
return !field_offset || verifier.Verify<T>(data_, field_offset);
}
// VerifyField for required fields.
template<typename T>
bool VerifyFieldRequired(const Verifier &verifier, voffset_t field,
size_t align) const {
bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
return verifier.Check(field_offset != 0) &&
verifier.VerifyField<T>(data_, field_offset, align);
verifier.Verify<T>(data_, field_offset);
}
// Versions for offsets.
@@ -165,4 +163,4 @@ inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
} // namespace flatbuffers
#endif // FLATBUFFERS_TABLE_H_
#endif // FLATBUFFERS_TABLE_H_
+5 -32
View File
@@ -17,20 +17,19 @@
#ifndef FLATBUFFERS_UTIL_H_
#define FLATBUFFERS_UTIL_H_
#include <ctype.h>
#include <errno.h>
#include "flatbuffers/base.h"
#include "flatbuffers/stl_emulation.h"
#ifndef FLATBUFFERS_PREFER_PRINTF
# include <iomanip>
# include <sstream>
#else // FLATBUFFERS_PREFER_PRINTF
# include <float.h>
# include <stdio.h>
#endif // FLATBUFFERS_PREFER_PRINTF
#include <iomanip>
#include <string>
namespace flatbuffers {
@@ -95,7 +94,7 @@ template<typename T> size_t IntToDigitCount(T t) {
// Count a single 0 left of the dot for fractional numbers
if (-1 < t && t < 1) digit_count++;
// Count digits until fractional part
T eps = std::numeric_limits<T>::epsilon();
T eps = std::numeric_limits<float>::epsilon();
while (t <= (-1 + eps) || (1 - eps) <= t) {
t /= 10;
digit_count++;
@@ -255,7 +254,7 @@ inline void strtoval_impl(double *val, const char *str, char **endptr) {
}
// UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
__suppress_ubsan__("float-cast-overflow")
__supress_ubsan__("float-cast-overflow")
inline void strtoval_impl(float *val, const char *str, char **endptr) {
*val = __strtof_impl(str, endptr);
}
@@ -448,9 +447,6 @@ std::string StripPath(const std::string &filepath);
// Strip the last component of the path + separator.
std::string StripFileName(const std::string &filepath);
std::string StripPrefix(const std::string &filepath,
const std::string &prefix_to_remove);
// Concatenates a path with a filename, regardless of whether the path
// ends in a separator or not.
std::string ConCatPathFileName(const std::string &path,
@@ -685,31 +681,8 @@ bool SetGlobalTestLocale(const char *locale_name,
bool ReadEnvironmentVariable(const char *var_name,
std::string *_value = nullptr);
enum class Case {
kUnknown = 0,
// TheQuickBrownFox
kUpperCamel = 1,
// theQuickBrownFox
kLowerCamel = 2,
// the_quick_brown_fox
kSnake = 3,
// THE_QUICK_BROWN_FOX
kScreamingSnake = 4,
// THEQUICKBROWNFOX
kAllUpper = 5,
// thequickbrownfox
kAllLower = 6,
// the-quick-brown-fox
kDasher = 7,
// THEQuiCKBr_ownFox (or whatever you want, we won't change it)
kKeep = 8,
// the_quick_brown_fox123 (as opposed to the_quick_brown_fox_123)
kSnake2 = 9,
};
// Convert the `input` string of case `input_case` to the specified `output_case`.
std::string ConvertCase(const std::string &input, Case output_case,
Case input_case = Case::kSnake);
// MSVC specific: Send all assert reports to STDOUT to prevent CI hangs.
void SetupDefaultCRTReportMode();
} // namespace flatbuffers
-19
View File
@@ -19,7 +19,6 @@
#include "flatbuffers/base.h"
#include "flatbuffers/buffer.h"
#include "flatbuffers/stl_emulation.h"
namespace flatbuffers {
@@ -327,24 +326,6 @@ FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t> make_bytes_span(
return span<const uint8_t>(vec.Data(), vec.size() * sizeof(U));
}
// Convenient helper functions to get a span of any vector, regardless
// of whether it is null or not (the field is not set).
template<class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> *ptr)
FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return ptr ? make_span(*ptr) : span<U>();
}
template<class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U> make_span(
const Vector<U> *ptr) FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return ptr ? make_span(*ptr) : span<const U>();
}
// Represent a vector much like the template above, but in this case we
// don't know what the element types are (used with reflection.h).
class VectorOfAny {
+1 -1
View File
@@ -24,7 +24,7 @@
namespace flatbuffers {
// This is a minimal replication of std::vector<uint8_t> functionality,
// except growing from higher to lower addresses. i.e. push_back() inserts data
// except growing from higher to lower addresses. i.e push_back() inserts data
// in the lowest address in the vector.
// Since this vector leaves the lower part unused, we support a "scratch-pad"
// that can be stored there for temporary data, to share the allocated space.
+67 -114
View File
@@ -18,6 +18,7 @@
#define FLATBUFFERS_VERIFIER_H_
#include "flatbuffers/base.h"
#include "flatbuffers/util.h"
#include "flatbuffers/vector.h"
namespace flatbuffers {
@@ -25,37 +26,21 @@ namespace flatbuffers {
// Helper class to verify the integrity of a FlatBuffer
class Verifier FLATBUFFERS_FINAL_CLASS {
public:
struct Options {
// The maximum nesting of tables and vectors before we call it invalid.
uoffset_t max_depth = 64;
// The maximum number of tables we will verify before we call it invalid.
uoffset_t max_tables = 1000000;
// If true, verify all data is aligned.
bool check_alignment = true;
// If true, run verifier on nested flatbuffers
bool check_nested_flatbuffers = true;
};
explicit Verifier(const uint8_t *const buf, const size_t buf_len,
const Options &opts)
: buf_(buf), size_(buf_len), opts_(opts) {
Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
uoffset_t _max_tables = 1000000, bool _check_alignment = true)
: buf_(buf),
size_(buf_len),
depth_(0),
max_depth_(_max_depth),
num_tables_(0),
max_tables_(_max_tables),
upper_bound_(0),
check_alignment_(_check_alignment) {
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
}
// Deprecated API, please construct with Verifier::Options.
Verifier(const uint8_t *const buf, const size_t buf_len,
const uoffset_t max_depth = 64, const uoffset_t max_tables = 1000000,
const bool check_alignment = true)
: Verifier(buf, buf_len, [&] {
Options opts;
opts.max_depth = max_depth;
opts.max_tables = max_tables;
opts.check_alignment = check_alignment;
return opts;
}()) {}
// Central location where any verification failures register.
bool Check(const bool ok) const {
bool Check(bool ok) const {
// clang-format off
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
FLATBUFFERS_ASSERT(ok);
@@ -69,7 +54,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
}
// Verify any range within the buffer.
bool Verify(const size_t elem, const size_t elem_len) const {
bool Verify(size_t elem, size_t elem_len) const {
// clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
auto upper_bound = elem + elem_len;
@@ -80,52 +65,48 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return Check(elem_len < size_ && elem <= size_ - elem_len);
}
bool VerifyAlignment(const size_t elem, const size_t align) const {
return Check((elem & (align - 1)) == 0 || !opts_.check_alignment);
template<typename T> bool VerifyAlignment(size_t elem) const {
return Check((elem & (sizeof(T) - 1)) == 0 || !check_alignment_);
}
// Verify a range indicated by sizeof(T).
template<typename T> bool Verify(const size_t elem) const {
return VerifyAlignment(elem, sizeof(T)) && Verify(elem, sizeof(T));
template<typename T> bool Verify(size_t elem) const {
return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
}
bool VerifyFromPointer(const uint8_t *const p, const size_t len) {
return Verify(static_cast<size_t>(p - buf_), len);
bool VerifyFromPointer(const uint8_t *p, size_t len) {
auto o = static_cast<size_t>(p - buf_);
return Verify(o, len);
}
// Verify relative to a known-good base pointer.
bool VerifyFieldStruct(const uint8_t *const base, const voffset_t elem_off,
const size_t elem_len, const size_t align) const {
const auto f = static_cast<size_t>(base - buf_) + elem_off;
return VerifyAlignment(f, align) && Verify(f, elem_len);
bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
}
template<typename T>
bool VerifyField(const uint8_t *const base, const voffset_t elem_off,
const size_t align) const {
const auto f = static_cast<size_t>(base - buf_) + elem_off;
return VerifyAlignment(f, align) && Verify(f, sizeof(T));
bool Verify(const uint8_t *base, voffset_t elem_off) const {
return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
}
// Verify a pointer (may be NULL) of a table type.
template<typename T> bool VerifyTable(const T *const table) {
template<typename T> bool VerifyTable(const T *table) {
return !table || table->Verify(*this);
}
// Verify a pointer (may be NULL) of any vector type.
template<typename T> bool VerifyVector(const Vector<T> *const vec) const {
template<typename T> bool VerifyVector(const Vector<T> *vec) const {
return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
sizeof(T));
}
// Verify a pointer (may be NULL) of a vector to struct.
template<typename T>
bool VerifyVector(const Vector<const T *> *const vec) const {
template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
}
// Verify a pointer (may be NULL) to string.
bool VerifyString(const String *const str) const {
bool VerifyString(const String *str) const {
size_t end;
return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
1, &end) &&
@@ -134,24 +115,24 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
}
// Common code between vectors and strings.
bool VerifyVectorOrString(const uint8_t *const vec, const size_t elem_size,
size_t *const end = nullptr) const {
const auto veco = static_cast<size_t>(vec - buf_);
bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
size_t *end = nullptr) const {
auto veco = static_cast<size_t>(vec - buf_);
// Check we can read the size field.
if (!Verify<uoffset_t>(veco)) return false;
// Check the whole array. If this is a string, the byte past the array must
// be 0.
const auto size = ReadScalar<uoffset_t>(vec);
const auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
// Check the whole array. If this is a string, the byte past the array
// must be 0.
auto size = ReadScalar<uoffset_t>(vec);
auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
if (!Check(size < max_elems))
return false; // Protect against byte_size overflowing.
const auto byte_size = sizeof(size) + elem_size * size;
auto byte_size = sizeof(size) + elem_size * size;
if (end) *end = veco + byte_size;
return Verify(veco, byte_size);
}
// Special case for string contents, after the above has been called.
bool VerifyVectorOfStrings(const Vector<Offset<String>> *const vec) const {
bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
if (vec) {
for (uoffset_t i = 0; i < vec->size(); i++) {
if (!VerifyString(vec->Get(i))) return false;
@@ -161,8 +142,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
}
// Special case for table contents, after the above has been called.
template<typename T>
bool VerifyVectorOfTables(const Vector<Offset<T>> *const vec) {
template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
if (vec) {
for (uoffset_t i = 0; i < vec->size(); i++) {
if (!vec->Get(i)->Verify(*this)) return false;
@@ -171,41 +151,30 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return true;
}
__suppress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
const uint8_t *const table) {
__supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
const uint8_t *table) {
// Check the vtable offset.
const auto tableo = static_cast<size_t>(table - buf_);
auto tableo = static_cast<size_t>(table - buf_);
if (!Verify<soffset_t>(tableo)) return false;
// This offset may be signed, but doing the subtraction unsigned always
// gives the result we want.
const auto vtableo =
tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
// Check the vtable size field, then check vtable fits in its entirety.
if (!(VerifyComplexity() && Verify<voffset_t>(vtableo) &&
VerifyAlignment(ReadScalar<voffset_t>(buf_ + vtableo),
sizeof(voffset_t))))
return false;
const auto vsize = ReadScalar<voffset_t>(buf_ + vtableo);
return Check((vsize & 1) == 0) && Verify(vtableo, vsize);
return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
}
template<typename T>
bool VerifyBufferFromStart(const char *const identifier, const size_t start) {
// Buffers have to be of some size to be valid. The reason it is a runtime
// check instead of static_assert, is that nested flatbuffers go through
// this call and their size is determined at runtime.
if (!Check(size_ >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false;
// If an identifier is provided, check that we have a buffer
bool VerifyBufferFromStart(const char *identifier, size_t start) {
if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
BufferHasIdentifier(buf_ + start, identifier)))) {
return false;
}
// Call T::Verify, which must be in the generated code for this type.
const auto o = VerifyOffset(start);
return Check(o != 0) &&
reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
auto o = VerifyOffset(start);
return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
// clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
&& GetComputedSize()
@@ -215,17 +184,9 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
}
template<typename T>
bool VerifyNestedFlatBuffer(const Vector<uint8_t> *const buf,
const char *const identifier) {
// Caller opted out of this.
if (!opts_.check_nested_flatbuffers) return true;
// An empty buffer is OK as it indicates not present.
bool VerifyNestedFlatBuffer(const Vector<uint8_t> *buf,
const char *identifier) {
if (!buf) return true;
// If there is a nested buffer, it must be greater than the min size.
if (!Check(buf->size() >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false;
Verifier nested_verifier(buf->data(), buf->size());
return nested_verifier.VerifyBuffer<T>(identifier);
}
@@ -233,20 +194,19 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
// Verify this whole buffer, starting with root type T.
template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
template<typename T> bool VerifyBuffer(const char *const identifier) {
template<typename T> bool VerifyBuffer(const char *identifier) {
return VerifyBufferFromStart<T>(identifier, 0);
}
template<typename T>
bool VerifySizePrefixedBuffer(const char *const identifier) {
template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
return Verify<uoffset_t>(0U) &&
Check(ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t)) &&
ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
}
uoffset_t VerifyOffset(const size_t start) const {
uoffset_t VerifyOffset(size_t start) const {
if (!Verify<uoffset_t>(start)) return 0;
const auto o = ReadScalar<uoffset_t>(buf_ + start);
auto o = ReadScalar<uoffset_t>(buf_ + start);
// May not point to itself.
if (!Check(o != 0)) return 0;
// Can't wrap around / buffers are max 2GB.
@@ -257,18 +217,18 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return o;
}
uoffset_t VerifyOffset(const uint8_t *const base,
const voffset_t start) const {
uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
return VerifyOffset(static_cast<size_t>(base - buf_) + start);
}
// Called at the start of a table to increase counters measuring data
// structure depth and amount, and possibly bails out with false if limits set
// by the constructor have been hit. Needs to be balanced with EndTable().
// structure depth and amount, and possibly bails out with false if
// limits set by the constructor have been hit. Needs to be balanced
// with EndTable().
bool VerifyComplexity() {
depth_++;
num_tables_++;
return Check(depth_ <= opts_.max_depth && num_tables_ <= opts_.max_tables);
return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
}
// Called at the end of a table to pop the depth count.
@@ -294,22 +254,15 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
// clang-format on
}
std::vector<uint8_t> *GetFlexReuseTracker() { return flex_reuse_tracker_; }
void SetFlexReuseTracker(std::vector<uint8_t> *const rt) {
flex_reuse_tracker_ = rt;
}
private:
const uint8_t *buf_;
const size_t size_;
const Options opts_;
mutable size_t upper_bound_ = 0;
uoffset_t depth_ = 0;
uoffset_t num_tables_ = 0;
std::vector<uint8_t> *flex_reuse_tracker_ = nullptr;
size_t size_;
uoffset_t depth_;
uoffset_t max_depth_;
uoffset_t num_tables_;
uoffset_t max_tables_;
mutable size_t upper_bound_;
bool check_alignment_;
};
} // namespace flatbuffers
+29 -29
View File
@@ -71,19 +71,19 @@ drawvec readLinePart(const FlatGeobuf::Geometry *geometry) {
drawvec readGeometry(const FlatGeobuf::Geometry *geometry, FlatGeobuf::GeometryType h_geometry_type) {
FlatGeobuf::GeometryType geometry_type = h_geometry_type;
if (h_geometry_type == FlatGeobuf::GeometryType_Unknown) geometry_type = geometry->type();
if (h_geometry_type == FlatGeobuf::GeometryType::Unknown) geometry_type = geometry->type();
if (geometry_type == FlatGeobuf::GeometryType_Point) {
if (geometry_type == FlatGeobuf::GeometryType::Point) {
return readPoints(geometry);
} if (geometry_type == FlatGeobuf::GeometryType_MultiPoint) {
} if (geometry_type == FlatGeobuf::GeometryType::MultiPoint) {
return readPoints(geometry);
} if (geometry_type == FlatGeobuf::GeometryType_LineString) {
} if (geometry_type == FlatGeobuf::GeometryType::LineString) {
return readLinePart(geometry);
} else if (h_geometry_type == FlatGeobuf::GeometryType_MultiLineString) {
} else if (h_geometry_type == FlatGeobuf::GeometryType::MultiLineString) {
return readLinePart(geometry);
} if (geometry_type == FlatGeobuf::GeometryType_Polygon) {
} if (geometry_type == FlatGeobuf::GeometryType::Polygon) {
return readLinePart(geometry);
} else if (geometry_type == FlatGeobuf::GeometryType_MultiPolygon) {
} else if (geometry_type == FlatGeobuf::GeometryType::MultiPolygon) {
// if it is a GeometryCollection, parse Parts, ignore XY
drawvec dv;
for (size_t part = 0; part < geometry->parts()->size(); part++) {
@@ -106,23 +106,23 @@ void readFeature(const FlatGeobuf::Feature *feature, long long feature_sequence_
int drawvec_type = -1;
FlatGeobuf::GeometryType geometry_type = h_geometry_type;
if (h_geometry_type == FlatGeobuf::GeometryType_Unknown) geometry_type = feature->geometry()->type();
if (h_geometry_type == FlatGeobuf::GeometryType::Unknown) geometry_type = feature->geometry()->type();
switch (geometry_type) {
case FlatGeobuf::GeometryType_Point :
case FlatGeobuf::GeometryType_MultiPoint :
case FlatGeobuf::GeometryType::Point :
case FlatGeobuf::GeometryType::MultiPoint :
drawvec_type = 1;
break;
case FlatGeobuf::GeometryType_LineString :
case FlatGeobuf::GeometryType_MultiLineString :
case FlatGeobuf::GeometryType::LineString :
case FlatGeobuf::GeometryType::MultiLineString :
drawvec_type = 2;
break;
case FlatGeobuf::GeometryType_Polygon :
case FlatGeobuf::GeometryType_MultiPolygon :
case FlatGeobuf::GeometryType::Polygon :
case FlatGeobuf::GeometryType::MultiPolygon :
drawvec_type = 3;
break;
case FlatGeobuf::GeometryType_Unknown :
case FlatGeobuf::GeometryType_GeometryCollection :
case FlatGeobuf::GeometryType::Unknown :
case FlatGeobuf::GeometryType::GeometryCollection :
default:
fprintf(stderr, "flatgeobuf has unsupported geometry type %u\n", (unsigned int)h_geometry_type);
exit(EXIT_IMPOSSIBLE);
@@ -161,73 +161,73 @@ void readFeature(const FlatGeobuf::Feature *feature, long long feature_sequence_
FlatGeobuf::ColumnType col_type = h_column_types[col_idx];
serial_val sv;
if (col_type == FlatGeobuf::ColumnType_Byte) {
if (col_type == FlatGeobuf::ColumnType::Byte) {
sv.type = mvt_sint;
int8_t byte_val;
memcpy(&byte_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(byte_val));
sv.s = std::to_string(byte_val);
p_pos += sizeof(uint16_t) + sizeof(byte_val);
} else if (col_type == FlatGeobuf::ColumnType_UByte) {
} else if (col_type == FlatGeobuf::ColumnType::UByte) {
sv.type = mvt_uint;
uint8_t ubyte_val;
memcpy(&ubyte_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(ubyte_val));
sv.s = std::to_string(ubyte_val);
p_pos += sizeof(uint16_t) + sizeof(ubyte_val);
} else if (col_type == FlatGeobuf::ColumnType_Bool) {
} else if (col_type == FlatGeobuf::ColumnType::Bool) {
sv.type = mvt_bool;
uint8_t bool_val;
memcpy(&bool_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(bool_val));
sv.s = std::to_string(bool_val);
p_pos += sizeof(uint16_t) + sizeof(bool_val);
} else if (col_type == FlatGeobuf::ColumnType_Short) {
} else if (col_type == FlatGeobuf::ColumnType::Short) {
sv.type = mvt_sint;
int16_t short_val;
memcpy(&short_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(short_val));
sv.s = std::to_string(short_val);
p_pos += sizeof(uint16_t) + sizeof(short_val);
} else if (col_type == FlatGeobuf::ColumnType_UShort) {
} else if (col_type == FlatGeobuf::ColumnType::UShort) {
sv.type = mvt_uint;
uint16_t ushort_val;
memcpy(&ushort_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(ushort_val));
sv.s = std::to_string(ushort_val);
p_pos += sizeof(uint16_t) + sizeof(ushort_val);
} else if (col_type == FlatGeobuf::ColumnType_Int) {
} else if (col_type == FlatGeobuf::ColumnType::Int) {
sv.type = mvt_sint;
int32_t int_val;
memcpy(&int_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(int_val));
sv.s = std::to_string(int_val);
p_pos += sizeof(uint16_t) + sizeof(int_val);
} else if (col_type == FlatGeobuf::ColumnType_UInt) {
} else if (col_type == FlatGeobuf::ColumnType::UInt) {
sv.type = mvt_uint;
uint32_t uint_val;
memcpy(&uint_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(uint_val));
sv.s = std::to_string(uint_val);
p_pos += sizeof(uint16_t) + sizeof(uint_val);
} else if (col_type == FlatGeobuf::ColumnType_Long) {
} else if (col_type == FlatGeobuf::ColumnType::Long) {
sv.type = mvt_sint;
int64_t long_val;
memcpy(&long_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(long_val));
sv.s = std::to_string(long_val);
p_pos += sizeof(uint16_t) + sizeof(long_val);
} else if (col_type == FlatGeobuf::ColumnType_ULong) {
} else if (col_type == FlatGeobuf::ColumnType::ULong) {
sv.type = mvt_uint;
int64_t ulong_val;
memcpy(&ulong_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(ulong_val));
sv.s = std::to_string(ulong_val);
p_pos += sizeof(uint16_t) + sizeof(ulong_val);
} else if (col_type == FlatGeobuf::ColumnType_Float) {
} else if (col_type == FlatGeobuf::ColumnType::Float) {
sv.type = mvt_float;
float float_val;
memcpy(&float_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(float_val));
sv.s = milo::dtoa_milo(float_val);
p_pos += sizeof(uint16_t) + sizeof(float_val);
} else if (col_type == FlatGeobuf::ColumnType_Double) {
} else if (col_type == FlatGeobuf::ColumnType::Double) {
sv.type = mvt_double;
double double_val;
memcpy(&double_val, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(double_val));
sv.s = milo::dtoa_milo(double_val);
p_pos += sizeof(uint16_t) + sizeof(double_val);
} else if (col_type == FlatGeobuf::ColumnType_String || col_type == FlatGeobuf::ColumnType_Json || col_type == FlatGeobuf::ColumnType_DateTime) {
} else if (col_type == FlatGeobuf::ColumnType::String || col_type == FlatGeobuf::ColumnType::Json || col_type == FlatGeobuf::ColumnType::DateTime) {
sv.type = mvt_string;
uint32_t val_len;
memcpy(&val_len, feature->properties()->data() + p_pos + sizeof(uint16_t), sizeof(val_len));
@@ -252,7 +252,7 @@ void readFeature(const FlatGeobuf::Feature *feature, long long feature_sequence_
struct fgb_queued_feature {
const FlatGeobuf::Feature *feature = NULL;
long long feature_sequence_id = -1;
FlatGeobuf::GeometryType h_geometry_type = FlatGeobuf::GeometryType_Unknown;
FlatGeobuf::GeometryType h_geometry_type = FlatGeobuf::GeometryType::Unknown;
const std::vector<std::string> *h_column_names = NULL;
const std::vector<FlatGeobuf::ColumnType> *h_column_types = NULL;
std::vector<struct serialization_state> *sst = NULL;
+3 -10
View File
@@ -6,13 +6,6 @@
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 22 &&
FLATBUFFERS_VERSION_MINOR == 9 &&
FLATBUFFERS_VERSION_REVISION == 29,
"Non-compatible flatbuffers version included");
#include "header_generated.h"
namespace FlatGeobuf {
@@ -73,7 +66,7 @@ struct Geometry FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
verifier.VerifyVector(t()) &&
VerifyOffset(verifier, VT_TM) &&
verifier.VerifyVector(tm()) &&
VerifyField<uint8_t>(verifier, VT_TYPE, 1) &&
VerifyField<uint8_t>(verifier, VT_TYPE) &&
VerifyOffset(verifier, VT_PARTS) &&
verifier.VerifyVector(parts()) &&
verifier.VerifyVectorOfTables(parts()) &&
@@ -128,7 +121,7 @@ inline flatbuffers::Offset<Geometry> CreateGeometry(
flatbuffers::Offset<flatbuffers::Vector<double>> m = 0,
flatbuffers::Offset<flatbuffers::Vector<double>> t = 0,
flatbuffers::Offset<flatbuffers::Vector<uint64_t>> tm = 0,
FlatGeobuf::GeometryType type = FlatGeobuf::GeometryType_Unknown,
FlatGeobuf::GeometryType type = FlatGeobuf::GeometryType::Unknown,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<FlatGeobuf::Geometry>>> parts = 0) {
GeometryBuilder builder_(_fbb);
builder_.add_parts(parts);
@@ -150,7 +143,7 @@ inline flatbuffers::Offset<Geometry> CreateGeometryDirect(
const std::vector<double> *m = nullptr,
const std::vector<double> *t = nullptr,
const std::vector<uint64_t> *tm = nullptr,
FlatGeobuf::GeometryType type = FlatGeobuf::GeometryType_Unknown,
FlatGeobuf::GeometryType type = FlatGeobuf::GeometryType::Unknown,
const std::vector<flatbuffers::Offset<FlatGeobuf::Geometry>> *parts = nullptr) {
auto ends__ = ends ? _fbb.CreateVector<uint32_t>(*ends) : 0;
auto xy__ = xy ? _fbb.CreateVector<double>(*xy) : 0;
+93 -100
View File
@@ -6,13 +6,6 @@
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 22 &&
FLATBUFFERS_VERSION_MINOR == 9 &&
FLATBUFFERS_VERSION_REVISION == 29,
"Non-compatible flatbuffers version included");
namespace FlatGeobuf {
struct Column;
@@ -24,49 +17,49 @@ struct CrsBuilder;
struct Header;
struct HeaderBuilder;
enum GeometryType : uint8_t {
GeometryType_Unknown = 0,
GeometryType_Point = 1,
GeometryType_LineString = 2,
GeometryType_Polygon = 3,
GeometryType_MultiPoint = 4,
GeometryType_MultiLineString = 5,
GeometryType_MultiPolygon = 6,
GeometryType_GeometryCollection = 7,
GeometryType_CircularString = 8,
GeometryType_CompoundCurve = 9,
GeometryType_CurvePolygon = 10,
GeometryType_MultiCurve = 11,
GeometryType_MultiSurface = 12,
GeometryType_Curve = 13,
GeometryType_Surface = 14,
GeometryType_PolyhedralSurface = 15,
GeometryType_TIN = 16,
GeometryType_Triangle = 17,
GeometryType_MIN = GeometryType_Unknown,
GeometryType_MAX = GeometryType_Triangle
enum class GeometryType : uint8_t {
Unknown = 0,
Point = 1,
LineString = 2,
Polygon = 3,
MultiPoint = 4,
MultiLineString = 5,
MultiPolygon = 6,
GeometryCollection = 7,
CircularString = 8,
CompoundCurve = 9,
CurvePolygon = 10,
MultiCurve = 11,
MultiSurface = 12,
Curve = 13,
Surface = 14,
PolyhedralSurface = 15,
TIN = 16,
Triangle = 17,
MIN = Unknown,
MAX = Triangle
};
inline const GeometryType (&EnumValuesGeometryType())[18] {
static const GeometryType values[] = {
GeometryType_Unknown,
GeometryType_Point,
GeometryType_LineString,
GeometryType_Polygon,
GeometryType_MultiPoint,
GeometryType_MultiLineString,
GeometryType_MultiPolygon,
GeometryType_GeometryCollection,
GeometryType_CircularString,
GeometryType_CompoundCurve,
GeometryType_CurvePolygon,
GeometryType_MultiCurve,
GeometryType_MultiSurface,
GeometryType_Curve,
GeometryType_Surface,
GeometryType_PolyhedralSurface,
GeometryType_TIN,
GeometryType_Triangle
GeometryType::Unknown,
GeometryType::Point,
GeometryType::LineString,
GeometryType::Polygon,
GeometryType::MultiPoint,
GeometryType::MultiLineString,
GeometryType::MultiPolygon,
GeometryType::GeometryCollection,
GeometryType::CircularString,
GeometryType::CompoundCurve,
GeometryType::CurvePolygon,
GeometryType::MultiCurve,
GeometryType::MultiSurface,
GeometryType::Curve,
GeometryType::Surface,
GeometryType::PolyhedralSurface,
GeometryType::TIN,
GeometryType::Triangle
};
return values;
}
@@ -97,48 +90,48 @@ inline const char * const *EnumNamesGeometryType() {
}
inline const char *EnumNameGeometryType(GeometryType e) {
if (flatbuffers::IsOutRange(e, GeometryType_Unknown, GeometryType_Triangle)) return "";
if (flatbuffers::IsOutRange(e, GeometryType::Unknown, GeometryType::Triangle)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesGeometryType()[index];
}
enum ColumnType : uint8_t {
ColumnType_Byte = 0,
ColumnType_UByte = 1,
ColumnType_Bool = 2,
ColumnType_Short = 3,
ColumnType_UShort = 4,
ColumnType_Int = 5,
ColumnType_UInt = 6,
ColumnType_Long = 7,
ColumnType_ULong = 8,
ColumnType_Float = 9,
ColumnType_Double = 10,
ColumnType_String = 11,
ColumnType_Json = 12,
ColumnType_DateTime = 13,
ColumnType_Binary = 14,
ColumnType_MIN = ColumnType_Byte,
ColumnType_MAX = ColumnType_Binary
enum class ColumnType : uint8_t {
Byte = 0,
UByte = 1,
Bool = 2,
Short = 3,
UShort = 4,
Int = 5,
UInt = 6,
Long = 7,
ULong = 8,
Float = 9,
Double = 10,
String = 11,
Json = 12,
DateTime = 13,
Binary = 14,
MIN = Byte,
MAX = Binary
};
inline const ColumnType (&EnumValuesColumnType())[15] {
static const ColumnType values[] = {
ColumnType_Byte,
ColumnType_UByte,
ColumnType_Bool,
ColumnType_Short,
ColumnType_UShort,
ColumnType_Int,
ColumnType_UInt,
ColumnType_Long,
ColumnType_ULong,
ColumnType_Float,
ColumnType_Double,
ColumnType_String,
ColumnType_Json,
ColumnType_DateTime,
ColumnType_Binary
ColumnType::Byte,
ColumnType::UByte,
ColumnType::Bool,
ColumnType::Short,
ColumnType::UShort,
ColumnType::Int,
ColumnType::UInt,
ColumnType::Long,
ColumnType::ULong,
ColumnType::Float,
ColumnType::Double,
ColumnType::String,
ColumnType::Json,
ColumnType::DateTime,
ColumnType::Binary
};
return values;
}
@@ -166,7 +159,7 @@ inline const char * const *EnumNamesColumnType() {
}
inline const char *EnumNameColumnType(ColumnType e) {
if (flatbuffers::IsOutRange(e, ColumnType_Byte, ColumnType_Binary)) return "";
if (flatbuffers::IsOutRange(e, ColumnType::Byte, ColumnType::Binary)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesColumnType()[index];
}
@@ -223,17 +216,17 @@ struct Column FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyField<uint8_t>(verifier, VT_TYPE, 1) &&
VerifyField<uint8_t>(verifier, VT_TYPE) &&
VerifyOffset(verifier, VT_TITLE) &&
verifier.VerifyString(title()) &&
VerifyOffset(verifier, VT_DESCRIPTION) &&
verifier.VerifyString(description()) &&
VerifyField<int32_t>(verifier, VT_WIDTH, 4) &&
VerifyField<int32_t>(verifier, VT_PRECISION, 4) &&
VerifyField<int32_t>(verifier, VT_SCALE, 4) &&
VerifyField<uint8_t>(verifier, VT_NULLABLE, 1) &&
VerifyField<uint8_t>(verifier, VT_UNIQUE, 1) &&
VerifyField<uint8_t>(verifier, VT_PRIMARY_KEY, 1) &&
VerifyField<int32_t>(verifier, VT_WIDTH) &&
VerifyField<int32_t>(verifier, VT_PRECISION) &&
VerifyField<int32_t>(verifier, VT_SCALE) &&
VerifyField<uint8_t>(verifier, VT_NULLABLE) &&
VerifyField<uint8_t>(verifier, VT_UNIQUE) &&
VerifyField<uint8_t>(verifier, VT_PRIMARY_KEY) &&
VerifyOffset(verifier, VT_METADATA) &&
verifier.VerifyString(metadata()) &&
verifier.EndTable();
@@ -292,7 +285,7 @@ struct ColumnBuilder {
inline flatbuffers::Offset<Column> CreateColumn(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
FlatGeobuf::ColumnType type = FlatGeobuf::ColumnType_Byte,
FlatGeobuf::ColumnType type = FlatGeobuf::ColumnType::Byte,
flatbuffers::Offset<flatbuffers::String> title = 0,
flatbuffers::Offset<flatbuffers::String> description = 0,
int32_t width = -1,
@@ -320,7 +313,7 @@ inline flatbuffers::Offset<Column> CreateColumn(
inline flatbuffers::Offset<Column> CreateColumnDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
FlatGeobuf::ColumnType type = FlatGeobuf::ColumnType_Byte,
FlatGeobuf::ColumnType type = FlatGeobuf::ColumnType::Byte,
const char *title = nullptr,
const char *description = nullptr,
int32_t width = -1,
@@ -381,7 +374,7 @@ struct Crs FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_ORG) &&
verifier.VerifyString(org()) &&
VerifyField<int32_t>(verifier, VT_CODE, 4) &&
VerifyField<int32_t>(verifier, VT_CODE) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_DESCRIPTION) &&
@@ -534,16 +527,16 @@ struct Header FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_ENVELOPE) &&
verifier.VerifyVector(envelope()) &&
VerifyField<uint8_t>(verifier, VT_GEOMETRY_TYPE, 1) &&
VerifyField<uint8_t>(verifier, VT_HAS_Z, 1) &&
VerifyField<uint8_t>(verifier, VT_HAS_M, 1) &&
VerifyField<uint8_t>(verifier, VT_HAS_T, 1) &&
VerifyField<uint8_t>(verifier, VT_HAS_TM, 1) &&
VerifyField<uint8_t>(verifier, VT_GEOMETRY_TYPE) &&
VerifyField<uint8_t>(verifier, VT_HAS_Z) &&
VerifyField<uint8_t>(verifier, VT_HAS_M) &&
VerifyField<uint8_t>(verifier, VT_HAS_T) &&
VerifyField<uint8_t>(verifier, VT_HAS_TM) &&
VerifyOffset(verifier, VT_COLUMNS) &&
verifier.VerifyVector(columns()) &&
verifier.VerifyVectorOfTables(columns()) &&
VerifyField<uint64_t>(verifier, VT_FEATURES_COUNT, 8) &&
VerifyField<uint16_t>(verifier, VT_INDEX_NODE_SIZE, 2) &&
VerifyField<uint64_t>(verifier, VT_FEATURES_COUNT) &&
VerifyField<uint16_t>(verifier, VT_INDEX_NODE_SIZE) &&
VerifyOffset(verifier, VT_CRS) &&
verifier.VerifyTable(crs()) &&
VerifyOffset(verifier, VT_TITLE) &&
@@ -617,7 +610,7 @@ inline flatbuffers::Offset<Header> CreateHeader(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<double>> envelope = 0,
FlatGeobuf::GeometryType geometry_type = FlatGeobuf::GeometryType_Unknown,
FlatGeobuf::GeometryType geometry_type = FlatGeobuf::GeometryType::Unknown,
bool has_z = false,
bool has_m = false,
bool has_t = false,
@@ -651,7 +644,7 @@ inline flatbuffers::Offset<Header> CreateHeaderDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const std::vector<double> *envelope = nullptr,
FlatGeobuf::GeometryType geometry_type = FlatGeobuf::GeometryType_Unknown,
FlatGeobuf::GeometryType geometry_type = FlatGeobuf::GeometryType::Unknown,
bool has_z = false,
bool has_m = false,
bool has_t = false,
+83 -202
View File
@@ -92,17 +92,6 @@ void to_tile_scale(drawvec &geom, int z, int detail) {
}
}
drawvec from_tile_scale(drawvec const &geom, int z, int detail) {
drawvec out;
for (size_t i = 0; i < geom.size(); i++) {
draw d = geom[i];
d.x <<= (32 - detail - z);
d.y <<= (32 - detail - z);
out.push_back(d);
}
return out;
}
drawvec remove_noop(drawvec geom, int type, int shift) {
// first pass: remove empty linetos
@@ -601,11 +590,9 @@ drawvec simple_clip_poly(drawvec &geom, int z, int buffer) {
return simple_clip_poly(geom, -clip_buffer, -clip_buffer, area + clip_buffer, area + clip_buffer);
}
drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double *accum_area, serial_feature *this_feature, serial_feature *tiny_feature) {
drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double *accum_area) {
drawvec out;
const double pixel = (1LL << (32 - detail - z)) * (double) tiny_polygon_size;
bool includes_real = false;
bool includes_dust = false;
*reduced = true;
bool included_last_outer = false;
@@ -649,7 +636,6 @@ drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double
out.push_back(draw(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2 + pixel));
out.push_back(draw(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2 + pixel));
out.push_back(draw(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2));
includes_dust = true;
*accum_area -= pixel * pixel;
}
@@ -669,7 +655,6 @@ drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double
// which means that the overall polygon has a real geometry,
// which means that it gets to be simplified.
*reduced = false;
includes_real = true;
if (area > 0) {
included_last_outer = true;
@@ -687,28 +672,6 @@ drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double
fprintf(stderr, "\n");
out.push_back(geom[i]);
includes_real = true;
}
}
if (!includes_real) {
if (includes_dust) {
// this geometry is just dust, so if there is another feature that
// contributed to the dust that is larger than this feature,
// keep its attributes instead of this one that just happened to be
// the one that hit the threshold of survival.
if (tiny_feature->extent > this_feature->extent) {
*this_feature = *tiny_feature;
tiny_feature->extent = 0;
}
} else {
// this is a feature that we are throwing away, so hang on to it
// attributes if it is bigger than the biggest one we threw away so far
if (this_feature->extent > tiny_feature->extent) {
*tiny_feature = *this_feature;
}
}
}
@@ -1478,6 +1441,15 @@ draw centerOfMass(const drawvec &dv, size_t start, size_t end, draw centre) {
}
}
struct polygon_label {
long long size;
draw point;
bool operator<(const polygon_label &o) const {
return size > o.size; // reverse sort, largest first
}
};
double label_goodness(const drawvec &dv, size_t start, size_t count, long long x, long long y) {
if (!pnpoly(dv, start, count, x, y)) {
return 0; // outside the polygon is as bad as it gets
@@ -1516,8 +1488,8 @@ double label_goodness(const drawvec &dv, size_t start, size_t count, long long x
// least-bad option.
drawvec polygon_to_anchor(const drawvec &geom) {
size_t start = 0, end = 0;
size_t best_area = 0;
std::vector<polygon_label> labels;
drawvec dv;
for (size_t i = 0; i < geom.size(); i++) {
if (geom[i].op == VT_MOVETO) {
@@ -1528,176 +1500,85 @@ drawvec polygon_to_anchor(const drawvec &geom) {
}
}
long long xsum = 0;
long long ysum = 0;
size_t count = 0;
long long xmin = LLONG_MAX, ymin = LLONG_MAX, xmax = LLONG_MIN, ymax = LLONG_MIN;
double area = get_area(geom, i, j);
if (area > best_area) {
start = i;
end = j;
best_area = area;
if (area > 0) { // don't generate anchors for holes
// Calculate centroid and bounding box.
// i + 1 to exclude the first point, which is duplicated as the last
for (size_t k = i + 1; k < j; k++) {
xsum += geom[k].x;
ysum += geom[k].y;
count++;
xmin = std::min(xmin, geom[k].x);
ymin = std::min(ymin, geom[k].y);
xmax = std::max(xmax, geom[k].x);
ymax = std::max(ymax, geom[k].y);
}
if (count > 0) {
draw centroid(VT_MOVETO, xsum / count, ysum / count);
draw d = centerOfMass(geom, i, j, centroid);
double radius = sqrt(area / M_PI);
double goodness_threshold = radius / 5;
double goodness = label_goodness(geom, i, j - i - 1, d.x, d.y);
if (goodness < goodness_threshold) {
// Label is too close to the border or outside it,
// so try some other possible points
for (long long sub = 2;
sub < 32 && (xmax - xmin) > 2 * sub && (ymax - ymin) > 2 * sub;
sub *= 2) {
for (long long x = 1; x < sub; x++) {
for (long long y = 1; y < sub; y++) {
draw maybe(VT_MOVETO,
xmin + x * (xmax - xmin) / sub,
ymin + y * (ymax - ymin) / sub);
double maybe_goodness = label_goodness(geom, i, j - i, maybe.x, maybe.y);
if (maybe_goodness > goodness) {
// better than the previous
d = maybe;
goodness = maybe_goodness;
}
}
}
if (goodness > goodness_threshold) {
break;
}
}
// There is nothing really good. Is the centroid maybe better?
// If not, we're stuck with whatever the best we found was.
if (label_goodness(geom, i, j - i, centroid.x, centroid.y) > goodness) {
d = centroid;
}
}
polygon_label pl;
pl.size = area;
pl.point = d;
labels.push_back(pl);
}
}
i = j - 1;
}
}
if (best_area > 0) {
long long xsum = 0;
long long ysum = 0;
size_t count = 0;
long long xmin = LLONG_MAX, ymin = LLONG_MAX, xmax = LLONG_MIN, ymax = LLONG_MIN;
std::sort(labels.begin(), labels.end());
// Calculate centroid and bounding box.
// start + 1 to exclude the first point, which is duplicated as the last
for (size_t k = start + 1; k < end; k++) {
xsum += geom[k].x;
ysum += geom[k].y;
count++;
xmin = std::min(xmin, geom[k].x);
ymin = std::min(ymin, geom[k].y);
xmax = std::max(xmax, geom[k].x);
ymax = std::max(ymax, geom[k].y);
}
if (count > 0) {
draw centroid(VT_MOVETO, xsum / count, ysum / count);
draw d = centerOfMass(geom, start, end, centroid);
double radius = sqrt(best_area / M_PI);
double goodness_threshold = radius / 5;
double goodness = label_goodness(geom, start, end - start - 1, d.x, d.y);
if (goodness < goodness_threshold) {
// Label is too close to the border or outside it,
// so try some other possible points
for (long long sub = 2;
sub < 32 && (xmax - xmin) > 2 * sub && (ymax - ymin) > 2 * sub;
sub *= 2) {
for (long long x = 1; x < sub; x++) {
for (long long y = 1; y < sub; y++) {
draw maybe(VT_MOVETO,
xmin + x * (xmax - xmin) / sub,
ymin + y * (ymax - ymin) / sub);
double maybe_goodness = label_goodness(geom, start, end - start, maybe.x, maybe.y);
if (maybe_goodness > goodness) {
// better than the previous
d = maybe;
goodness = maybe_goodness;
}
}
}
if (goodness > goodness_threshold) {
break;
}
}
// There is nothing really good. Is the centroid maybe better?
// If not, we're stuck with whatever the best we found was.
if (label_goodness(geom, start, end - start, centroid.x, centroid.y) > goodness) {
d = centroid;
}
}
drawvec dv;
dv.push_back(d);
return dv;
}
if (labels.size() > 0) {
dv.push_back(labels[0].point);
}
return drawvec();
}
static double dist(long long x1, long long y1, long long x2, long long y2) {
double dx = x2 - x1;
double dy = y2 - y1;
return sqrt(dx * dx + dy * dy);
}
drawvec spiral_anchors(drawvec const &geom, int tx, int ty, int z, unsigned long long label_point) {
drawvec out;
// anchor point in world coordinates
unsigned wx, wy;
decode_index(label_point, &wx, &wy);
// upper left of tile in world coordinates
long long tx1 = 0, ty1 = 0;
// lower right of tile in world coordinates;
long long tx2 = 1LL << 32, ty2 = 1LL << 32;
if (z != 0) {
tx1 = (long long) tx << (32 - z);
ty1 = (long long) ty << (32 - z);
tx2 = (long long) (tx + 1) << (32 - z);
ty2 = (long long) (ty + 1) << (32 - z);
}
// min and max distance of corners of this tile from the label point
double min_radius, max_radius;
if (wx >= tx1 && wx <= tx2 && wy >= ty1 && wy <= ty2) {
// center is in this tile,
// so min is 0, max can't be more than sqrt(2) tiles
min_radius = 0;
max_radius = sqrt(2);
} else {
// center is elsewhere,
// so min is at most sqrt(2)/2 tiles short of the center of the tile
// and max is at most sqrt(2)/2 tiles past the center of the tile
min_radius = std::max(0.0, dist(wx, wy, (tx1 + tx2) / 2, (ty1 + ty2) / 2) / (1LL << (32 - z)) - sqrt(2) / 2);
max_radius = min_radius + sqrt(2);
}
// labels complete a circle every 0.4 tiles of radius
const double spiral_dist = 0.4;
size_t min_i = pow(min_radius / spiral_dist, 2);
size_t max_i = pow(max_radius / spiral_dist, 2);
// https://craftofcoding.wordpress.com/tag/sunflower-spiral/
double angle = M_PI * (3.0 - sqrt(5.0)); // 137.5 in radians
for (size_t i = min_i; i <= max_i; i++) {
double r = sqrt(i) * spiral_dist;
double theta = i * angle;
// Convert polar to cartesian
long long x = r * cos(theta) * (1LL << (32 - z)) + wx;
long long y = r * sin(theta) * (1LL << (32 - z)) + wy;
if (x >= tx1 && x <= tx2 && y >= ty1 && y <= ty2) {
// is it actually inside the bounding box of the feature? then keep it.
for (size_t a = 0; a < geom.size(); a++) {
if (geom[a].op == VT_MOVETO) {
size_t b;
for (b = a + 1; b < geom.size(); b++) {
if (geom[b].op != VT_LINETO) {
break;
}
}
// If it's the central label, it's the best we've got,
// so accept it in any case. If it's from the outer spiral,
// don't use it if it's too close to a border.
if (i == 0) {
out.push_back(draw(VT_MOVETO, x - tx1, y - ty1));
break;
} else {
double tilesize = 1LL << (32 - z);
double goodness_threshold = tilesize / 100;
if (label_goodness(geom, a, b - a, x - tx1, y - ty1) > goodness_threshold) {
out.push_back(draw(VT_MOVETO, x - tx1, y - ty1));
break;
}
}
a = b - 1;
}
}
}
}
return out;
return dv;
}
+1 -4
View File
@@ -56,17 +56,15 @@ struct draw {
};
typedef std::vector<draw> drawvec;
struct serial_feature;
drawvec decode_geometry(FILE *meta, std::atomic<long long> *geompos, int z, unsigned tx, unsigned ty, long long *bbox, unsigned initial_x, unsigned initial_y);
void to_tile_scale(drawvec &geom, int z, int detail);
drawvec from_tile_scale(drawvec const &geom, int z, int detail);
drawvec remove_noop(drawvec geom, int type, int shift);
drawvec clip_point(drawvec &geom, int z, long long buffer);
drawvec clean_or_clip_poly(drawvec &geom, int z, int buffer, bool clip);
drawvec simple_clip_poly(drawvec &geom, int z, int buffer);
drawvec close_poly(drawvec &geom);
drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double *accum_area, serial_feature *this_feature, serial_feature *tiny_feature);
drawvec reduce_tiny_poly(drawvec &geom, int z, int detail, bool *reduced, double *accum_area);
drawvec clip_lines(drawvec &geom, int z, long long buffer);
drawvec stairstep(drawvec &geom, int z, int detail);
bool point_within_tile(long long x, long long y, int z);
@@ -79,7 +77,6 @@ void check_polygon(drawvec &geom);
double get_area(const drawvec &geom, size_t i, size_t j);
double get_mp_area(drawvec &geom);
drawvec polygon_to_anchor(const drawvec &geom);
drawvec spiral_anchors(drawvec const &geom, int tx, int ty, int z, unsigned long long label_point);
drawvec simple_clip_poly(drawvec &geom, long long x1, long long y1, long long x2, long long y2);
drawvec clip_lines(drawvec &geom, long long x1, long long y1, long long x2, long long y2);
+7 -44
View File
@@ -404,7 +404,7 @@ void *run_sort(void *v) {
return NULL;
}
void do_read_parallel(char *map, long long len, long long initial_offset, const char *reading, std::vector<struct reader> *readers, std::atomic<long long> *progress_seq, std::set<std::string> *exclude, std::set<std::string> *include, int exclude_all, int basezoom, int source, std::vector<std::map<std::string, layermap_entry> > *layermaps, int *initialized, unsigned *initial_x, unsigned *initial_y, int maxzoom, std::string layername, bool uses_gamma, std::map<std::string, int> const *attribute_types, int separator, double *dist_sum, size_t *dist_count, double *area_sum, bool want_dist, bool filters) {
void do_read_parallel(char *map, long long len, long long initial_offset, const char *reading, std::vector<struct reader> *readers, std::atomic<long long> *progress_seq, std::set<std::string> *exclude, std::set<std::string> *include, int exclude_all, int basezoom, int source, std::vector<std::map<std::string, layermap_entry> > *layermaps, int *initialized, unsigned *initial_x, unsigned *initial_y, int maxzoom, std::string layername, bool uses_gamma, std::map<std::string, int> const *attribute_types, int separator, double *dist_sum, size_t *dist_count, bool want_dist, bool filters) {
long long segs[CPUS + 1];
segs[0] = 0;
segs[CPUS] = len;
@@ -419,7 +419,6 @@ void do_read_parallel(char *map, long long len, long long initial_offset, const
double dist_sums[CPUS];
size_t dist_counts[CPUS];
double area_sums[CPUS];
std::atomic<long long> layer_seq[CPUS];
for (size_t i = 0; i < CPUS; i++) {
@@ -427,7 +426,6 @@ void do_read_parallel(char *map, long long len, long long initial_offset, const
// begins with that segment's offset into the input
layer_seq[i] = segs[i] + initial_offset;
dist_sums[i] = dist_counts[i] = 0;
area_sums[i] = 0;
}
std::vector<parse_json_args> pja;
@@ -453,7 +451,6 @@ void do_read_parallel(char *map, long long len, long long initial_offset, const
sst[i].initial_x = &initial_x[i];
sst[i].initial_y = &initial_y[i];
sst[i].dist_sum = &(dist_sums[i]);
sst[i].area_sum = &(area_sums[i]);
sst[i].dist_count = &(dist_counts[i]);
sst[i].want_dist = want_dist;
sst[i].maxzoom = maxzoom;
@@ -489,7 +486,6 @@ void do_read_parallel(char *map, long long len, long long initial_offset, const
*dist_sum += dist_sums[i];
*dist_count += dist_counts[i];
*area_sum += area_sums[i];
json_end_map(pja[i].jp);
}
@@ -608,7 +604,6 @@ struct read_parallel_arg {
std::map<std::string, int> const *attribute_types = NULL;
double *dist_sum = NULL;
size_t *dist_count = NULL;
double *area_sum = NULL;
bool want_dist = false;
bool filters = false;
};
@@ -632,7 +627,7 @@ void *run_read_parallel(void *v) {
}
madvise(map, rpa->len, MADV_RANDOM); // sequential, but from several pointers at once
do_read_parallel(map, rpa->len, rpa->offset, rpa->reading, rpa->readers, rpa->progress_seq, rpa->exclude, rpa->include, rpa->exclude_all, rpa->basezoom, rpa->source, rpa->layermaps, rpa->initialized, rpa->initial_x, rpa->initial_y, rpa->maxzoom, rpa->layername, rpa->uses_gamma, rpa->attribute_types, rpa->separator, rpa->dist_sum, rpa->dist_count, rpa->area_sum, rpa->want_dist, rpa->filters);
do_read_parallel(map, rpa->len, rpa->offset, rpa->reading, rpa->readers, rpa->progress_seq, rpa->exclude, rpa->include, rpa->exclude_all, rpa->basezoom, rpa->source, rpa->layermaps, rpa->initialized, rpa->initial_x, rpa->initial_y, rpa->maxzoom, rpa->layername, rpa->uses_gamma, rpa->attribute_types, rpa->separator, rpa->dist_sum, rpa->dist_count, rpa->want_dist, rpa->filters);
madvise(map, rpa->len, MADV_DONTNEED);
if (munmap(map, rpa->len) != 0) {
@@ -649,7 +644,7 @@ void *run_read_parallel(void *v) {
return NULL;
}
void start_parsing(int fd, STREAM *fp, long long offset, long long len, std::atomic<int> *is_parsing, pthread_t *parallel_parser, bool &parser_created, const char *reading, std::vector<struct reader> *readers, std::atomic<long long> *progress_seq, std::set<std::string> *exclude, std::set<std::string> *include, int exclude_all, int basezoom, int source, std::vector<std::map<std::string, layermap_entry> > &layermaps, int *initialized, unsigned *initial_x, unsigned *initial_y, int maxzoom, std::string layername, bool uses_gamma, std::map<std::string, int> const *attribute_types, int separator, double *dist_sum, size_t *dist_count, double *area_sum, bool want_dist, bool filters) {
void start_parsing(int fd, STREAM *fp, long long offset, long long len, std::atomic<int> *is_parsing, pthread_t *parallel_parser, bool &parser_created, const char *reading, std::vector<struct reader> *readers, std::atomic<long long> *progress_seq, std::set<std::string> *exclude, std::set<std::string> *include, int exclude_all, int basezoom, int source, std::vector<std::map<std::string, layermap_entry> > &layermaps, int *initialized, unsigned *initial_x, unsigned *initial_y, int maxzoom, std::string layername, bool uses_gamma, std::map<std::string, int> const *attribute_types, int separator, double *dist_sum, size_t *dist_count, bool want_dist, bool filters) {
// This has to kick off an intermediate thread to start the parser threads,
// so the main thread can get back to reading the next input stage while
// the intermediate thread waits for the completion of the parser threads.
@@ -687,7 +682,6 @@ void start_parsing(int fd, STREAM *fp, long long offset, long long len, std::ato
rpa->attribute_types = attribute_types;
rpa->dist_sum = dist_sum;
rpa->dist_count = dist_count;
rpa->area_sum = area_sum;
rpa->want_dist = want_dist;
rpa->filters = filters;
@@ -1336,7 +1330,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
long overall_offset = 0;
double dist_sum = 0;
size_t dist_count = 0;
double area_sum = 0;
int files_open_before_reading = open("/dev/null", O_RDONLY | O_CLOEXEC);
if (files_open_before_reading < 0) {
@@ -1390,7 +1383,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
std::atomic<long long> layer_seq[CPUS];
double dist_sums[CPUS];
size_t dist_counts[CPUS];
double area_sums[CPUS];
std::vector<struct serialization_state> sst;
sst.resize(CPUS);
@@ -1398,7 +1390,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
layer_seq[i] = overall_offset;
dist_sums[i] = 0;
dist_counts[i] = 0;
area_sums[i] = 0;
sst[i].fname = reading.c_str();
sst[i].line = 0;
@@ -1411,7 +1402,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
sst[i].initialized = &initialized[i];
sst[i].dist_sum = &dist_sums[i];
sst[i].dist_count = &dist_counts[i];
sst[i].area_sum = &area_sums[i];
sst[i].want_dist = guess_maxzoom;
sst[i].maxzoom = maxzoom;
sst[i].filters = prefilter != NULL || postfilter != NULL;
@@ -1429,7 +1419,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
for (size_t i = 0; i < CPUS; i++) {
dist_sum += dist_sums[i];
dist_count += dist_counts[i];
area_sum = area_sums[i];
}
if (munmap(map, st.st_size) != 0) {
@@ -1463,7 +1452,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
std::atomic<long long> layer_seq[CPUS];
double dist_sums[CPUS];
size_t dist_counts[CPUS];
double area_sums[CPUS];
std::vector<struct serialization_state> sst;
sst.resize(CPUS);
@@ -1471,7 +1459,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
layer_seq[i] = overall_offset;
dist_sums[i] = 0;
dist_counts[i] = 0;
area_sums[i] = 0;
sst[i].fname = reading.c_str();
sst[i].line = 0;
@@ -1484,7 +1471,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
sst[i].initialized = &initialized[i];
sst[i].dist_sum = &dist_sums[i];
sst[i].dist_count = &dist_counts[i];
sst[i].area_sum = &area_sums[i];
sst[i].want_dist = guess_maxzoom;
sst[i].maxzoom = maxzoom;
sst[i].filters = prefilter != NULL || postfilter != NULL;
@@ -1502,7 +1488,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
for (size_t i = 0; i < CPUS; i++) {
dist_sum += dist_sums[i];
dist_count += dist_counts[i];
area_sum += area_sums[i];
}
if (munmap(map, st.st_size) != 0) {
@@ -1523,7 +1508,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
std::atomic<long long> layer_seq[CPUS];
double dist_sums[CPUS];
size_t dist_counts[CPUS];
double area_sums[CPUS];
std::vector<struct serialization_state> sst;
sst.resize(CPUS);
@@ -1533,7 +1517,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
layer_seq[i] = overall_offset;
dist_sums[i] = 0;
dist_counts[i] = 0;
area_sums[i] = 0;
sst[i].fname = reading.c_str();
sst[i].line = 0;
@@ -1546,7 +1529,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
sst[i].initialized = &initialized[i];
sst[i].dist_sum = &dist_sums[i];
sst[i].dist_count = &dist_counts[i];
sst[i].area_sum = &area_sums[i];
sst[i].want_dist = guess_maxzoom;
sst[i].maxzoom = maxzoom;
sst[i].filters = prefilter != NULL || postfilter != NULL;
@@ -1608,7 +1590,7 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
}
if (map != NULL && map != MAP_FAILED && read_parallel_this) {
do_read_parallel(map, st.st_size - off, overall_offset, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, &layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, uses_gamma, attribute_types, read_parallel_this, &dist_sum, &dist_count, &area_sum, guess_maxzoom, prefilter != NULL || postfilter != NULL);
do_read_parallel(map, st.st_size - off, overall_offset, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, &layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, uses_gamma, attribute_types, read_parallel_this, &dist_sum, &dist_count, guess_maxzoom, prefilter != NULL || postfilter != NULL);
overall_offset += st.st_size - off;
checkdisk(&readers);
@@ -1686,7 +1668,7 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
}
fflush(readfp);
start_parsing(readfd, streamfpopen(readfp), initial_offset, ahead, &is_parsing, &parallel_parser, parser_created, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, gamma != 0, attribute_types, read_parallel_this, &dist_sum, &dist_count, &area_sum, guess_maxzoom, prefilter != NULL || postfilter != NULL);
start_parsing(readfd, streamfpopen(readfp), initial_offset, ahead, &is_parsing, &parallel_parser, parser_created, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, gamma != 0, attribute_types, read_parallel_this, &dist_sum, &dist_count, guess_maxzoom, prefilter != NULL || postfilter != NULL);
initial_offset += ahead;
overall_offset += ahead;
@@ -1723,7 +1705,7 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
fflush(readfp);
if (ahead > 0) {
start_parsing(readfd, streamfpopen(readfp), initial_offset, ahead, &is_parsing, &parallel_parser, parser_created, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, gamma != 0, attribute_types, read_parallel_this, &dist_sum, &dist_count, &area_sum, guess_maxzoom, prefilter != NULL || postfilter != NULL);
start_parsing(readfd, streamfpopen(readfp), initial_offset, ahead, &is_parsing, &parallel_parser, parser_created, reading.c_str(), &readers, &progress_seq, exclude, include, exclude_all, basezoom, layer, layermaps, initialized, initial_x, initial_y, maxzoom, sources[layer].layer, gamma != 0, attribute_types, read_parallel_this, &dist_sum, &dist_count, guess_maxzoom, prefilter != NULL || postfilter != NULL);
if (parser_created) {
if (pthread_join(parallel_parser, NULL) != 0) {
@@ -1753,7 +1735,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
sst.initialized = &initialized[0];
sst.dist_sum = &dist_sum;
sst.dist_count = &dist_count;
sst.area_sum = &area_sum;
sst.want_dist = guess_maxzoom;
sst.maxzoom = maxzoom;
sst.filters = prefilter != NULL || postfilter != NULL;
@@ -2182,24 +2163,6 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
}
}
double total_tile_count = 0;
for (int i = 1; i <= maxzoom; i++) {
double tile_count = ceil(area_sum / ((1LL << (32 - i)) * (1LL << (32 - i))));
total_tile_count += tile_count;
// 2M tiles is an arbitrary limit, chosen to make tiling jobs
// that seem like they should finish in a few minutes
// actually finish in a few minutes. It is large enough to
// tile a polygon that covers the entire world to z10
// or the United States to z13.
if (total_tile_count > 2 * 1024 * 1024) {
printf("Limiting maxzoom to -z%d to keep from generating %lld tiles\n", i - 1, (long long) total_tile_count);
maxzoom = i - 1;
break;
}
}
if (maxzoom < minimum_maxzoom) {
if (!quiet) {
fprintf(stderr, "Using minimum maxzoom of -z%d\n", minimum_maxzoom);
@@ -2464,7 +2427,7 @@ int read_input(std::vector<source> &sources, char *fname, int maxzoom, int minzo
if (maxzoom != written) {
if (written > minzoom) {
fprintf(stderr, "\n\n\n*** NOTE TILES ONLY COMPLETE THROUGH ZOOM %d ***\n", written);
fprintf(stderr, "\n\n\n*** NOTE TILES ONLY COMPLETE THROUGH ZOOM %d ***\n\n\n", written);
maxzoom = written;
ret = EXIT_INCOMPLETE;
} else {
+14 -67
View File
@@ -52,45 +52,20 @@ sqlite3 *mbtiles_open(char *dbname, char **argv, int forcetable) {
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create tiles table: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "create unique index name on metadata (name);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: index metadata: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
// "map" maps z/x/y coordinates to a content hash
if (sqlite3_exec(outdb, "CREATE TABLE map (zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_id TEXT);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create map table: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "CREATE UNIQUE INDEX map_index ON map (zoom_level, tile_column, tile_row);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create map index: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
// "images" maps a content hash to tile contents
if (sqlite3_exec(outdb, "CREATE TABLE images (tile_data blob, tile_id text);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create images table: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "CREATE UNIQUE INDEX images_id ON images (tile_id);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create images index: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
}
// "tiles" is a view that retrieves content from "images"
// via the content hash looked up from "map".
if (sqlite3_exec(outdb, "CREATE VIEW tiles AS SELECT map.zoom_level AS zoom_level, map.tile_column AS tile_column, map.tile_row AS tile_row, images.tile_data AS tile_data FROM map JOIN images ON images.tile_id = map.tile_id;", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create tiles view: %s\n", argv[0], err);
if (sqlite3_exec(outdb, "create unique index tile_index on tiles (zoom_level, tile_column, tile_row);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: index tiles: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_EXISTS);
}
@@ -100,51 +75,23 @@ sqlite3 *mbtiles_open(char *dbname, char **argv, int forcetable) {
}
void mbtiles_write_tile(sqlite3 *outdb, int z, int tx, int ty, const char *data, int size) {
// Store tiles by a hash of their contents. node-mbtiles uses MD5,
// but I am resisting adding the dependency, so instead here is
// everybody's first hash function. It is the same as Java's String.hashCode(),
// https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode()
unsigned long long h = 0;
for (int i = 0; i < size; i++) {
h = h * 31 + data[i];
}
std::string hash = std::to_string(h);
// following https://github.com/mapbox/node-mbtiles/blob/master/lib/mbtiles.js
sqlite3_stmt *stmt;
const char *images = "replace into images (tile_id, tile_data) values (?, ?)";
if (sqlite3_prepare_v2(outdb, images, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "sqlite3 images prep failed\n");
exit(EXIT_SQLITE);
}
sqlite3_bind_blob(stmt, 1, hash.c_str(), hash.size(), NULL);
sqlite3_bind_blob(stmt, 2, data, size, NULL);
if (sqlite3_step(stmt) != SQLITE_DONE) {
fprintf(stderr, "sqlite3 images insert failed: %s\n", sqlite3_errmsg(outdb));
}
if (sqlite3_finalize(stmt) != SQLITE_OK) {
fprintf(stderr, "sqlite3 images finalize failed: %s\n", sqlite3_errmsg(outdb));
}
const char *map = "insert into map (zoom_level, tile_column, tile_row, tile_id) values (?, ?, ?, ?)";
if (sqlite3_prepare_v2(outdb, map, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "sqlite3 map prep failed\n");
const char *query = "insert into tiles (zoom_level, tile_column, tile_row, tile_data) values (?, ?, ?, ?)";
if (sqlite3_prepare_v2(outdb, query, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "sqlite3 insert prep failed\n");
exit(EXIT_SQLITE);
}
sqlite3_bind_int(stmt, 1, z);
sqlite3_bind_int(stmt, 2, tx);
sqlite3_bind_int(stmt, 3, (1 << z) - 1 - ty);
sqlite3_bind_blob(stmt, 4, hash.c_str(), hash.size(), NULL);
sqlite3_bind_blob(stmt, 4, data, size, NULL);
if (sqlite3_step(stmt) != SQLITE_DONE) {
fprintf(stderr, "sqlite3 map insert failed: %s\n", sqlite3_errmsg(outdb));
fprintf(stderr, "sqlite3 insert failed: %s\n", sqlite3_errmsg(outdb));
}
if (sqlite3_finalize(stmt) != SQLITE_OK) {
fprintf(stderr, "sqlite3 map finalize failed: %s\n", sqlite3_errmsg(outdb));
fprintf(stderr, "sqlite3 finalize failed: %s\n", sqlite3_errmsg(outdb));
}
}
+1 -5
View File
@@ -539,7 +539,7 @@ int serialize_feature(struct serialization_state *sst, serial_feature &sf) {
}
double extent = 0;
if (additional[A_DROP_SMALLEST_AS_NEEDED] || additional[A_COALESCE_SMALLEST_AS_NEEDED] || order_by_size || sst->want_dist) {
if (additional[A_DROP_SMALLEST_AS_NEEDED] || additional[A_COALESCE_SMALLEST_AS_NEEDED] || order_by_size) {
if (sf.t == VT_POLYGON) {
for (size_t i = 0; i < scaled_geometry.size(); i++) {
if (scaled_geometry[i].op == VT_MOVETO) {
@@ -576,10 +576,6 @@ int serialize_feature(struct serialization_state *sst, serial_feature &sf) {
sf.extent = LLONG_MAX;
}
if (sst->want_dist && sf.t == VT_POLYGON) {
*(sst->area_sum) += extent;
}
if (!prevent[P_INPUT_ORDER]) {
sf.seq = 0;
}
-1
View File
@@ -150,7 +150,6 @@ struct serialization_state {
double *dist_sum = NULL; // running tally for calculation of resolution within features
size_t *dist_count = NULL;
double *area_sum = NULL;
bool want_dist = false;
int maxzoom = 0;
@@ -125,9 +125,9 @@
{ "type": "FeatureCollection", "properties": { "layer": "layer3115744778", "version": 2, "extent": 4096 }, "features": [
{ "type": "Feature", "properties": { "rule": "type: 2, [\"in\", \"$type\", \"Polygon\", \"LineString\", \"Point\"]" }, "geometry": { "type": "LineString", "coordinates": [ [ 0.000000, 0.000000 ], [ 0.966797, 1.054628 ] ] } }
,
{ "type": "Feature", "properties": { "rule": "type: 1, [\"in\", \"$type\", \"Polygon\", \"LineString\", \"Point\"]" }, "geometry": { "type": "Point", "coordinates": [ 0.000000, 0.000000 ] } }
,
{ "type": "Feature", "properties": { "rule": "type: 3, [\"in\", \"$type\", \"Polygon\", \"LineString\", \"Point\"]" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 0.966797, 1.054628 ], [ 0.966797, 0.000000 ], [ 0.000000, 0.000000 ], [ 0.966797, 1.054628 ] ] ] } }
,
{ "type": "Feature", "properties": { "rule": "type: 1, [\"in\", \"$type\", \"Polygon\", \"LineString\", \"Point\"]" }, "geometry": { "type": "Point", "coordinates": [ 0.000000, 0.000000 ] } }
] }
,
{ "type": "FeatureCollection", "properties": { "layer": "layer328238911", "version": 2, "extent": 4096 }, "features": [
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -16,23 +16,23 @@
{ "type": "FeatureCollection", "properties": { "layer": "in", "version": 2, "extent": 1024 }, "features": [
{ "type": "Feature", "properties": { "seq": 8 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721518, -37.166209 ], [ 174.721518, -37.166210 ], [ 174.721518, -37.166210 ], [ 174.721518, -37.166209 ], [ 174.721518, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 7 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721519, -37.166209 ], [ 174.721519, -37.166210 ], [ 174.721519, -37.166210 ], [ 174.721519, -37.166209 ], [ 174.721519, -37.166209 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 9 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721519, -37.166209 ], [ 174.721519, -37.166210 ], [ 174.721519, -37.166210 ], [ 174.721519, -37.166209 ], [ 174.721519, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 11 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721520, -37.166209 ], [ 174.721520, -37.166210 ], [ 174.721520, -37.166210 ], [ 174.721520, -37.166209 ], [ 174.721520, -37.166209 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 10 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721520, -37.166209 ], [ 174.721520, -37.166210 ], [ 174.721520, -37.166210 ], [ 174.721520, -37.166209 ], [ 174.721520, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 12 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721522, -37.166209 ], [ 174.721522, -37.166210 ], [ 174.721521, -37.166210 ], [ 174.721521, -37.166209 ], [ 174.721522, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 13 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721525, -37.166209 ], [ 174.721525, -37.166210 ], [ 174.721525, -37.166210 ], [ 174.721525, -37.166209 ], [ 174.721525, -37.166209 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 15 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721525, -37.166209 ], [ 174.721525, -37.166210 ], [ 174.721525, -37.166210 ], [ 174.721525, -37.166209 ], [ 174.721525, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 17 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721527, -37.166209 ], [ 174.721527, -37.166210 ], [ 174.721526, -37.166210 ], [ 174.721526, -37.166209 ], [ 174.721527, -37.166209 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 18 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721533, -37.166210 ], [ 174.721533, -37.166210 ], [ 174.721533, -37.166210 ], [ 174.721533, -37.166210 ], [ 174.721533, -37.166210 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 19 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 20 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ], [ 174.721536, -37.166210 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 21 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 22 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ], [ 174.721540, -37.166210 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 23 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 24 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ], [ 174.721542, -37.166210 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 25 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721544, -37.166210 ], [ 174.721544, -37.166210 ], [ 174.721543, -37.166210 ], [ 174.721544, -37.166210 ] ] ] } }
,
@@ -48,7 +48,7 @@
,
{ "type": "Feature", "properties": { "seq": 34 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721559, -37.166210 ], [ 174.721559, -37.166211 ], [ 174.721559, -37.166211 ], [ 174.721559, -37.166210 ], [ 174.721559, -37.166210 ] ] ] } }
,
{ "type": "Feature", "properties": { "seq": 33 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ] ] ] } }
{ "type": "Feature", "properties": { "seq": 35 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ], [ 174.721564, -37.166210 ] ] ] } }
] }
] }
,
+1 -1
View File
@@ -131,7 +131,7 @@ std::string truncate16(std::string const &s, size_t runes) {
int integer_zoom(std::string where, std::string text) {
double d = atof(text.c_str());
if (!std::isfinite(d) || d != floor(d) || d < 0 || d > 32) {
if (!isfinite(d) || d != floor(d) || d < 0 || d > 32) {
fprintf(stderr, "%s: Expected integer zoom level in \"tippecanoe\" GeoJSON extension, not %s\n", where.c_str(), text.c_str());
exit(EXIT_JSON);
}
+105 -25
View File
@@ -447,12 +447,9 @@ struct partial {
long long layer = 0;
long long original_seq = 0;
unsigned long long index = 0;
unsigned long long label_point = 0;
int segment = 0;
bool reduced = 0;
int z = 0;
int tx = 0;
int ty = 0;
int line_detail = 0;
int extra_detail = 0;
int maxzoom = 0;
@@ -578,37 +575,31 @@ void *partial_feature_worker(void *v) {
to_tile_scale(geom, z, out_detail);
std::vector<drawvec> geoms;
geoms.push_back(geom);
if (t == VT_POLYGON) {
// Scaling may have made the polygon degenerate.
// Give Clipper a chance to try to fix it.
{
drawvec before = geom;
geom = clean_or_clip_poly(geom, 0, 0, false);
for (size_t g = 0; g < geoms.size(); g++) {
drawvec before = geoms[g];
geoms[g] = clean_or_clip_poly(geoms[g], 0, 0, false);
if (additional[A_DEBUG_POLYGON]) {
check_polygon(geom);
check_polygon(geoms[g]);
}
if (geom.size() < 3) {
if (geoms[g].size() < 3) {
if (area > 0) {
// area is in world coordinates, calculated before scaling down
geom = revive_polygon(before, area, z, out_detail);
geoms[g] = revive_polygon(before, area / geoms.size(), z, out_detail);
} else {
geom.clear();
geoms[g].clear();
}
}
}
}
if (t == VT_POLYGON && additional[A_GENERATE_POLYGON_LABEL_POINTS]) {
t = (*partials)[i].t = VT_POINT;
geom = spiral_anchors(from_tile_scale(geom, z, out_detail), (*partials)[i].tx, (*partials)[i].ty, z, (*partials)[i].label_point);
to_tile_scale(geom, z, out_detail);
}
(*partials)[i].index = i;
std::vector<drawvec> geoms; // artifact of former polygon-splitting to reduce geometric complexity
geoms.push_back(geom);
(*partials)[i].geoms = geoms;
}
@@ -1810,6 +1801,95 @@ static bool line_is_too_small(drawvec const &geometry, int z, int detail) {
return true;
}
static double dist(long long x1, long long y1, long long x2, long long y2) {
double dx = x2 - x1;
double dy = y2 - y1;
return sqrt(dx * dx + dy * dy);
}
drawvec spiral_anchors(drawvec const &geom, int tx, int ty, int z, unsigned long long label_point) {
drawvec out;
// anchor point in world coordinates
unsigned wx, wy;
decode_index(label_point, &wx, &wy);
// upper left of tile in world coordinates
long long tx1 = 0, ty1 = 0;
// lower right of tile in world coordinates;
long long tx2 = 1LL << 32, ty2 = 1LL << 32;
if (z != 0) {
tx1 = (long long) tx << (32 - z);
ty1 = (long long) ty << (32 - z);
tx2 = (long long) (tx + 1) << (32 - z);
ty2 = (long long) (ty + 1) << (32 - z);
}
// min and max distance of corners of this tile from the label point
double min_radius, max_radius;
if (wx >= tx1 && wx <= tx2 && wy >= ty1 && wy <= ty2) {
// center is in this tile
min_radius = 0;
} else {
// center is elsewhere
min_radius = std::min(dist(wx, wy, tx1, ty1),
std::min(dist(wx, wy, tx2, ty1),
std::min(dist(wx, wy, tx2, ty2),
dist(wx, wy, tx1, ty2))));
}
max_radius = std::max(dist(wx, wy, tx1, ty1),
std::max(dist(wx, wy, tx2, ty1),
std::max(dist(wx, wy, tx2, ty2),
dist(wx, wy, tx1, ty2))));
// from world coordinates to tiles
min_radius /= 1LL << (32 - z);
max_radius /= 1LL << (32 - z);
// labels complete a circle every 0.4 tiles of radius
const double spiral_dist = 0.4;
size_t min_i = pow(min_radius / spiral_dist, 2);
size_t max_i = pow(max_radius / spiral_dist, 2);
// https://craftofcoding.wordpress.com/tag/sunflower-spiral/
double angle = M_PI * (3.0 - sqrt(5.0)); // 137.5 in radians
for (size_t i = min_i; i <= max_i; i++) {
double r = sqrt(i) * spiral_dist;
double theta = i * angle;
// Convert polar to cartesian
long long x = r * cos(theta) * (1LL << (32 - z)) + wx;
long long y = r * sin(theta) * (1LL << (32 - z)) + wy;
if (x >= tx1 && x <= tx2 && y >= ty1 && y <= ty2) {
// is it actually inside the bounding box of the feature? then keep it.
for (size_t a = 0; a < geom.size(); a++) {
if (geom[a].op == VT_MOVETO) {
size_t b;
for (b = a + 1; b < geom.size(); b++) {
if (geom[b].op != VT_LINETO) {
break;
}
}
if (pnpoly(geom, a, b - a, x - tx1, y - ty1)) {
out.push_back(draw(VT_MOVETO, x - tx1, y - ty1));
break;
}
a = b - 1;
}
}
}
}
return out;
}
long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *metabase, char *stringpool, int z, const unsigned tx, const unsigned ty, const int detail, int min_detail, sqlite3 *outdb, const char *outdir, int buffer, const char *fname, FILE **geomfile, int minzoom, int maxzoom, double todo, std::atomic<long long> *along, long long alongminus, double gamma, int child_shards, long long *meta_off, long long *pool_off, unsigned *initial_x, unsigned *initial_y, std::atomic<int> *running, double simplification, std::vector<std::map<std::string, layermap_entry>> *layermaps, std::vector<std::vector<std::string>> *layer_unmaps, size_t tiling_seg, size_t pass, size_t passes, unsigned long long mingap, long long minextent, double fraction, const char *prefilter, const char *postfilter, struct json_object *filter, write_tile_args *arg, atomic_strategy *strategy) {
double merge_fraction = 1;
double mingap_fraction = 1;
@@ -1893,8 +1973,6 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
FILE *prefilter_read_fp = NULL;
json_pull *prefilter_jp = NULL;
serial_feature tiny_feature;
if (z < minzoom) {
prefilter = NULL;
postfilter = NULL;
@@ -2083,7 +2161,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
bool reduced = false;
if (sf.t == VT_POLYGON) {
if (!prevent[P_TINY_POLYGON_REDUCTION] && !additional[A_GRID_LOW_ZOOMS]) {
sf.geometry = reduce_tiny_poly(sf.geometry, z, line_detail, &reduced, &accum_area, &sf, &tiny_feature);
sf.geometry = reduce_tiny_poly(sf.geometry, z, line_detail, &reduced, &accum_area);
if (reduced) {
strategy->tiny_polygons++;
}
@@ -2096,6 +2174,11 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
}
}
if (sf.t == VT_POLYGON && additional[A_GENERATE_POLYGON_LABEL_POINTS]) {
sf.t = VT_POINT;
sf.geometry = spiral_anchors(sf.geometry, tx, ty, z, sf.label_point);
}
if (sf.geometry.size() > 0) {
if (partials.size() > max_tile_size) {
// Even being maximally conservative, each feature is still going to be
@@ -2118,8 +2201,6 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
p.original_seq = sf.seq;
p.reduced = reduced;
p.z = z;
p.tx = tx;
p.ty = ty;
p.line_detail = line_detail;
p.extra_detail = line_detail;
p.maxzoom = maxzoom;
@@ -2132,7 +2213,6 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
p.id = sf.id;
p.has_id = sf.has_id;
p.index = sf.index;
p.label_point = sf.label_point;
p.renamed = -1;
p.extent = sf.extent;
p.clustered = 0;
+1 -1
View File
@@ -1,6 +1,6 @@
#ifndef VERSION_HPP
#define VERSION_HPP
#define VERSION "v2.11.0"
#define VERSION "v2.9.0"
#endif