FlatCityBuf C++ reader 0.10.0
Native C++17 reader for FlatCityBuf, the cloud-optimized CityJSON format
Loading...
Searching...
No Matches
feature_serializer.cpp
Go to the documentation of this file.
2
3#ifdef FCB_WITH_JSON
4
5# include <fcb/error.hpp>
6
7# include <algorithm>
8# include <cstdint>
9# include <limits>
10# include <string>
11
12namespace fcb {
13
14namespace {
15
16// Same 33 strings, in the same enum order, as cityjson.cpp's
17// kCityObjectTypeNames -- kept separate rather than shared, mirroring
18// Rust's own split between deserializer.rs's to_cj_co_type (read) and
19// serializer.rs's to_co_type (write).
20const char* const kCityObjectTypeNames[] = {
21 "Bridge",
22 "BridgePart",
23 "BridgeInstallation",
24 "BridgeConstructiveElement",
25 "BridgeRoom",
26 "BridgeFurniture",
27 "Building",
28 "BuildingPart",
29 "BuildingInstallation",
30 "BuildingConstructiveElement",
31 "BuildingFurniture",
32 "BuildingStorey",
33 "BuildingRoom",
34 "BuildingUnit",
35 "CityFurniture",
36 "CityObjectGroup",
37 "GenericCityObject",
38 "LandUse",
39 "OtherConstruction",
40 "PlantCover",
41 "SolitaryVegetationObject",
42 "TINRelief",
43 "Road",
44 "Railway",
45 "Waterway",
46 "TransportSquare",
47 "Tunnel",
48 "TunnelPart",
49 "TunnelInstallation",
50 "TunnelConstructiveElement",
51 "TunnelHollowSpace",
52 "TunnelFurniture",
53 "WaterBody",
54};
55constexpr std::size_t kCityObjectTypeCount =
56 sizeof(kCityObjectTypeNames) / sizeof(kCityObjectTypeNames[0]);
57
58const char* const kSemanticSurfaceTypeNames[] = {
59 "RoofSurface", "GroundSurface", "WallSurface", "ClosureSurface",
60 "OuterCeilingSurface", "OuterFloorSurface", "Window", "Door",
61 "InteriorWallSurface", "CeilingSurface", "FloorSurface", "WaterSurface",
62 "WaterGroundSurface", "WaterClosureSurface", "TrafficArea", "AuxiliaryTrafficArea",
63 "TransportationMarking", "TransportationHole",
64};
65constexpr std::size_t kSemanticSurfaceTypeCount =
66 sizeof(kSemanticSurfaceTypeNames) / sizeof(kSemanticSurfaceTypeNames[0]);
67
68std::optional<::flatbuffers::Offset<::flatbuffers::Vector<double>>>
69to_color(::flatbuffers::FlatBufferBuilder& fbb, const nlohmann::ordered_json& obj,
70 const char* key) {
71 auto it = obj.find(key);
72 if (it == obj.end() || it->is_null())
73 return std::nullopt;
74 std::vector<double> v;
75 for (const auto& c : *it)
76 v.push_back(c.get<double>());
77 return fbb.CreateVector(v);
78}
79
86::flatbuffers::Offset<::SemanticObject>
87to_semantic_object(::flatbuffers::FlatBufferBuilder& fbb, const nlohmann::ordered_json& surface,
88 const AttributeSchema* semantic_attr_schema) {
89 auto [type_, extension_type_name] =
90 semantic_surface_type_from_name(surface.at("type").get<std::string>());
91
92 // Builder call order matches Rust's `to_geometry` semantic-object arm
93 // (writer/serializer.rs:920-949) exactly: `children` is created BEFORE
94 // `extension_type`. FlatBuffers builder calls are side-effecting (each
95 // appends to the buffer), so this order is part of the wire format, not
96 // just source-code style -- it must be sequenced with separate named
97 // locals, never left to argument-evaluation order.
98 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<std::uint32_t>>> children;
99 if (auto it = surface.find("children"); it != surface.end() && it->is_array()) {
100 std::vector<std::uint32_t> c;
101 for (const auto& v : *it)
102 c.push_back(v.get<std::uint32_t>());
103 children = fbb.CreateVector(c);
104 }
105
106 auto extension_type =
107 extension_type_name ? std::optional(fbb.CreateString(*extension_type_name)) : std::nullopt;
108
109 ::flatbuffers::Optional<std::uint32_t> parent = ::flatbuffers::nullopt;
110 if (auto it = surface.find("parent"); it != surface.end() && !it->is_null())
111 parent = it->get<std::uint32_t>();
112
113 nlohmann::ordered_json other = nlohmann::ordered_json::object();
114 for (const auto& [key, val] : surface.items())
115 if (key != "type" && key != "parent" && key != "children")
116 other[key] = val;
117
118 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<std::uint8_t>>> attributes;
119 if (!other.empty() && semantic_attr_schema != nullptr) {
120 attributes = fbb.CreateVector(encode_attributes_with_schema(other, *semantic_attr_schema));
121 }
122
123 return CreateSemanticObject(fbb, type_, attributes.value_or(0), children.value_or(0), parent,
124 extension_type.value_or(0));
125}
126
127} // namespace
128
129CoType city_object_type_from_name(const std::string& name) {
130 for (std::size_t i = 0; i < kCityObjectTypeCount; ++i) {
131 if (name == kCityObjectTypeNames[i])
132 return {static_cast<::CityObjectType>(i), std::nullopt};
133 }
134 return {::CityObjectType::ExtensionObject, name};
135}
136
138 for (std::size_t i = 0; i < kSemanticSurfaceTypeCount; ++i) {
139 if (name == kSemanticSurfaceTypeNames[i])
140 return {static_cast<::SemanticSurfaceType>(i), std::nullopt};
141 }
142 return {::SemanticSurfaceType::ExtraSemanticSurface, name};
143}
144
145::flatbuffers::Offset<::Appearance> to_appearance(::flatbuffers::FlatBufferBuilder& fbb,
146 const nlohmann::ordered_json& appearance) {
147 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Material>>>>
148 materials_off;
149 if (auto it = appearance.find("materials"); it != appearance.end() && it->is_array()) {
150 std::vector<::flatbuffers::Offset<::Material>> materials;
151 for (const auto& m : *it) {
152 // Builder call order matches Rust's `to_appearance` material arm
153 // (writer/serializer.rs:542-566) exactly: name, then
154 // diffuse/emissive/specular color IN THAT ORDER, each a
155 // separate sequenced statement -- C++ does not specify
156 // function-argument evaluation order, so these side-effecting
157 // `fbb.CreateVector`/`CreateString` calls must never be written
158 // as inline call arguments.
159 auto name = fbb.CreateString(m.at("name").get<std::string>());
160 auto diffuse_color = to_color(fbb, m, "diffuseColor");
161 auto emissive_color = to_color(fbb, m, "emissiveColor");
162 auto specular_color = to_color(fbb, m, "specularColor");
163
164 auto ambient = m.find("ambientIntensity");
165 auto shininess = m.find("shininess");
166 auto transparency = m.find("transparency");
167 auto is_smooth = m.find("isSmooth");
168 materials.push_back(CreateMaterial(
169 fbb, name,
170 ambient != m.end() && !ambient->is_null()
171 ? ::flatbuffers::Optional<double>(ambient->get<double>())
172 : ::flatbuffers::nullopt,
173 diffuse_color.value_or(0), emissive_color.value_or(0), specular_color.value_or(0),
174 shininess != m.end() && !shininess->is_null()
175 ? ::flatbuffers::Optional<double>(shininess->get<double>())
176 : ::flatbuffers::nullopt,
177 transparency != m.end() && !transparency->is_null()
178 ? ::flatbuffers::Optional<double>(transparency->get<double>())
179 : ::flatbuffers::nullopt,
180 is_smooth != m.end() && !is_smooth->is_null()
181 ? ::flatbuffers::Optional<bool>(is_smooth->get<bool>())
182 : ::flatbuffers::nullopt));
183 }
184 materials_off = fbb.CreateVector(materials);
185 }
186
187 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Texture>>>>
188 textures_off;
189 if (auto it = appearance.find("textures"); it != appearance.end() && it->is_array()) {
190 std::vector<::flatbuffers::Offset<::Texture>> textures;
191 for (const auto& t : *it) {
192 // `type` maps `Some(PNG)|absent -> PNG`; only "JPG" (any case
193 // handled by exact string match) selects the other tag.
194 auto type_it = t.find("type");
195 const ::TextureFormat format = (type_it != t.end() && *type_it == "JPG")
196 ? ::TextureFormat::JPG
197 : ::TextureFormat::PNG;
198 auto image = fbb.CreateString(t.value("image", std::string()));
199
200 ::flatbuffers::Optional<::WrapMode> wrap_mode = ::flatbuffers::nullopt;
201 if (auto w = t.find("wrapMode"); w != t.end() && !w->is_null()) {
202 const std::string& s = w->get_ref<const std::string&>();
203 if (s == "none")
204 wrap_mode = ::WrapMode::None;
205 else if (s == "wrap")
206 wrap_mode = ::WrapMode::Wrap;
207 else if (s == "mirror")
208 wrap_mode = ::WrapMode::Mirror;
209 else if (s == "clamp")
210 wrap_mode = ::WrapMode::Clamp;
211 else if (s == "border")
212 wrap_mode = ::WrapMode::Border;
213 }
214
215 ::flatbuffers::Optional<::TextureType> texture_type = ::flatbuffers::nullopt;
216 if (auto tt = t.find("textureType"); tt != t.end() && !tt->is_null()) {
217 const std::string& s = tt->get_ref<const std::string&>();
218 if (s == "unknown")
219 texture_type = ::TextureType::Unknown;
220 else if (s == "specific")
221 texture_type = ::TextureType::Specific;
222 else if (s == "typical")
223 texture_type = ::TextureType::Typical;
224 }
225
226 // Builder call order matches Rust's texture arm
227 // (writer/serializer.rs:579-599): `image` (already a separate
228 // statement above), then `border_color`, sequenced explicitly
229 // for the same reason as the material loop above.
230 auto border_color = to_color(fbb, t, "borderColor");
231 textures.push_back(CreateTexture(fbb, format, image, wrap_mode, texture_type,
232 border_color.value_or(0)));
233 }
234 textures_off = fbb.CreateVector(textures);
235 }
236
237 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<const ::Vec2*>>> vertices_texture_off;
238 if (auto it = appearance.find("vertices-texture"); it != appearance.end() && it->is_array()) {
239 std::vector<::Vec2> uvs;
240 for (const auto& v : *it)
241 uvs.push_back(::Vec2(v.at(0).get<double>(), v.at(1).get<double>()));
242 vertices_texture_off = fbb.CreateVectorOfStructs(uvs);
243 }
244
245 std::optional<::flatbuffers::Offset<::flatbuffers::String>> default_theme_texture_off;
246 if (auto it = appearance.find("default-theme-texture");
247 it != appearance.end() && it->is_string())
248 default_theme_texture_off = fbb.CreateString(it->get<std::string>());
249
250 std::optional<::flatbuffers::Offset<::flatbuffers::String>> default_theme_material_off;
251 if (auto it = appearance.find("default-theme-material");
252 it != appearance.end() && it->is_string())
253 default_theme_material_off = fbb.CreateString(it->get<std::string>());
254
255 return CreateAppearance(fbb, materials_off.value_or(0), textures_off.value_or(0),
256 vertices_texture_off.value_or(0), default_theme_texture_off.value_or(0),
257 default_theme_material_off.value_or(0));
258}
259
260::flatbuffers::Offset<::Geometry> to_geometry(::flatbuffers::FlatBufferBuilder& fbb,
261 const nlohmann::ordered_json& geometry,
262 const AttributeSchema* semantic_attr_schema) {
263 const GeometryKind kind = geometry_kind_from_name(geometry.at("type").get<std::string>());
264 const auto type_ = static_cast<::GeometryType>(kind);
265 auto lod = geometry.find("lod");
266 auto lod_off = (lod != geometry.end() && lod->is_string())
267 ? std::optional(fbb.CreateString(lod->get<std::string>()))
268 : std::nullopt;
269
270 EncodedGeometry encoded = encode(geometry);
271 auto solids_off = fbb.CreateVector(encoded.boundaries.solids);
272 auto shells_off = fbb.CreateVector(encoded.boundaries.shells);
273 auto surfaces_off = fbb.CreateVector(encoded.boundaries.surfaces);
274 auto strings_off = fbb.CreateVector(encoded.boundaries.strings);
275 auto boundaries_off = fbb.CreateVector(encoded.boundaries.indices);
276
277 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<std::uint32_t>>> semantics_values_off;
278 std::optional<
279 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::SemanticObject>>>>
280 semantics_objects_off;
281 if (encoded.semantics) {
282 std::vector<::flatbuffers::Offset<::SemanticObject>> objects;
283 for (const auto& surface : encoded.semantics->surfaces)
284 objects.push_back(to_semantic_object(fbb, surface, semantic_attr_schema));
285 semantics_objects_off = fbb.CreateVector(objects);
286 if (encoded.semantics->values)
287 semantics_values_off = fbb.CreateVector(*encoded.semantics->values);
288 }
289
290 std::optional<
291 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::MaterialMapping>>>>
292 material_off;
293 if (encoded.materials) {
294 std::vector<::flatbuffers::Offset<::MaterialMapping>> mappings;
295 for (const auto& m : *encoded.materials) {
296 auto theme = fbb.CreateString(m.theme);
297 switch (m.kind) {
299 mappings.push_back(CreateMaterialMapping(
300 fbb, theme, 0, 0, 0, ::flatbuffers::Optional<std::uint32_t>(m.value)));
301 break;
303 // Present-but-empty: created unconditionally, even when
304 // a level genuinely has zero entries, so `[]` stays
305 // distinct from an absent field. Order (solids, shells,
306 // vertices) matches Rust's `GMMaterialMapping::Values`
307 // arm (writer/serializer.rs:966-978) exactly, as three
308 // separately sequenced statements -- see the
309 // to_semantic_object note on why this cannot be inline
310 // call arguments.
311 auto solids = fbb.CreateVector(m.solids);
312 auto shells = fbb.CreateVector(m.shells);
313 auto vertices = fbb.CreateVector(m.vertices);
314 mappings.push_back(CreateMaterialMapping(fbb, theme, solids, shells, vertices,
315 ::flatbuffers::nullopt));
316 break;
317 }
319 mappings.push_back(
320 CreateMaterialMapping(fbb, theme, 0, 0, 0, ::flatbuffers::nullopt));
321 break;
322 }
323 }
324 material_off = fbb.CreateVector(mappings);
325 }
326
327 std::optional<
328 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::TextureMapping>>>>
329 texture_off;
330 if (encoded.textures) {
331 std::vector<::flatbuffers::Offset<::TextureMapping>> mappings;
332 for (const auto& t : *encoded.textures) {
333 auto theme = fbb.CreateString(t.theme);
334 if (t.has_values) {
335 // As with material Values: all five arrays are created
336 // unconditionally, even where empty. Order (solids, shells,
337 // surfaces, strings, vertices) matches Rust's texture arm
338 // (writer/serializer.rs:1022-1029) exactly, as five
339 // separately sequenced statements.
340 auto solids = fbb.CreateVector(t.solids);
341 auto shells = fbb.CreateVector(t.shells);
342 auto surfaces = fbb.CreateVector(t.surfaces);
343 auto strings = fbb.CreateVector(t.strings);
344 auto vertices = fbb.CreateVector(t.vertices);
345 mappings.push_back(
346 CreateTextureMapping(fbb, theme, solids, shells, surfaces, strings, vertices));
347 } else {
348 mappings.push_back(CreateTextureMapping(fbb, theme, 0, 0, 0, 0, 0));
349 }
350 }
351 texture_off = fbb.CreateVector(mappings);
352 }
353
354 return CreateGeometry(fbb, type_, lod_off.value_or(0), solids_off, shells_off, surfaces_off,
355 strings_off, boundaries_off, semantics_values_off.value_or(0),
356 semantics_objects_off.value_or(0), material_off.value_or(0),
357 texture_off.value_or(0));
358}
359
360::flatbuffers::Offset<::GeometryInstance>
361to_geometry_instance(::flatbuffers::FlatBufferBuilder& fbb,
362 const nlohmann::ordered_json& geometry) {
363 if (geometry.at("type").get<std::string>() != "GeometryInstance") {
365 "to_geometry_instance called on a non-GeometryInstance geometry");
366 }
367
368 const std::uint32_t template_ = geometry.at("template").get<std::uint32_t>();
369
370 std::vector<std::uint32_t> indices;
371 for (const auto& v : geometry.at("boundaries"))
372 indices.push_back(v.get<std::uint32_t>());
373 auto boundaries_off = fbb.CreateVector(indices);
374
375 const auto& m = geometry.at("transformationMatrix");
376 ::TransformationMatrix matrix(
377 m.at(0).get<double>(), m.at(1).get<double>(), m.at(2).get<double>(), m.at(3).get<double>(),
378 m.at(4).get<double>(), m.at(5).get<double>(), m.at(6).get<double>(), m.at(7).get<double>(),
379 m.at(8).get<double>(), m.at(9).get<double>(), m.at(10).get<double>(),
380 m.at(11).get<double>(), m.at(12).get<double>(), m.at(13).get<double>(),
381 m.at(14).get<double>(), m.at(15).get<double>());
382
383 return CreateGeometryInstance(fbb, &matrix, template_, boundaries_off);
384}
385
386::GeographicalExtent to_geographical_extent(const std::array<double, 6>& extent) {
387 return ::GeographicalExtent(::Vector(extent[0], extent[1], extent[2]),
388 ::Vector(extent[3], extent[4], extent[5]));
389}
390
391namespace {
392
396std::int32_t to_vertex_coordinate(const nlohmann::ordered_json& c) {
397 const auto v = c.get<std::int64_t>();
398 if (v < std::numeric_limits<std::int32_t>::min() ||
399 v > std::numeric_limits<std::int32_t>::max())
400 throw Error(ErrorCode::VertexOutOfRange,
401 "vertex coordinate " + std::to_string(v) +
402 " is outside the 32-bit range of a FlatCityBuf Vertex");
403 return static_cast<std::int32_t>(v);
404}
405
409struct FcbAttribute {
410 ::flatbuffers::Offset<::flatbuffers::Vector<std::uint8_t>> attr_offset;
411 std::optional<AttributeSchema> own_schema;
412};
413
414FcbAttribute to_fcb_attribute(::flatbuffers::FlatBufferBuilder& fbb,
415 const nlohmann::ordered_json& attr, const AttributeSchema& schema) {
416 bool is_own_schema = false;
417 for (const auto& [key, val] : attr.items()) {
418 if (schema.find(key) == schema.end()) {
419 is_own_schema = true;
420 break;
421 }
422 }
423 if (is_own_schema) {
424 AttributeSchema own_schema;
425 add_attributes(own_schema, attr);
426 auto encoded = encode_attributes_with_schema(attr, own_schema);
427 return {fbb.CreateVector(encoded), std::move(own_schema)};
428 }
429 auto encoded = encode_attributes_with_schema(attr, schema);
430 return {fbb.CreateVector(encoded), std::nullopt};
431}
432
433} // namespace
434
435::flatbuffers::Offset<::Address> to_address(::flatbuffers::FlatBufferBuilder& fbb,
436 const nlohmann::ordered_json& address) {
437 if (!address.is_object())
438 throw Error(ErrorCode::JsonError, "a City Object address must be a JSON object");
439
440 // Rust's order: `location`, then the attribute blob, then its columns.
441 std::optional<::flatbuffers::Offset<::Geometry>> location_off;
442 nlohmann::ordered_json other = nlohmann::ordered_json::object();
443 for (const auto& [key, val] : address.items()) {
444 if (key == "location")
445 location_off = to_geometry(fbb, val, nullptr);
446 else
447 other[key] = val;
448 }
449
450 // Keyed on the members being present at all, before any `null` is
451 // dropped: `{"unit": null}` still writes an (empty) blob and columns.
452 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<std::uint8_t>>> attributes_off;
453 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Column>>>>
454 columns_off;
455 if (!other.empty()) {
456 AttributeSchema schema;
457 add_attributes(schema, other);
458 auto encoded = encode_attributes_with_schema(other, schema);
459 attributes_off = fbb.CreateVector(encoded);
460 columns_off = to_columns(fbb, schema);
461 }
462 return CreateAddress(fbb, attributes_off.value_or(0), columns_off.value_or(0),
463 location_off.value_or(0));
464}
465
466::flatbuffers::Offset<::CityObject> to_city_object(::flatbuffers::FlatBufferBuilder& fbb,
467 const std::string& id,
468 const nlohmann::ordered_json& co,
469 const AttributeSchema& attr_schema,
470 const AttributeSchema* semantic_attr_schema) {
471 auto id_off = fbb.CreateString(id);
472 auto [type_, extension_type_name] =
473 city_object_type_from_name(co.at("type").get<std::string>());
474 auto extension_type_off =
475 extension_type_name ? std::optional(fbb.CreateString(*extension_type_name)) : std::nullopt;
476
477 std::optional<::GeographicalExtent> extent;
478 if (auto it = co.find("geographicalExtent");
479 it != co.end() && it->is_array() && it->size() == 6) {
480 extent = to_geographical_extent({it->at(0).get<double>(), it->at(1).get<double>(),
481 it->at(2).get<double>(), it->at(3).get<double>(),
482 it->at(4).get<double>(), it->at(5).get<double>()});
483 }
484
485 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Geometry>>>>
486 geometry_off;
487 std::optional<
488 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::GeometryInstance>>>>
489 geometry_instances_off;
490 if (auto git = co.find("geometry"); git != co.end() && git->is_array()) {
491 // TWO FULL PASSES, matching Rust's `to_city_object` exactly
492 // (writer/serializer.rs:644-670): it filters "geometry" into a
493 // non-instance list and an instance list FIRST, builds every
494 // non-instance table AND CREATES THEIR VECTOR, and ONLY THEN builds
495 // every instance table and creates ITS vector. A single interleaved
496 // pass (building each entry as visited, in original array order)
497 // produces a DIFFERENT physical child allocation order in the
498 // FlatBuffer whenever instances and non-instances are interleaved in
499 // the source. Just as importantly, the "geoms" vector must be
500 // CREATED before any `to_geometry_instance` call runs, not after
501 // both loops finish -- Rust creates it immediately once the
502 // non-instance loop's `.collect()` completes, so every
503 // `fbb.CreateVector`/`CreateString` call inside `to_geometry_instance`
504 // happens strictly AFTER it on the Rust side too. The two orderings
505 // are not observably different by DECODED content, only by byte
506 // layout, so no functional test catches a regression here; only a
507 // byte-exact oracle over a file with interleaved geometry does (see
508 // test_writer_oracle.cpp's "interleaved geometry" case, which
509 // caught exactly this once already).
510 std::vector<::flatbuffers::Offset<::Geometry>> geoms;
511 for (const auto& g : *git)
512 if (g.at("type").get<std::string>() != "GeometryInstance")
513 geoms.push_back(to_geometry(fbb, g, semantic_attr_schema));
514 geometry_off = fbb.CreateVector(geoms);
515
516 std::vector<::flatbuffers::Offset<::GeometryInstance>> instances;
517 for (const auto& g : *git)
518 if (g.at("type").get<std::string>() == "GeometryInstance")
519 instances.push_back(to_geometry_instance(fbb, g));
520 // Both created -- even empty -- whenever "geometry" is present at
521 // all, matching Rust's Option<Vec<_>> filtered from ONE Option: it
522 // is the presence of the key, not either resulting list's own
523 // emptiness, that decides presence on the wire.
524 geometry_instances_off = fbb.CreateVector(instances);
525 }
526
527 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<std::uint8_t>>> attributes_off;
528 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Column>>>>
529 columns_off;
530 if (auto ait = co.find("attributes"); ait != co.end() && ait->is_object()) {
531 FcbAttribute fcb_attr = to_fcb_attribute(fbb, *ait, attr_schema);
532 attributes_off = fcb_attr.attr_offset;
533 if (fcb_attr.own_schema)
534 columns_off = to_columns(fbb, *fcb_attr.own_schema);
535 }
536
537 std::optional<
538 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>>>
539 children_off;
540 if (auto it = co.find("children"); it != co.end() && it->is_array()) {
541 std::vector<::flatbuffers::Offset<::flatbuffers::String>> c;
542 for (const auto& s : *it)
543 c.push_back(fbb.CreateString(s.get<std::string>()));
544 children_off = fbb.CreateVector(c);
545 }
546
547 // "children_roles" (CityObjectGroup only; the cjseq field is
548 // `children_roles`, snake_case like the FlatBuffers field itself, NOT
549 // camelCase -- confirmed against the cjseq2 source during the M3 codex
550 // review, correcting an earlier unverified guess of "childrenRoles").
551 // An unspecified role is `null` in CityJSON; the header has no way to
552 // spell that, so it is written as the empty string, mirroring the
553 // equivalent handling for point-of-contact strings elsewhere in this
554 // writer.
555 std::optional<
556 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>>>
557 children_roles_off;
558 if (auto it = co.find("children_roles"); it != co.end() && it->is_array()) {
559 std::vector<::flatbuffers::Offset<::flatbuffers::String>> r;
560 for (const auto& role : *it)
561 r.push_back(
562 fbb.CreateString(role.is_string() ? role.get<std::string>() : std::string()));
563 children_roles_off = fbb.CreateVector(r);
564 }
565
566 std::optional<
567 ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>>>
568 parents_off;
569 if (auto it = co.find("parents"); it != co.end() && it->is_array()) {
570 std::vector<::flatbuffers::Offset<::flatbuffers::String>> p;
571 for (const auto& s : *it)
572 p.push_back(fbb.CreateString(s.get<std::string>()));
573 parents_off = fbb.CreateVector(p);
574 }
575
576 // Built after `parents`, as in Rust, so the bytes match.
577 std::optional<::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::Address>>>>
578 address_off;
579 if (auto it = co.find("address"); it != co.end() && it->is_array()) {
580 std::vector<::flatbuffers::Offset<::Address>> a;
581 for (const auto& entry : *it)
582 a.push_back(to_address(fbb, entry));
583 address_off = fbb.CreateVector(a);
584 }
585
586 return CreateCityObject(
587 fbb, type_, extension_type_off.value_or(0), id_off, extent ? &*extent : nullptr,
588 geometry_off.value_or(0), geometry_instances_off.value_or(0), attributes_off.value_or(0),
589 columns_off.value_or(0), children_off.value_or(0), children_roles_off.value_or(0),
590 parents_off.value_or(0), address_off.value_or(0));
591}
592
593std::pair<::flatbuffers::Offset<::CityFeature>, NodeItem>
594to_fcb_city_feature(::flatbuffers::FlatBufferBuilder& fbb, const std::string& id,
595 const nlohmann::ordered_json& city_feature, const AttributeSchema& attr_schema,
596 const AttributeSchema* semantic_attr_schema) {
597 auto id_off = fbb.CreateString(id);
598
599 // `CityObjects` is a JSON object, so visited in ascending id order for
600 // reproducibility -- same determinism reasoning as
601 // cityfeature_to_index_entries (writer/attribute.hpp).
602 static const nlohmann::ordered_json kEmptyObjects = nlohmann::ordered_json::object();
603 auto co_it = city_feature.find("CityObjects");
604 const nlohmann::ordered_json& city_objects =
605 (co_it != city_feature.end() && co_it->is_object()) ? *co_it : kEmptyObjects;
606
607 std::vector<std::string> object_ids;
608 object_ids.reserve(city_objects.size());
609 for (const auto& [oid, unused] : city_objects.items())
610 object_ids.push_back(oid);
611 std::sort(object_ids.begin(), object_ids.end());
612
613 std::vector<::flatbuffers::Offset<::CityObject>> objects;
614 objects.reserve(object_ids.size());
615 for (const auto& oid : object_ids)
616 objects.push_back(
617 to_city_object(fbb, oid, city_objects.at(oid), attr_schema, semantic_attr_schema));
618 auto objects_off = fbb.CreateVector(objects);
619
620 std::vector<::Vertex> fb_vertices;
621 double min_x = 0, min_y = 0, max_x = 0, max_y = 0;
622 bool first = true;
623 if (auto it = city_feature.find("vertices"); it != city_feature.end()) {
624 fb_vertices.reserve(it->size());
625 for (const auto& v : *it) {
626 const double x = v.at(0).get<double>();
627 const double y = v.at(1).get<double>();
628 fb_vertices.emplace_back(to_vertex_coordinate(v.at(0)), to_vertex_coordinate(v.at(1)),
629 to_vertex_coordinate(v.at(2)));
630 if (first) {
631 min_x = max_x = x;
632 min_y = max_y = y;
633 first = false;
634 } else {
635 min_x = std::min(min_x, x);
636 max_x = std::max(max_x, x);
637 min_y = std::min(min_y, y);
638 max_y = std::max(max_y, y);
639 }
640 }
641 }
642 auto vertices_off = fbb.CreateVectorOfStructs(fb_vertices);
643
644 std::optional<::flatbuffers::Offset<::Appearance>> appearance_off;
645 if (auto it = city_feature.find("appearance"); it != city_feature.end() && it->is_object())
646 appearance_off = to_appearance(fbb, *it);
647
648 NodeItem bbox{min_x, min_y, max_x, max_y, 0};
649 auto feature_off =
650 CreateCityFeature(fbb, id_off, objects_off, vertices_off, appearance_off.value_or(0));
651 return {feature_off, bbox};
652}
653
654} // namespace fcb
655
656#endif // FCB_WITH_JSON
Every failure the library reports is one of these.
Definition error.hpp:31
GeometryKind geometry_kind_from_name(const std::string &name)
Maps a CityJSON geometry type string to GeometryKind.
std::vector< std::uint8_t > encode_attributes_with_schema(const nlohmann::ordered_json &attr, const AttributeSchema &schema)
Encodes attr (a CityJSON attributes object) against schema: repeated [u16 LE column index][value] rec...
::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.
@ InvalidAttributeValue
Definition error.hpp:20
std::map< std::string, std::pair< std::uint16_t, ::ColumnType > > AttributeSchema
Attribute schema: name -> (column index, column type).
Definition attribute.hpp:43
::flatbuffers::Offset<::CityObject > to_city_object(::flatbuffers::FlatBufferBuilder &fbb, const std::string &id, const nlohmann::ordered_json &co, const AttributeSchema &attr_schema, const AttributeSchema *semantic_attr_schema)
Builds one CityObject table: type, geographical extent, geometry (split into non-instance and Geometr...
EncodedGeometry encode(const nlohmann::ordered_json &geometry)
Flattens one CityJSON geometry object – its boundaries and whatever semantics, material and texture i...
::flatbuffers::Offset<::GeometryInstance > to_geometry_instance(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &geometry)
Builds a GeometryInstance table: the template index, the 4x4 transformation matrix,...
::flatbuffers::Offset<::Address > to_address(::flatbuffers::FlatBufferBuilder &fbb, const nlohmann::ordered_json &address)
Builds one Address table from one entry of a CityJSON address array: location as a MultiPoint Geometr...
GeometryKind
The FlatBuffers GeometryType enumerators, mirrored here so a caller can name a geometry type without ...
Definition geometry.hpp:22
void add_attributes(AttributeSchema &schema, const nlohmann::ordered_json &attrs)
Adds every member of a JSON object to schema, assigning each new, non-null name the next free column ...
CoType city_object_type_from_name(const std::string &name)
Maps a CityJSON CityObject type string to the FlatBuffers tag.
::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::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,...
SurfaceType semantic_surface_type_from_name(const std::string &name)
Maps a CityJSON semantic surface type string to the FlatBuffers tag.
A CityObjectType tag, plus the verbatim CityJSON name when the tag is ExtensionObject (which has no s...
Everything one CityJSON geometry object flattens to.
std::optional< std::vector< TextureMapping > > textures
std::optional< GMSemantics > semantics
std::optional< std::vector< MaterialMapping > > materials
std::vector< std::uint32_t > strings
std::vector< std::uint32_t > shells
std::vector< std::uint32_t > solids
std::vector< std::uint32_t > surfaces
std::vector< std::uint32_t > indices
One R-tree node entry: 4 doubles then a u64, all little-endian, 40 bytes with no padding (packed_rtre...
A SemanticSurfaceType tag, plus the verbatim CityJSON name when the tag is ExtraSemanticSurface.