FlatCityBuf C++ reader 0.10.0
Native C++17 reader for FlatCityBuf, the cloud-optimized CityJSON format
Loading...
Searching...
No Matches
fcb_writer.cpp
Go to the documentation of this file.
1#include <fcb/error.hpp>
5
6#include <algorithm>
7#include <limits>
8#include <sstream>
9
10#if defined(_WIN32)
11# define FCB_FSEEK _fseeki64
12using fcb_off_t = long long;
13#else
14# include <sys/types.h>
15# define FCB_FSEEK fseeko
16using fcb_off_t = off_t;
17#endif
18
19namespace fcb {
20
21namespace {
22
23// "fcb" + VERSION + "fcb" + 0 (const_vars.rs:5, layout.hpp's kVersion == 1).
24constexpr std::uint8_t kMagicBytes[8] = {'f', 'c', 'b', kVersion, 'f', 'c', 'b', 0};
25
26// Feature bytes are streamed from the spool to the output in chunks this
27// size, rather than ever materializing a whole feature (let alone the
28// whole feature section) as one buffer.
29constexpr std::size_t kCopyChunkSize = 1 << 16; // 64 KiB
30
31} // namespace
32
33FcbWriter::FcbWriter(nlohmann::ordered_json cj, FcbWriterOptions options,
34 AttributeSchema attr_schema,
35 std::optional<AttributeSchema> semantic_attr_schema)
36 : cj_(std::move(cj)), options_(std::move(options)), attr_schema_(std::move(attr_schema)),
37 semantic_attr_schema_(std::move(semantic_attr_schema)) {
38 for (const auto& [name, unused] : options_.attribute_indices)
39 indexing_attr_.push_back(name);
40 id_column_ = id_column_index(options_.id_index, attr_schema_);
41
42 const auto& transform = cj_.at("transform");
43 scale_x_ = transform.at("scale").at(0).get<double>();
44 scale_y_ = transform.at("scale").at(1).get<double>();
45 translate_x_ = transform.at("translate").at(0).get<double>();
46 translate_y_ = transform.at("translate").at(1).get<double>();
47
48 tmp_ = std::tmpfile();
49 if (tmp_ == nullptr) {
50 throw Error(ErrorCode::IoError, "FcbWriter: failed to create a temporary file for feature "
51 "spooling");
52 }
53}
54
56 if (tmp_ != nullptr) {
57 std::fclose(tmp_); // removes the file too: that is std::tmpfile()'s whole contract
58 }
59}
60
61void FcbWriter::add_feature(const nlohmann::ordered_json& feature) {
62 if (written_) {
63 throw Error(ErrorCode::IoError, "FcbWriter::add_feature called after write()");
64 }
65
66 flatbuffers::FlatBufferBuilder fbb;
67 auto [off, raw_bbox] =
68 to_fcb_city_feature(fbb, feature.at("id").get<std::string>(), feature, attr_schema_,
69 semantic_attr_schema_ ? &*semantic_attr_schema_ : nullptr);
70 fbb.FinishSizePrefixed(off);
71 const std::uint64_t size = fbb.GetSize();
72
73 if (size > 0) {
74 if (FCB_FSEEK(tmp_, static_cast<fcb_off_t>(tmp_write_pos_), SEEK_SET) != 0 ||
75 std::fwrite(fbb.GetBufferPointer(), 1, size, tmp_) != size) {
76 throw Error(ErrorCode::IoError, "FcbWriter: failed writing a feature to the temp file");
77 }
78 }
79
80 const std::uint64_t temp_id = feat_offsets_.size();
81 feat_offsets_.push_back(FeatureSlot{tmp_write_pos_, size});
82 tmp_write_pos_ += size;
83
84 feat_nodes_.push_back(NodeItem{raw_bbox.min_x * scale_x_ + translate_x_,
85 raw_bbox.min_y * scale_y_ + translate_y_,
86 raw_bbox.max_x * scale_x_ + translate_x_,
87 raw_bbox.max_y * scale_y_ + translate_y_, temp_id});
88
89 if (!indexing_attr_.empty()) {
90 index_entries_by_feature_.push_back(
91 cityfeature_to_index_entries(feature, attr_schema_, indexing_attr_));
92 } else {
93 index_entries_by_feature_.emplace_back();
94 }
95 if (id_column_) {
96 auto ids = cityfeature_to_id_index_entries(feature, *id_column_);
97 auto& entries = index_entries_by_feature_.back();
98 entries.insert(entries.end(), ids.begin(), ids.end());
99 }
100}
101
102void FcbWriter::write(std::ostream& out) {
103 if (written_) {
104 throw Error(ErrorCode::IoError, "FcbWriter::write called more than once");
105 }
106 written_ = true;
107 std::fflush(tmp_);
108
109 // `write_index: false` forces index_node_size to 0 in the header,
110 // exactly like `HeaderWriter::new_with_options` (header_writer.rs:
111 // 87-94) -- computed once here so every downstream decision (whether
112 // to hilbert_sort, whether to build an R-tree, what the header
113 // records) uses the SAME effective value.
114 const std::uint16_t effective_node_size = options_.write_index ? options_.index_node_size : 0;
115
116 // Rust's own `if index_node_size > 0 && !feat_nodes.is_empty()` guards
117 // `hilbert_sort` itself, not just the R-tree build (writer/mod.rs:
118 // 208-225) -- when it's false, features stay in ORIGINAL order (each
119 // `.offset` still its temp id from `add_feature`).
120 NodeItem extent = NodeItem::empty(0);
121 const bool build_rtree = effective_node_size > 0 && !feat_nodes_.empty();
122 if (build_rtree) {
123 extent = calc_extent(feat_nodes_);
124 hilbert_sort(feat_nodes_, extent);
125 }
126
127 // Bookkeeping-only pass: compute each feature's FINAL byte offset in
128 // the (sorted or original) output order, WITHOUT reading any feature
129 // bytes yet -- `feat_nodes_` itself is left untouched (`.offset` still
130 // each entry's original temp id) so the later streaming pass can still
131 // look up where in the spool file to read each one from.
132 std::vector<std::uint64_t> final_offset_by_temp_id(feat_offsets_.size());
133 {
134 std::uint64_t running = 0;
135 for (const auto& node : feat_nodes_) {
136 final_offset_by_temp_id[static_cast<std::size_t>(node.offset)] = running;
137 running += feat_offsets_[static_cast<std::size_t>(node.offset)].size;
138 }
139 }
140
141 std::vector<std::uint8_t> rtree_bytes;
142 if (build_rtree) {
143 // A throwaway copy with `.offset` remapped to final byte offsets --
144 // `feat_nodes_` itself keeps carrying temp ids for the streaming
145 // pass below.
146 std::vector<NodeItem> rtree_input = feat_nodes_;
147 for (auto& node : rtree_input)
148 node.offset = final_offset_by_temp_id[static_cast<std::size_t>(node.offset)];
149 std::vector<NodeItem> tree = build_packed_rtree(rtree_input, extent, effective_node_size);
150 rtree_bytes = encode_packed_rtree(tree);
151 }
152
153 // Per-column attribute index dispatch (writer/mod.rs:192-202,252-265),
154 // sorted by SCHEMA COLUMN INDEX (not request order). A requested name
155 // absent from the schema, or with zero indexable entries, is silently
156 // skipped -- mirrors `if let Ok(...) = build_attribute_index_for_attr(
157 // ...)` (writer/mod.rs:255-264), which discards an `Err` (from either
158 // `Error::AttributeIndexNotFound` or `Stree::init`'s empty-tree check)
159 // rather than propagating it.
160 std::vector<std::pair<std::string, std::optional<std::uint16_t>>> sorted_indices =
161 options_.attribute_indices;
162 std::stable_sort(
163 sorted_indices.begin(), sorted_indices.end(), [this](const auto& a, const auto& b) {
164 const auto ia = attr_schema_.find(a.first);
165 const auto ib = attr_schema_.find(b.first);
166 const std::uint16_t idx_a = ia != attr_schema_.end()
167 ? ia->second.first
168 : std::numeric_limits<std::uint16_t>::max();
169 const std::uint16_t idx_b = ib != attr_schema_.end()
170 ? ib->second.first
171 : std::numeric_limits<std::uint16_t>::max();
172 return idx_a < idx_b;
173 });
174
175 std::vector<std::uint8_t> attr_index_bytes;
176 std::vector<AttributeIndexInfo> attr_index_info;
177 if (!sorted_indices.empty() || id_column_) {
178 // One slot per column index; the id column's is the highest.
179 std::size_t column_slots = id_column_ ? *id_column_ + std::size_t{1} : 0;
180 for (const auto& [name, idx_type] : attr_schema_)
181 column_slots = std::max<std::size_t>(column_slots, idx_type.first + std::size_t{1});
182 std::vector<std::vector<BtreeEntry>> entries_by_column(column_slots);
183 for (std::size_t temp_id = 0; temp_id < feat_offsets_.size(); ++temp_id) {
184 const std::uint64_t feature_offset = final_offset_by_temp_id[temp_id];
185 for (const auto& e : index_entries_by_feature_[temp_id])
186 entries_by_column.at(e.index).push_back(BtreeEntry{e.value, feature_offset});
187 }
188
189 for (const auto& [name, bf_opt] : sorted_indices) {
190 const auto it = attr_schema_.find(name);
191 if (it == attr_schema_.end())
192 continue;
193 const std::uint16_t schema_index = it->second.first;
194 const auto& col_entries = entries_by_column.at(schema_index);
195 if (col_entries.empty())
196 continue;
197
198 const KeyKind kind = key_kind_for_column(static_cast<std::uint8_t>(it->second.second));
199 const std::uint16_t branching_factor = bf_opt.value_or(kDefaultBranchingFactor);
200 BuiltBtreeIndex built = build_static_btree(col_entries, kind, branching_factor);
201
202 attr_index_info.push_back(
203 AttributeIndexInfo{schema_index, static_cast<std::uint32_t>(built.bytes.size()),
204 built.branching_factor, built.num_unique_items});
205 attr_index_bytes.insert(attr_index_bytes.end(), built.bytes.begin(), built.bytes.end());
206 }
207
208 // The id column has the highest column index, so its index comes
209 // last. A file without features has no id to index.
210 if (id_column_ && !entries_by_column.at(*id_column_).empty()) {
211 const KeyKind kind =
212 key_kind_for_column(static_cast<std::uint8_t>(::ColumnType::String));
213 BuiltBtreeIndex built =
214 build_static_btree(entries_by_column.at(*id_column_), kind, *options_.id_index);
215 attr_index_info.push_back(
216 AttributeIndexInfo{*id_column_, static_cast<std::uint32_t>(built.bytes.size()),
217 built.branching_factor, built.num_unique_items});
218 attr_index_bytes.insert(attr_index_bytes.end(), built.bytes.begin(), built.bytes.end());
219 }
220 }
221
222 HeaderWriterOptions header_options;
223 header_options.feature_count = feat_offsets_.size();
224 header_options.index_node_size = effective_node_size;
225 header_options.geographical_extent = options_.geographical_extent;
226 header_options.id_index = options_.id_index;
227
228 flatbuffers::FlatBufferBuilder header_fbb;
229 auto header_off = to_fcb_header(header_fbb, cj_, header_options, attr_schema_,
230 semantic_attr_schema_ ? &*semantic_attr_schema_ : nullptr,
231 attr_index_info.empty() ? nullptr : &attr_index_info);
232 header_fbb.FinishSizePrefixed(header_off);
233
234 out.write(reinterpret_cast<const char*>(kMagicBytes), sizeof(kMagicBytes));
235 out.write(reinterpret_cast<const char*>(header_fbb.GetBufferPointer()),
236 static_cast<std::streamsize>(header_fbb.GetSize()));
237 if (!rtree_bytes.empty())
238 out.write(reinterpret_cast<const char*>(rtree_bytes.data()),
239 static_cast<std::streamsize>(rtree_bytes.size()));
240 if (!attr_index_bytes.empty())
241 out.write(reinterpret_cast<const char*>(attr_index_bytes.data()),
242 static_cast<std::streamsize>(attr_index_bytes.size()));
243 if (!out) {
244 throw Error(ErrorCode::IoError, "FcbWriter: failed writing the header/index sections");
245 }
246
247 // Stream every feature's bytes straight from the spool to `out`, in
248 // `feat_nodes_`'s CURRENT (sorted or original) order, through a fixed-
249 // size buffer -- never holding more than one chunk of feature data (let
250 // alone the whole feature section) in memory at once.
251 std::vector<char> chunk(kCopyChunkSize);
252 for (const auto& node : feat_nodes_) {
253 const FeatureSlot& slot = feat_offsets_[static_cast<std::size_t>(node.offset)];
254 if (slot.size == 0)
255 continue;
256 if (FCB_FSEEK(tmp_, static_cast<fcb_off_t>(slot.offset), SEEK_SET) != 0) {
257 throw Error(ErrorCode::IoError, "FcbWriter: failed to seek the temp file");
258 }
259 std::uint64_t remaining = slot.size;
260 while (remaining > 0) {
261 const std::size_t want =
262 static_cast<std::size_t>(std::min<std::uint64_t>(remaining, chunk.size()));
263 if (std::fread(chunk.data(), 1, want, tmp_) != want) {
265 "FcbWriter: failed reading a feature back from the temp file");
266 }
267 out.write(chunk.data(), static_cast<std::streamsize>(want));
268 if (!out) {
270 "FcbWriter: failed writing a feature to the output");
271 }
272 remaining -= want;
273 }
274 }
275}
276
277std::vector<std::uint8_t> FcbWriter::write() {
278 std::ostringstream oss(std::ios::binary);
279 write(oss);
280 const std::string& s = oss.str();
281 return std::vector<std::uint8_t>(s.begin(), s.end());
282}
283
284} // namespace fcb
Every failure the library reports is one of these.
Definition error.hpp:31
void add_feature(const nlohmann::ordered_json &city_json_feature)
Encodes and spools one CityJSONFeature line.
std::vector< std::uint8_t > write()
Convenience wrapper around write(std::ostream&) that returns the complete file as one buffer.
FcbWriter(nlohmann::ordered_json cj, FcbWriterOptions options, AttributeSchema attr_schema, std::optional< AttributeSchema > semantic_attr_schema)
cj is the CityJSONSeq's metadata line (first line: type/ version/transform/metadata/etc).
off_t fcb_off_t
#define FCB_FSEEK
void hilbert_sort(std::vector< NodeItem > &items, const NodeItem &extent)
Sorts items in place by descending Hilbert index (the item furthest along the curve first) – a STABLE...
std::vector< std::uint8_t > encode_packed_rtree(const std::vector< NodeItem > &tree)
Serializes every node in tree (as returned by build_packed_rtree) in array order, 40 bytes each.
constexpr std::uint16_t kDefaultBranchingFactor
Mirrors static_btree::DEFAULT_BRANCHING_FACTOR (static_btree/mod.rs:19), used whenever a caller reque...
BuiltBtreeIndex build_static_btree(const std::vector< BtreeEntry > &entries, KeyKind kind, std::uint16_t branching_factor)
Builds one column's complete attribute index blob from its (key, offset) entries.
std::map< std::string, std::pair< std::uint16_t, ::ColumnType > > AttributeSchema
Attribute schema: name -> (column index, column type).
Definition attribute.hpp:43
KeyKind key_kind_for_column(std::uint8_t column_type)
Column type to key kind, following what the WRITER emits.
Definition key.cpp:387
std::vector< NodeItem > build_packed_rtree(const std::vector< NodeItem > &nodes, const NodeItem &extent, std::uint16_t node_size)
Builds the full flat packed-R-tree node array (leaves first in nodes's own order at the array's tail ...
std::vector< AttributeIndexEntry > cityfeature_to_index_entries(const nlohmann::ordered_json &city_feature, const AttributeSchema &schema, const std::vector< std::string > &indexing_attr)
Same, over every object in one CityJSONFeature's CityObjects, visited in ascending object-id order (n...
std::vector< AttributeIndexEntry > cityfeature_to_id_index_entries(const nlohmann::ordered_json &city_feature, std::uint16_t index)
One index entry per City Object of city_feature, keyed by the object's id, for the id column at index...
KeyKind
The concrete key types the B+tree index can hold.
Definition key.hpp:14
NodeItem calc_extent(const std::vector< NodeItem > &nodes)
The bbox union of every item, via repeated NodeItem::expand starting from NodeItem::empty(0).
std::optional< std::uint16_t > id_column_index(const std::optional< std::uint16_t > &id_index, const AttributeSchema &schema)
The index of the City Object id column: the next free one when id_index asks for an id index and sche...
constexpr std::uint8_t kVersion
Definition layout.hpp:14
std::pair<::flatbuffers::Offset<::CityFeature >, NodeItem > to_fcb_city_feature(::flatbuffers::FlatBufferBuilder &fbb, const std::string &id, const nlohmann::ordered_json &city_feature, const AttributeSchema &attr_schema, const AttributeSchema *semantic_attr_schema)
Builds one CityFeature table – its CityObjects (visited in ascending id order), vertices,...
::flatbuffers::Offset<::Header > to_fcb_header(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &cj, const HeaderWriterOptions &options, const AttributeSchema &attr_schema, const AttributeSchema *semantic_attr_schema, const std::vector< AttributeIndexInfo > *attribute_indices_info)
Builds the whole Header table from the CityJSON metadata line (the first line of a CityJSONSeq: type/...
One attribute column's B+tree index metadata, as recorded in the header (AttributeIndex,...
One (key, feature byte offset) pair to be indexed.
The finished index: the flat node array concatenated with the payload section (mirrors Stree::stream_...
std::vector< std::uint8_t > bytes
std::uint32_t num_unique_items
std::uint16_t branching_factor
Configuration for FcbWriter.
Configuration for header writing.
std::optional< std::uint16_t > id_index
The branching factor of the index over City Object ids, or std::nullopt for none.
std::optional< std::array< double, 6 > > geographical_extent
One R-tree node entry: 4 doubles then a u64, all little-endian, 40 bytes with no padding (packed_rtre...
static NodeItem empty(std::uint64_t offset)
The "empty" node used as the fold/aggregation identity: any real bbox's expand widens it.