FlatCityBuf C++ reader 0.10.0
Native C++17 reader for FlatCityBuf, the cloud-optimized CityJSON format
Loading...
Searching...
No Matches
header_serializer.cpp
Go to the documentation of this file.
1#include <fcb/error.hpp>
3
4#include <charconv>
5#include <optional>
6#include <string_view>
7
8namespace fcb {
9
10namespace {
11
12std::string as_str_or_empty(const nlohmann::ordered_json& obj, const std::string& key) {
13 auto it = obj.find(key);
14 if (it == obj.end() || !it->is_string())
15 return std::string();
16 return it->get<std::string>();
17}
18
25std::string require_string_field(const nlohmann::ordered_json& obj, const std::string& key) {
26 auto it = obj.find(key);
27 if (it == obj.end() || !it->is_string())
29 "pointOfContact." + key + " is required and must be a string");
30 return it->get<std::string>();
31}
32
43std::optional<std::string> optional_string_field(const nlohmann::ordered_json& obj,
44 const std::string& key) {
45 auto it = obj.find(key);
46 if (it == obj.end() || !it->is_string())
47 return std::nullopt;
48 return it->get<std::string>();
49}
50
56std::optional<std::string> address_member(const nlohmann::ordered_json& address,
57 const std::string& key) {
58 auto it = address.find(key);
59 if (it == address.end() || it->is_null())
60 return std::nullopt;
61 if (it->is_string())
62 return it->get<std::string>();
63 return it->dump();
64}
65
66std::optional<std::string> address_either(const nlohmann::ordered_json& address,
67 const std::string& a, const std::string& b) {
68 if (auto v = address_member(address, a))
69 return v;
70 return address_member(address, b);
71}
72
73std::int32_t parse_i32_whole(std::string_view s) {
74 if (s.empty())
75 return 0;
76 // `std::from_chars` rejects a leading '+' for signed integers, but
77 // Rust's `str::parse::<i32>()` accepts one (its `FromStr` impl allows an
78 // optional leading `+` or `-`) -- ".../EPSG/0/+7415" is a legal `code`
79 // segment there. Strip it here, but only when a digit actually follows,
80 // so a malformed "+-7415" or bare "+" still falls through to failure
81 // below rather than silently parsing "-7415".
82 if (s.front() == '+') {
83 s.remove_prefix(1);
84 if (s.empty() || !(s.front() >= '0' && s.front() <= '9'))
85 return 0;
86 }
87 std::int32_t value = 0;
88 auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
89 if (ec != std::errc() || ptr != s.data() + s.size())
90 return 0;
91 return value;
92}
93
94} // namespace
95
96::Transform to_transform(const nlohmann::ordered_json& transform) {
97 const auto& scale = transform.at("scale");
98 const auto& translate = transform.at("translate");
99 return ::Transform(
100 ::Vector(scale.at(0).get<double>(), scale.at(1).get<double>(), scale.at(2).get<double>()),
101 ::Vector(translate.at(0).get<double>(), translate.at(1).get<double>(),
102 translate.at(2).get<double>()));
103}
104
105std::optional<ParsedReferenceSystem> parse_reference_system(const std::string& url) {
106 static constexpr std::string_view kPrefixes[] = {"http://www.opengis.net/def/crs/",
107 "https://www.opengis.net/def/crs/"};
108 for (const auto& prefix : kPrefixes) {
109 if (url.compare(0, prefix.size(), prefix) != 0)
110 continue;
111
112 const std::string rest = url.substr(prefix.size());
113 std::vector<std::string> segments;
114 std::size_t start = 0;
115 while (true) {
116 const std::size_t pos = rest.find('/', start);
117 const std::size_t end = pos == std::string::npos ? rest.size() : pos;
118 segments.push_back(rest.substr(start, end - start));
119 if (pos == std::string::npos)
120 break;
121 start = pos + 1;
122 }
123
125 out.authority = segments[0];
126 out.version = segments.size() > 1 ? parse_i32_whole(segments[1]) : 0;
127 out.code = segments.size() > 2 ? parse_i32_whole(segments[2]) : 0;
128 return out;
129 }
130 return std::nullopt;
131}
132
133::flatbuffers::Offset<::ReferenceSystem> to_reference_system(::flatbuffers::FlatBufferBuilder& fbb,
134 const ParsedReferenceSystem& ref_sys) {
135 auto authority = fbb.CreateString(ref_sys.authority);
136 return CreateReferenceSystem(fbb, authority, ref_sys.version, ref_sys.code, 0);
137}
138
139::flatbuffers::Offset<::Extension> to_extension(::flatbuffers::FlatBufferBuilder& fbb,
140 const std::string& name, const std::string& url,
141 const std::string& version,
142 const nlohmann::ordered_json& members) {
143 auto name_off = fbb.CreateString(name);
144 auto url_off = fbb.CreateString(url);
145 auto version_off = fbb.CreateString(version);
146 // Compact, in the entry's own key order: what serde_json's `to_string`
147 // gives for Rust's insertion-ordered map. Absent when there are none.
148 std::optional<::flatbuffers::Offset<::flatbuffers::String>> members_off;
149 if (members.is_object() && !members.empty())
150 members_off = fbb.CreateString(members.dump());
151 return CreateExtension(fbb, name_off, 0, url_off, version_off, 0, 0, 0, 0, 0,
152 members_off.value_or(0));
153}
154
155::flatbuffers::Offset<::flatbuffers::Vector<const ::DoubleVertex*>>
156to_templates_vertices(::flatbuffers::FlatBufferBuilder& fbb,
157 const nlohmann::ordered_json& vertices_templates) {
158 std::vector<::DoubleVertex> verts;
159 if (vertices_templates.is_array()) {
160 for (const auto& v : vertices_templates) {
161 if (!v.is_array())
162 continue;
163 std::vector<double> coords;
164 for (const auto& c : v)
165 if (c.is_number())
166 coords.push_back(c.get<double>());
167 if (coords.size() == 3)
168 verts.emplace_back(coords[0], coords[1], coords[2]);
169 }
170 }
171 return fbb.CreateVectorOfStructs(verts);
172}
173
174PocOffsets to_point_of_contact(::flatbuffers::FlatBufferBuilder& fbb,
175 const nlohmann::ordered_json& poc) {
176 PocOffsets out;
177 out.contact_name = fbb.CreateString(require_string_field(poc, "contactName"));
178
179 if (auto v = optional_string_field(poc, "contactType"))
180 out.contact_type = fbb.CreateString(*v);
181 if (auto v = optional_string_field(poc, "role"))
182 out.role = fbb.CreateString(*v);
183 if (auto v = optional_string_field(poc, "phone"))
184 out.phone = fbb.CreateString(*v);
185 out.email = fbb.CreateString(require_string_field(poc, "emailAddress"));
186 if (auto v = optional_string_field(poc, "website"))
187 out.website = fbb.CreateString(*v);
188
189 // `address`'s presence check is the same disclosed leniency as
190 // `optional_string_field`: Rust's `Option<Address>` would reject the
191 // whole document if `address` were present but not a JSON object (an
192 // `Address`'s `#[serde(flatten)]` map requires object shape); this
193 // writer just treats it as absent instead.
194 if (auto addr_it = poc.find("address"); addr_it != poc.end() && addr_it->is_object()) {
195 const nlohmann::ordered_json& address = *addr_it;
196 if (auto v = address_member(address, "thoroughfareNumber"))
197 out.address_thoroughfare_number = fbb.CreateString(*v);
198 if (auto v = address_member(address, "thoroughfareName"))
199 out.address_thoroughfare_name = fbb.CreateString(*v);
200 if (auto v = address_member(address, "locality"))
201 out.address_locality = fbb.CreateString(*v);
202 if (auto v = address_either(address, "postcode", "postalCode"))
203 out.address_postcode = fbb.CreateString(*v);
204 if (auto v = address_member(address, "country"))
205 out.address_country = fbb.CreateString(*v);
206 }
207 return out;
208}
209
210::flatbuffers::Offset<::Header>
211to_fcb_header(::flatbuffers::FlatBufferBuilder& fbb, const nlohmann::ordered_json& cj,
212 const HeaderWriterOptions& options, const AttributeSchema& attr_schema,
213 const AttributeSchema* semantic_attr_schema,
214 const std::vector<AttributeIndexInfo>* attribute_indices_info) {
215 auto version = fbb.CreateString(cj.at("version").get<std::string>());
216 ::Transform transform = to_transform(cj.at("transform"));
217 const std::uint64_t features_count = options.feature_count;
218
219 auto columns = to_columns(fbb, attr_schema, id_column_index(options.id_index, attr_schema));
220 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Column>>>>
221 semantic_columns;
222 if (semantic_attr_schema != nullptr)
223 semantic_columns = to_columns(fbb, *semantic_attr_schema);
224
225 const std::uint16_t index_node_size = options.index_node_size;
226
227 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<const ::AttributeIndex*>>>
228 attribute_index;
229 if (attribute_indices_info != nullptr) {
230 std::vector<::AttributeIndex> entries;
231 entries.reserve(attribute_indices_info->size());
232 for (const auto& info : *attribute_indices_info)
233 entries.emplace_back(info.index, info.length, info.branching_factor,
234 info.num_unique_items);
235 attribute_index = fbb.CreateVectorOfStructs(entries);
236 }
237
238 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Extension>>>>
239 extensions;
240 if (auto it = cj.find("extensions"); it != cj.end() && it->is_object()) {
241 std::vector<::flatbuffers::Offset<::Extension>> ext_offs;
242 for (const auto& [name, ext] : it->items()) {
243 // Every member other than url and version, in the entry's order.
244 nlohmann::ordered_json members = nlohmann::ordered_json::object();
245 if (ext.is_object()) {
246 for (const auto& [key, val] : ext.items())
247 if (key != "url" && key != "version")
248 members[key] = val;
249 }
250 ext_offs.push_back(to_extension(fbb, name, as_str_or_empty(ext, "url"),
251 as_str_or_empty(ext, "version"), members));
252 }
253 extensions = fbb.CreateVector(ext_offs);
254 }
255
256 std::optional<::GeographicalExtent> geographical_extent;
257 if (options.geographical_extent)
258 geographical_extent = to_geographical_extent(*options.geographical_extent);
259
260 std::optional<::flatbuffers::Offset<::Appearance>> appearance;
261 if (auto it = cj.find("appearance"); it != cj.end() && it->is_object())
262 appearance = to_appearance(fbb, *it);
263
264 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<const ::DoubleVertex*>>>
265 templates_vertices;
266 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Geometry>>>>
267 templates;
268 if (auto gm_it = cj.find("geometry-templates"); gm_it != cj.end() && gm_it->is_object()) {
269 templates_vertices = to_templates_vertices(fbb, gm_it->at("vertices-templates"));
270
271 std::vector<::flatbuffers::Offset<::Geometry>> geom_offs;
272 for (const auto& g : gm_it->at("templates"))
273 geom_offs.push_back(to_geometry(fbb, g, semantic_attr_schema));
274 templates = fbb.CreateVector(geom_offs);
275 }
276
277 std::optional<::flatbuffers::Offset<::ReferenceSystem>> reference_system;
278 std::optional<::flatbuffers::Offset<::flatbuffers::String>> identifier;
279 std::optional<::flatbuffers::Offset<::flatbuffers::String>> reference_date;
280 std::optional<::flatbuffers::Offset<::flatbuffers::String>> title;
281 PocOffsets poc;
282
283 if (auto meta_it = cj.find("metadata"); meta_it != cj.end() && meta_it->is_object()) {
284 const nlohmann::ordered_json& meta = *meta_it;
285
286 if (auto rs_it = meta.find("referenceSystem"); rs_it != meta.end() && rs_it->is_string()) {
287 if (auto parsed = parse_reference_system(rs_it->get<std::string>()))
288 reference_system = to_reference_system(fbb, *parsed);
289 }
290
291 if (!geographical_extent) {
292 if (auto ge_it = meta.find("geographicalExtent");
293 ge_it != meta.end() && ge_it->is_array() && ge_it->size() == 6) {
294 std::array<double, 6> extent{};
295 for (std::size_t i = 0; i < 6; ++i)
296 extent[i] = ge_it->at(i).get<double>();
297 geographical_extent = to_geographical_extent(extent);
298 }
299 }
300
301 if (auto v = optional_string_field(meta, "identifier"))
302 identifier = fbb.CreateString(*v);
303 if (auto v = optional_string_field(meta, "referenceDate"))
304 reference_date = fbb.CreateString(*v);
305 if (auto v = optional_string_field(meta, "title"))
306 title = fbb.CreateString(*v);
307
308 if (auto poc_it = meta.find("pointOfContact"); poc_it != meta.end() && poc_it->is_object())
309 poc = to_point_of_contact(fbb, *poc_it);
310 }
311
312 // `CreateHeader` (flatc-generated, header_generated.h) is used here
313 // instead of hand-sequenced `HeaderBuilder::add_*` calls: flatc's
314 // generated `Create*` helper adds fields in a fixed, WIDTH-sorted order
315 // (widest fields first) to minimize padding, and it does so IDENTICALLY
316 // across every language backend -- which is the only reason Rust's and
317 // C++'s output can be byte-identical at all. A field's byte offset
318 // WITHIN the table is determined by the order its `add_*` was actually
319 // CALLED (each call appends at the builder's current cursor), so calling
320 // them by hand in any other order -- e.g. grouped by CityJSON-source
321 // semantics, as this function's own local-variable order reads -- lays
322 // the table out differently even though every field ends up present
323 // with the right value: a real byte-exact regression this milestone's
324 // own oracle test caught (see test_writer_oracle.cpp).
325 return CreateHeader(
326 fbb, &transform, appearance.value_or(0), columns, semantic_columns.value_or(0),
327 features_count, index_node_size, attribute_index.value_or(0),
328 geographical_extent ? &*geographical_extent : nullptr, reference_system.value_or(0),
329 identifier.value_or(0), reference_date.value_or(0), title.value_or(0),
330 templates.value_or(0), templates_vertices.value_or(0), extensions.value_or(0),
331 poc.contact_name.value_or(0), poc.contact_type.value_or(0), poc.role.value_or(0),
332 poc.phone.value_or(0), poc.email.value_or(0), poc.website.value_or(0),
333 poc.address_thoroughfare_number.value_or(0), poc.address_thoroughfare_name.value_or(0),
334 poc.address_locality.value_or(0), poc.address_postcode.value_or(0),
335 poc.address_country.value_or(0), /*attributes=*/0, version);
336}
337
338} // namespace fcb
Every failure the library reports is one of these.
Definition error.hpp:31
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Column > > > to_columns(::flatbuffers::FlatBufferBuilder &fbb, const AttributeSchema &schema, std::optional< std::uint16_t > id_column=std::nullopt)
Builds the Column vector for Header.columns or CityObject.columns, in ascending column-index order.
@ MissingRequiredField
Definition error.hpp:18
::flatbuffers::Offset<::Extension > to_extension(::flatbuffers::FlatBufferBuilder &fbb, const std::string &name, const std::string &url, const std::string &version, const nlohmann::ordered_json &members)
Builds one extensions entry: name, url, version, and members – every other member of the entry,...
::Transform to_transform(const nlohmann::ordered_json &transform)
Builds the Transform struct (scale + translate) from CityJSON's top-level transform member.
std::map< std::string, std::pair< std::uint16_t, ::ColumnType > > AttributeSchema
Attribute schema: name -> (column index, column type).
Definition attribute.hpp:43
::flatbuffers::Offset<::flatbuffers::Vector< const ::DoubleVertex * > > to_templates_vertices(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &vertices_templates)
Builds Header.templates_vertices from CityJSON's geometry-templates.vertices-templates (f64 precision...
PocOffsets to_point_of_contact(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &poc)
::flatbuffers::Offset<::Appearance > to_appearance(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &appearance)
Builds the Appearance table (materials, textures, UV vertices, default themes) from a CityJSON appear...
::flatbuffers::Offset<::Geometry > to_geometry(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &geometry, const AttributeSchema *semantic_attr_schema)
Builds one Geometry table – boundaries, and whatever semantics, material and texture it carries – fro...
::GeographicalExtent to_geographical_extent(const std::array< double, 6 > &extent)
Builds a GeographicalExtent struct from a 6-element [minx,miny,minz,maxx,maxy,maxz] array.
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...
::flatbuffers::Offset<::ReferenceSystem > to_reference_system(::flatbuffers::FlatBufferBuilder &fbb, const ParsedReferenceSystem &ref_sys)
Builds the ReferenceSystem table from a parsed metadata.referenceSystem URL.
std::optional< ParsedReferenceSystem > parse_reference_system(const std::string &url)
Parses a referenceSystem URL (https://www.opengis.net/def/crs/{authority}/{version}...
::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/...
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
A metadata.referenceSystem URL, parsed into its OGC three-element form.
Builds the pointOfContact fields of a header from CityJSON metadata.pointOfContact.
std::optional<::flatbuffers::Offset<::flatbuffers::String > > contact_name
std::optional<::flatbuffers::Offset<::flatbuffers::String > > role
std::optional<::flatbuffers::Offset<::flatbuffers::String > > phone
std::optional<::flatbuffers::Offset<::flatbuffers::String > > website
std::optional<::flatbuffers::Offset<::flatbuffers::String > > address_postcode
std::optional<::flatbuffers::Offset<::flatbuffers::String > > email
std::optional<::flatbuffers::Offset<::flatbuffers::String > > address_thoroughfare_number
std::optional<::flatbuffers::Offset<::flatbuffers::String > > address_country
std::optional<::flatbuffers::Offset<::flatbuffers::String > > address_thoroughfare_name
std::optional<::flatbuffers::Offset<::flatbuffers::String > > contact_type
std::optional<::flatbuffers::Offset<::flatbuffers::String > > address_locality