forked from tudelft3d/3dfier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMap3d.cpp
1884 lines (1740 loc) · 67.5 KB
/
Map3d.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
3dfier: takes 2D GIS datasets and "3dfies" to create 3D city models.
Copyright (C) 2015-2020 3D geoinformation research group, TU Delft
This file is part of 3dfier.
3dfier is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
3dfier is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with 3difer. If not, see <http://www.gnu.org/licenses/>.
For any information or further details about the use of 3dfier, contact
Hugo Ledoux
Faculty of Architecture & the Built Environment
Delft University of Technology
Julianalaan 134, Delft 2628BL, the Netherlands
*/
/**
* Map3D contains all configuration settings and functions to create the 3D model.
* It contains functions to read polygons, points, threedfy, construct CDT and
* create all output formats.
*/
#include "Map3d.h"
#include <ogrsf_frmts.h>
Map3d::Map3d() {
OGRRegisterAll();
_building_heightref_roof = 0.9;
_building_heightref_ground = 0.1;
_building_triangulate = true;
_building_lod = 1;
_building_include_floor = false;
_building_inner_walls = false;
_terrain_simplification = 0;
_forest_simplification = 0;
_terrain_simplification_tinsimp = 0.0;
_forest_simplification_tinsimp = 0.0;
_terrain_innerbuffer = 0.0;
_forest_innerbuffer = 0.0;
_water_heightref = 0.1;
_road_heightref = 0.5;
_road_filter_outliers = true;
_road_flatten = true;
_road_max_outlier_fraction = 0.2;
_separation_heightref = 0.8;
_bridge_heightref = 0.5;
_bridge_max_outlier_fraction = 0.2;
_radius_vertex_elevation = 1.0;
_building_radius_vertex_elevation = 3.0;
_threshold_jump_edges = 50;
_threshold_bridge_jump_edges = 50;
_requestedExtent = Box2(Point2(0, 0), Point2(0, 0));
_bbox = Box2(Point2(9999999, 9999999), Point2(-9999999, -9999999));
_minxradius = 9999999;
_maxxradius = 9999999;
_minyradius = -9999999;
_maxyradius = -9999999;
_max_angle_curvepolygon = 0;
}
Map3d::~Map3d() {
_lsFeatures.clear();
}
void Map3d::set_building_heightref_roof(float h) {
_building_heightref_roof = h;
}
void Map3d::set_building_heightref_ground(float h) {
_building_heightref_ground = h;
}
void Map3d::set_radius_vertex_elevation(float radius) {
_radius_vertex_elevation = radius;
}
void Map3d::set_building_radius_vertex_elevation(float radius) {
_building_radius_vertex_elevation = radius;
}
void Map3d::set_threshold_jump_edges(float threshold) {
_threshold_jump_edges = int(threshold * 100);
}
void Map3d::set_threshold_bridge_jump_edges(float threshold) {
_threshold_bridge_jump_edges = int(threshold * 100);
}
void Map3d::set_building_include_floor(bool include) {
_building_include_floor = include;
}
void Map3d::set_building_triangulate(bool triangulate) {
_building_triangulate = triangulate;
}
void Map3d::set_building_inner_walls(bool inner_walls) {
_building_inner_walls = inner_walls;
}
void Map3d::set_building_lod(int lod) {
_building_lod = lod;
}
void Map3d::set_terrain_simplification(int simplification) {
_terrain_simplification = simplification;
}
void Map3d::set_forest_simplification(int simplification) {
_forest_simplification = simplification;
}
void Map3d::set_terrain_simplification_tinsimp(double tinsimp_threshold){
_terrain_simplification_tinsimp = tinsimp_threshold;
}
void Map3d::set_forest_simplification_tinsimp(double tinsimp_threshold){
_forest_simplification_tinsimp = tinsimp_threshold;
}
void Map3d::set_terrain_innerbuffer(float innerbuffer) {
_terrain_innerbuffer = innerbuffer;
}
void Map3d::set_forest_innerbuffer(float innerbuffer) {
_forest_innerbuffer = innerbuffer;
}
void Map3d::set_water_heightref(float h) {
_water_heightref = h;
}
void Map3d::set_road_heightref(float h) {
_road_heightref = h;
}
void Map3d::set_road_filter_outliers(bool filter) {
_road_filter_outliers = filter;
}
void Map3d::set_road_flatten(bool flatten) {
_road_flatten = flatten;
}
void Map3d::set_road_max_outlier_fraction(float max_outlier_fraction) {
_road_max_outlier_fraction = max_outlier_fraction;
}
void Map3d::set_separation_heightref(float h) {
_separation_heightref = h;
}
void Map3d::set_bridge_heightref(float h) {
_bridge_heightref = h;
}
void Map3d::set_bridge_flatten(bool flatten) {
_bridge_flatten = flatten;
}
void Map3d::set_bridge_max_outlier_fraction(float max_outlier_fraction) {
_bridge_max_outlier_fraction = max_outlier_fraction;
}
void Map3d::set_requested_extent(double xmin, double ymin, double xmax, double ymax) {
_requestedExtent = Box2(Point2(xmin, ymin), Point2(xmax, ymax));
}
void Map3d::set_max_angle_curvepolygon(double max_angle) {
_max_angle_curvepolygon = max_angle;
}
Box2 Map3d::get_bbox() {
return _bbox;
}
bool Map3d::check_bounds(const double xmin, const double xmax, const double ymin, const double ymax) {
if ((xmin < _maxxradius || xmax > _minxradius) &&
(ymin < _maxyradius || ymax > _minyradius)) {
return true;
}
return false;
}
bool Map3d::get_cityjson(std::wostream& of) {
nlohmann::json j;
j["type"] = "CityJSON";
j["version"] = "1.0";
j["metadata"] = {};
double b[] = {bg::get<bg::min_corner, 0>(_bbox),
bg::get<bg::min_corner, 1>(_bbox),
0,
bg::get<bg::max_corner, 0>(_bbox),
bg::get<bg::max_corner, 1>(_bbox),
0};
j["metadata"]["geographicalExtent"] = b;
j["metadata"]["referenceSystem"] = "urn:ogc:def:crs:EPSG::7415";
std::unordered_map< std::string, unsigned long > dPts;
for (auto& f : _lsFeatures) {
f->get_cityjson(j, dPts);
}
//-- vertices
std::vector<std::string> thepts;
thepts.resize(dPts.size());
for (auto& p : dPts)
thepts[p.second] = p.first;
dPts.clear();
for (auto& p : thepts) {
std::vector<std::string> c;
boost::split(c, p, boost::is_any_of(" "));
j["vertices"].push_back({std::stod(c[0], NULL), std::stod(c[1], NULL), std::stod(c[2], NULL) });
}
of << j.dump() << std::endl;
return true;
}
void Map3d::get_citygml(std::wostream& of) {
create_citygml_header(of);
for (auto& f : _lsFeatures) {
f->get_citygml(of);
of << "\n";
}
of << "</CityModel>\n";
}
void Map3d::get_citygml_multifile(std::string ofname) {
std::unordered_map<std::string, std::wofstream*> ofs;
for (auto& f : _lsFeatures) {
std::string filename = ofname + f->get_layername() + ".gml";
if (ofs.find(filename) == ofs.end()) {
std::wofstream* of = new std::wofstream();
of->open(filename);
ofs.emplace(filename, of);
create_citygml_header(*ofs[filename]);
}
f->get_citygml(*ofs[filename]);
*ofs[filename] << "\n";
}
for (auto it = ofs.begin(); it != ofs.end(); it++) {
std::wofstream& of = *(it->second);
of << "</CityModel>\n";
of.close();
}
}
void Map3d::get_citygml_imgeo(std::wostream& of) {
create_citygml_imgeo_header(of);
for (auto& f : _lsFeatures) {
f->get_citygml_imgeo(of);
of << "\n";
}
of << "</CityModel>\n";
}
void Map3d::get_citygml_imgeo_multifile(std::string ofname) {
std::unordered_map<std::string, std::wofstream*> ofs;
for (auto& f : _lsFeatures) {
std::string filename = ofname + f->get_layername() + ".gml";
if (ofs.find(filename) == ofs.end()) {
std::wofstream* of = new std::wofstream();
of->open(filename);
ofs.emplace(filename, of);
create_citygml_imgeo_header(*ofs[filename]);
}
f->get_citygml_imgeo(*ofs[filename]);
*ofs[filename] << "\n";
}
for (auto it = ofs.begin(); it != ofs.end(); it++) {
std::wofstream& of = *(it->second);
of << "</CityModel>\n";
of.close();
}
}
void Map3d::create_citygml_header(std::wostream& of) {
of << std::setprecision(3) << std::fixed;
get_xml_header(of);
get_citygml_namespaces(of);
of << "<!-- Automatically generated by 3dfier (https://github.com/tudelft3d/3dfier) -->\n";
of << "<gml:name>my 3dfied map</gml:name>\n";
of << "<gml:boundedBy>";
of << "<gml:Envelope srsDimension=\"3\" srsName=\"urn:ogc:def:crs:EPSG::7415\">";
of << "<gml:lowerCorner>";
of << bg::get<bg::min_corner, 0>(_bbox) << " " << bg::get<bg::min_corner, 1>(_bbox) << " 0";
of << "</gml:lowerCorner>";
of << "<gml:upperCorner>";
of << bg::get<bg::max_corner, 0>(_bbox) << " " << bg::get<bg::max_corner, 1>(_bbox) << " 100";
of << "</gml:upperCorner>";
of << "</gml:Envelope>";
of << "</gml:boundedBy>\n";
}
void Map3d::create_citygml_imgeo_header(std::wostream& of) {
of << std::setprecision(3) << std::fixed;
get_xml_header(of);
get_citygml_imgeo_namespaces(of);
of << "<!-- Automatically generated by 3dfier (https://github.com/tudelft3d/3dfier), a software made with <3 by the 3D geoinformation group, TU Delft -->\n";
of << "<gml:name>my 3dfied map</gml:name>\n";
of << "<gml:boundedBy>";
of << "<gml:Envelope srsDimension=\"3\" srsName=\"urn:ogc:def:crs:EPSG::7415\">";
of << "<gml:lowerCorner>";
of << bg::get<bg::min_corner, 0>(_bbox) << " " << bg::get<bg::min_corner, 1>(_bbox) << " 0";
of << "</gml:lowerCorner>";
of << "<gml:upperCorner>";
of << bg::get<bg::max_corner, 0>(_bbox) << " " << bg::get<bg::max_corner, 1>(_bbox) << " 100";
of << "</gml:upperCorner>";
of << "</gml:Envelope>";
of << "</gml:boundedBy>\n";
}
void Map3d::get_csv_buildings(std::wostream& of) {
of << "id,roof,ground\n";
for (auto& p : _lsFeatures) {
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
b->get_csv(of);
}
}
}
void Map3d::get_csv_buildings_all_elevation_points(std::wostream& of) {
of << "id,allzvalues" << std::endl;
for (auto& p : _lsFeatures) {
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
of << b->get_id() << ",";
of << b->get_all_z_values();
of << std::endl;
}
}
}
void Map3d::get_csv_buildings_multiple_heights(std::wostream& of) {
//-- ground heights
std::vector<float> gpercentiles = {0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f};
std::vector<float> rpercentiles = {0.0f, 0.1f, 0.25f, 0.5f, 0.75f, 0.9f, 0.95f, 0.99f};
of << std::setprecision(2) << std::fixed;
of << "id";
for (auto& each : gpercentiles)
of << ",ground-" << each;
for (auto& each : rpercentiles)
of << ",roof-" << each;
of << std::endl;
for (auto& p : _lsFeatures) {
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
of << b->get_id();
for (auto& each : gpercentiles) {
int h = b->get_height_ground_at_percentile(each);
of << "," << float(h)/100;
}
for (auto& each : rpercentiles) {
int h = b->get_height_roof_at_percentile(each);
of << "," << float(h)/100;
}
of << std::endl;
}
}
}
void Map3d::get_obj_per_feature(std::wostream& of) {
std::unordered_map< std::string, unsigned long > dPts;
std::string fs;
for (auto& p : _lsFeatures) {
fs += "o "; fs += p->get_id(); fs += "\n";
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
b->get_obj(dPts, _building_lod, b->get_mtl(), fs);
}
else {
p->get_obj(dPts, p->get_mtl(), fs);
}
}
//-- sort the points in the map: simpler to copy to a vector
std::vector<std::string> thepts;
thepts.resize(dPts.size());
for (auto& p : dPts)
thepts[p.second - 1] = p.first;
dPts.clear();
of << "mtllib ./3dfier.mtl" << "\n";
for (auto& p : thepts) {
of << "v " << p << "\n";
}
of << fs << std::endl;
}
void Map3d::get_obj_per_class(std::wostream& of) {
std::unordered_map< std::string, unsigned long > dPts;
std::string fs;
for (int c = 0; c < 7; c++) {
for (auto& p : _lsFeatures) {
if (p->get_class() == c) {
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
b->get_obj(dPts, _building_lod, b->get_mtl(), fs);
}
else {
p->get_obj(dPts, p->get_mtl(), fs);
}
}
}
}
//-- sort the points in the map: simpler to copy to a vector
std::vector<std::string> thepts;
thepts.resize(dPts.size());
for (auto& p : dPts)
thepts[p.second - 1] = p.first;
dPts.clear();
of << "mtllib ./3dfier.mtl\n";
for (auto& p : thepts) {
of << "v " << p << std::endl;
}
of << fs << std::endl;
}
void Map3d::get_stl(std::wostream& of) {
std::unordered_map< std::string, unsigned long > dPts;
std::string fs[7];
for (int c = 0; c < 7; c++) {
for (auto& p : _lsFeatures) {
if (p->get_class() == c) {
if (p->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(p);
b->get_stl(dPts, _building_lod, fs[0]);
}
else {
p->get_stl(dPts, fs[c]);
}
}
}
}
// Is there a better way to handle this?
// Define each class as a separate solid
fs[0] = "solid Building\n" + fs[0]; fs[0] += "endsolid Building";
fs[1] = "solid Water\n" + fs[1]; fs[1] += "endsolid Water";
fs[2] = "solid Bridge\n" + fs[2]; fs[2] += "endsolid Bridge";
fs[3] = "solid Road\n" + fs[3]; fs[3] += "endsolid Road";
fs[4] = "solid Terrain\n" + fs[4]; fs[4] += "endsolid Terrain";
fs[5] = "solid Forest\n" + fs[5]; fs[5] += "endsolid Forest";
fs[6] = "solid Separation\n" + fs[6]; fs[6] += "endsolid Separation";
for (int c = 0; c < 7; c++) {
of << fs[c] << std::endl;
}
}
bool Map3d::get_postgis_output(std::string connstr, bool pdok, bool citygml) {
#if GDAL_VERSION_MAJOR < 2
std::cerr << "ERROR: cannot write MultiPolygonZ files with GDAL < 2.0.\n";
return false;
#else
if (GDALGetDriverCount() == 0)
GDALAllRegister();
GDALDriver *driver = GetGDALDriverManager()->GetDriverByName("PostgreSQL");
GDALDataset* dataSource = driver->Create(connstr.c_str(), 0, 0, 0, GDT_Unknown, NULL);
if (dataSource == NULL) {
std::cerr << "Starting database connection failed.\n";
return false;
}
if (dataSource->StartTransaction() != OGRERR_NONE) {
std::cerr << "Starting database transaction failed.\n";
return false;
}
std::unordered_map<std::string, OGRLayer*> layers;
// create and write layers first
for (auto& f : _lsFeatures) {
std::string layername = f->get_layername();
if (layers.find(layername) == layers.end()) {
AttributeMap &attributes = f->get_attributes();
if (pdok) {
//Add additional attribute to list for layer creation
attributes["xml"] = std::make_pair(OFTString, "");
}
OGRLayer *layer = create_gdal_layer(driver, dataSource, connstr, layername, attributes, f->get_class() == BUILDING);
if (layer == NULL) {
std::cerr << "ERROR: Cannot open database '" + connstr + "' for writing" << std::endl;
dataSource->RollbackTransaction();
GDALClose(dataSource);
return false;
}
layers.emplace(layername, layer);
}
}
if (dataSource->CommitTransaction() != OGRERR_NONE) {
std::cerr << "Writing to database failed.\n";
return false;
}
if (dataSource->StartTransaction() != OGRERR_NONE) {
std::cerr << "Starting database transaction failed.\n";
return false;
}
// create and write features to layers
int i = 1;
for (auto& f : _lsFeatures) {
std::string layername = f->get_layername();
AttributeMap extraAttribute = AttributeMap();
if (pdok) {
//Add additional attribute describing CityGML of feature
std::wstring_convert<codecvt<wchar_t, char, std::mbstate_t>>converter;
std::wstringstream ss;
ss << std::fixed << std::setprecision(3);
if (citygml) {
f->get_citygml(ss);
}
else {
f->get_citygml_imgeo(ss);
}
std::string gmlAttribute = converter.to_bytes(ss.str());
ss.clear();
extraAttribute["xml"] = std::make_pair(OFTString, gmlAttribute);
}
if (!f->get_shape(layers[layername], true, extraAttribute)) {
return false;
}
if (i % 1000 == 0) {
if (dataSource->CommitTransaction() != OGRERR_NONE) {
std::cerr << "Writing to database failed.\n";
return false;
}
if (dataSource->StartTransaction() != OGRERR_NONE) {
std::cerr << "Starting database transaction failed.\n";
return false;
}
}
i++;
}
if (dataSource->CommitTransaction() != OGRERR_NONE) {
std::cerr << "Writing to database failed.\n";
return false;
}
GDALClose(dataSource);
return true;
#endif
}
bool Map3d::get_gdal_output(std::string filename, std::string drivername, bool multi) {
#if GDAL_VERSION_MAJOR < 2
std::cerr << "ERROR: cannot write MultiPolygonZ files with GDAL < 2.0.\n";
return false;
#else
if (GDALGetDriverCount() == 0)
GDALAllRegister();
GDALDriver *driver = GetGDALDriverManager()->GetDriverByName(drivername.c_str());
if (!multi) {
GDALDataset* dataSource;
OGRLayer *layer = create_gdal_layer(driver, dataSource, filename, "my3dmap", AttributeMap(), true);
if (layer == NULL) {
std::cerr << "ERROR: Cannot open file '" + filename + "' for writing" << std::endl;
return false;
}
for (auto& f : _lsFeatures) {
f->get_shape(layer, false);
}
GDALClose(dataSource);
}
else {
std::unordered_map<std::string, OGRLayer*> layers;
GDALDataset* dataSource;
for (auto& f : _lsFeatures) {
std::string layername = f->get_layername();
if (layers.find(layername) == layers.end()) {
std::string tmpFilename = filename;
if (drivername == "ESRI Shapefile") {
tmpFilename = filename + layername;
}
OGRLayer *layer = create_gdal_layer(driver, dataSource, tmpFilename, layername, f->get_attributes(), f->get_class() == BUILDING);
if (layer == NULL) {
std::cerr << "ERROR: Cannot open file '" + filename + "' for writing" << std::endl;
return false;
}
layers.emplace(layername, layer);
}
if (!f->get_shape(layers[layername], true)) {
return false;
}
}
GDALClose(dataSource);
}
return true;
#endif
}
// #if GDAL_VERSION_MAJOR >= 2
// void Map3d::close_gdal_resources(GDALDriver* driver, std::unordered_map<std::string, OGRLayer*> layers) {
// for (auto& layer : layers) {
// GDALClose(layer.second);
// }
// }
// #endif
#if GDAL_VERSION_MAJOR >= 2
OGRLayer* Map3d::create_gdal_layer(GDALDriver* driver, GDALDataset* dataSource, std::string filename, std::string layername, AttributeMap attributes, bool addHeightAttributes) {
if (dataSource == NULL) {
dataSource = driver->Create(filename.c_str(), 0, 0, 0, GDT_Unknown, NULL);
}
if (dataSource == NULL) {
std::cerr << "ERROR: could not open file, skipping it.\n";
return NULL;
}
OGRLayer *layer = dataSource->GetLayerByName(layername.c_str());
if (layer == NULL) {
OGRSpatialReference* sr = new OGRSpatialReference();
sr->importFromEPSG(7415);
layer = dataSource->CreateLayer(layername.c_str(), sr, OGR_GT_SetZ(wkbMultiPolygon), NULL);
OGRFieldDefn oField("3df_id", OFTString);
if (layer->CreateField(&oField) != OGRERR_NONE) {
std::cerr << "Creating 3df_id field failed.\n";
return NULL;
}
OGRFieldDefn oField2("3df_class", OFTString);
if (layer->CreateField(&oField2) != OGRERR_NONE) {
std::cerr << "Creating 3df_class field failed.\n";
return NULL;
}
if (addHeightAttributes) {
OGRFieldDefn oField3("baseheight", OFTReal);
if (layer->CreateField(&oField3) != OGRERR_NONE) {
std::cerr << "Creating floorheight field failed.\n";
return NULL;
}
OGRFieldDefn oField4("RoofHeight", OFTReal);
if (layer->CreateField(&oField4) != OGRERR_NONE) {
std::cerr << "Creating roofheight field failed.\n";
return NULL;
}
}
for (auto attr : attributes) {
OGRFieldDefn oField(attr.first.c_str(), attr.second.first);
if (layer->CreateField(&oField) != OGRERR_NONE) {
std::cerr << "Creating " + attr.first + " field failed.\n";
return NULL;
}
}
}
return layer;
}
#endif
unsigned long Map3d::get_num_polygons() {
return _lsFeatures.size();
}
const std::vector<TopoFeature*>& Map3d::get_polygons3d() {
return _lsFeatures;
}
/**
* process a LAS/LAZ point
* search rtrees for intersecting features
* check if points classification is allowed for feature and add point to feature
*/
void Map3d::add_elevation_point(LASpoint const& laspt) {
//-- only process last returns;
//-- although perhaps not smart for vegetation/forest in the future
//-- TODO: always ignore the non-last-return points?
if (laspt.return_number != laspt.number_of_returns)
return;
std::vector<PairIndexed> re;
float x = laspt.get_x();
float y = laspt.get_y();
Point2 minp(x - _radius_vertex_elevation, y - _radius_vertex_elevation);
Point2 maxp(x + _radius_vertex_elevation, y + _radius_vertex_elevation);
Box2 querybox(minp, maxp);
_rtree.query(bgi::intersects(querybox), std::back_inserter(re));
minp = Point2(x - _building_radius_vertex_elevation, y - _building_radius_vertex_elevation);
maxp = Point2(x + _building_radius_vertex_elevation, y + _building_radius_vertex_elevation);
querybox = Box2(minp, maxp);
_rtree_buildings.query(bgi::intersects(querybox), std::back_inserter(re));
for (auto& v : re) {
TopoFeature* f = v.second;
float radius = _radius_vertex_elevation;
int c = (int)laspt.classification;
bool bInsert = false;
bool bWithin = false;
if (f->get_class() == BUILDING) {
bInsert = true;
radius = _building_radius_vertex_elevation;
}
else if (f->get_class() == TERRAIN) {
if (_las_classes_allowed[LAS_TERRAIN].empty() || _las_classes_allowed[LAS_TERRAIN].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_TERRAIN].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
else if (f->get_class() == FOREST) {
if (_las_classes_allowed[LAS_FOREST].empty() || _las_classes_allowed[LAS_FOREST].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_FOREST].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
else if (f->get_class() == ROAD) {
if (_las_classes_allowed[LAS_ROAD].empty() || _las_classes_allowed[LAS_ROAD].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_ROAD].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
else if (f->get_class() == WATER) {
if (_las_classes_allowed[LAS_WATER].empty() || _las_classes_allowed[LAS_WATER].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_WATER].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
else if (f->get_class() == SEPARATION) {
if (_las_classes_allowed[LAS_SEPARATION].empty() || _las_classes_allowed[LAS_SEPARATION].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_SEPARATION].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
else if (f->get_class() == BRIDGE) {
if (_las_classes_allowed[LAS_BRIDGE].empty() || _las_classes_allowed[LAS_BRIDGE].count(c) > 0) {
bInsert = true;
}
if (_las_classes_allowed_within[LAS_BRIDGE].count(c) > 0) {
bInsert = true;
bWithin = true;
}
}
if (bInsert == true) { //-- only insert if in the allowed LAS classes
Point2 p(x, y);
f->add_elevation_point(p, laspt.get_z(), radius, c, bWithin);
}
}
}
void Map3d::cleanup_elevations() {
for (auto& f : _lsFeatures) {
f->cleanup_elevations();
}
}
/**
* algorithm to create the 3D model from the input data
*
* 1. lift polygon vertices to calculated height from point cloud
* 2. stitch vertices to solve for vertical gaps and height jumps
* 3. fix bow ties created by wrong stitching
* 4. create vertical walls and building walls
*/
bool Map3d::threeDfy(bool stitching) {
try {
std::clog << "===== /LIFTING =====\n";
for (auto& f : _lsFeatures) {
f->lift();
}
std::clog << "===== LIFTING/ =====\n";
if (stitching == true) {
std::clog << "===== /ADJACENT FEATURES =====\n";
for (auto& f : _lsFeatures) {
this->collect_adjacent_features(f);
}
std::clog << "===== ADJACENT FEATURES/ =====\n";
std::clog << "===== /STITCHING =====\n";
this->stitch_lifted_features();
//-- handle bridges seperately
this->stitch_bridges();
std::clog << "===== STITCHING/ =====\n";
//-- Sort all node column vectors
for (auto& nc : _nc) {
std::sort(nc.second.begin(), nc.second.end());
// make values in nc unique
nc.second.erase(unique(nc.second.begin(), nc.second.end()), nc.second.end());
}
for (auto& nc : _nc_building_walls) {
std::sort(nc.second.begin(), nc.second.end());
// make values in nc unique
nc.second.erase(unique(nc.second.begin(), nc.second.end()), nc.second.end());
}
std::clog << "===== /BOWTIES =====\n";
for (auto& f : _lsFeatures) {
if (f->has_vertical_walls()) {
f->fix_bowtie();
}
}
std::clog << "===== BOWTIES/ =====\n";
std::clog << "===== /VERTICAL WALLS =====\n";
for (auto& f : _lsFeatures) {
if (f->get_class() == BUILDING) {
Building* b = dynamic_cast<Building*>(f);
b->construct_building_walls(_nc_building_walls);
}
else if (f->has_vertical_walls()) {
f->construct_vertical_walls(_nc);
}
}
std::clog << "===== VERTICAL WALLS/ =====\n";
}
}
catch (std::exception e) {
std::cerr << std::endl << "3dfying failed with error: " << e.what() << std::endl;
return false;
}
return true;
}
/**
* build the Constrained Delaunay Triangulation for each TopoFeature
*/
bool Map3d::construct_CDT() {
std::clog << "===== /CDT =====\n";
for (auto& p : _lsFeatures) {
try {
p->buildCDT();
}
catch (std::exception e) {
std::cerr << std::endl << "CDT failed for object \'" << p->get_id() << "\' (class " << p->get_class() << ") with error: " << e.what() << std::endl;
return false;
}
}
std::clog << "===== CDT/ =====\n";
return true;
}
bool Map3d::save_building_variables() {
Building::set_las_classes_roof(_las_classes_allowed[LAS_BUILDING_ROOF]);
Building::set_las_classes_ground(_las_classes_allowed[LAS_BUILDING_GROUND]);
return true;
}
/**
* create rtrees, one for building and one for other objects
* calculate a single bounding box from both trees
*/
bool Map3d::construct_rtree() {
std::clog << "Constructing the R-tree...";
for (auto p : _lsFeatures) {
if (p->get_class() == BUILDING) {
_rtree_buildings.insert(std::make_pair(p->get_bbox2d(), p));
}
else {
_rtree.insert(std::make_pair(p->get_bbox2d(), p));
}
}
std::clog << " done.\n";
//-- update the bounding box from _rtree and _rtree_buildings
_bbox = Box2(
Point2(std::min(bg::get<bg::min_corner, 0>(_rtree.bounds()), bg::get<bg::min_corner, 0>(_rtree_buildings.bounds())),
std::min(bg::get<bg::min_corner, 1>(_rtree.bounds()), bg::get<bg::min_corner, 1>(_rtree_buildings.bounds()))),
Point2(std::max(bg::get<bg::max_corner, 0>(_rtree.bounds()), bg::get<bg::max_corner, 0>(_rtree_buildings.bounds())),
std::max(bg::get<bg::max_corner, 1>(_rtree.bounds()), bg::get<bg::max_corner, 1>(_rtree_buildings.bounds()))));
double radius = std::max(_radius_vertex_elevation, _building_radius_vertex_elevation);
_minxradius = std::min(bg::get<bg::min_corner, 0>(_rtree.bounds()), bg::get<bg::min_corner, 0>(_rtree_buildings.bounds())) - radius;
_maxxradius = std::min(bg::get<bg::min_corner, 1>(_rtree.bounds()), bg::get<bg::min_corner, 1>(_rtree_buildings.bounds())) + radius;
_minyradius = std::max(bg::get<bg::max_corner, 0>(_rtree.bounds()), bg::get<bg::max_corner, 0>(_rtree_buildings.bounds())) - radius;
_maxyradius = std::max(bg::get<bg::max_corner, 1>(_rtree.bounds()), bg::get<bg::max_corner, 1>(_rtree_buildings.bounds())) + radius;
return true;
}
/**
* read a polygon file
* setup the GDAL driver, datasource and read layers
*/
bool Map3d::add_polygons_files(std::vector<PolygonFile> &files) {
#if GDAL_VERSION_MAJOR < 2
if (OGRSFDriverRegistrar::GetRegistrar()->GetDriverCount() == 0)
OGRRegisterAll();
#else
if (GDALGetDriverCount() == 0)
GDALAllRegister();
#endif
for (auto file = files.begin(); file != files.end(); ++file) {
std::string logstring = "Reading input dataset: " + file->filename;
if (strncmp(file->filename.c_str(), "PG:", strlen("PG:")) == 0) {
logstring = "Opening PostgreSQL database connection.";
}
std::clog << logstring << std::endl;
#if GDAL_VERSION_MAJOR < 2
OGRDataSource *dataSource = OGRSFDriverRegistrar::Open(file->filename.c_str(), false);
#else
GDALDataset *dataSource = (GDALDataset*)GDALOpenEx(file->filename.c_str(), GDAL_OF_READONLY | GDAL_OF_VECTOR, NULL, NULL, NULL);
#endif
if (dataSource == NULL) {
std::cerr << "\tERROR: " << logstring << std::endl;
return false;
}
// if the file doesn't have layers specified, add all
if (file->layers[0].first.empty()) {
std::string lifting = file->layers[0].second;
file->layers.clear();
int numberOfLayers = dataSource->GetLayerCount();
for (int i = 0; i < numberOfLayers; i++) {
OGRLayer *dataLayer = dataSource->GetLayer(i);
file->layers.emplace_back(dataLayer->GetName(), lifting);
}
}
bool wentgood = this->extract_and_add_polygon(dataSource, &(*file));
#if GDAL_VERSION_MAJOR < 2
OGRDataSource::DestroyDataSource(dataSource);
#else
GDALClose(dataSource);
#endif
if (!wentgood) {
return false;
}
}
return true;
}
/**
* read a polygon layer
* read id and relative height attributes and check if polygon is within max extent
* Split MultiPolygons/MultiSurface and stroke CurvedPolygons
*/
#if GDAL_VERSION_MAJOR < 2
bool Map3d::extract_and_add_polygon(OGRDataSource* dataSource, PolygonFile* file) {
#else
bool Map3d::extract_and_add_polygon(GDALDataset* dataSource, PolygonFile* file) {
#endif
const char *idfield = file->idfield.c_str();
const char *heightfield = file->heightfield.c_str();
bool multiple_heights = file->handle_multiple_heights;
bool wentgood = false;
for (auto l : file->layers) {
OGRLayer *dataLayer = dataSource->GetLayerByName((l.first).c_str());
if (dataLayer == NULL) {
continue;
}
if (dataLayer->FindFieldIndex(idfield, false) == -1) {
std::cerr << "ERROR: field '" << idfield << "' not found in layer '" << l.first << "'.\n";
return false;
}
if (strlen(heightfield) == 0) {
std::clog << "Using all polygons in layer '" << l.first << "'.\n";
}
else if (dataLayer->FindFieldIndex(heightfield, false) == -1) {
std::clog << "Warning: field '" << heightfield << "' not found in layer '" << l.first << "', using all polygons.\n";
}
dataLayer->ResetReading();
unsigned int numberOfPolygons = dataLayer->GetFeatureCount(true);
std::string layerName = dataLayer->GetName();
std::clog << "\tLayer: " << layerName << std::endl;
std::clog << "\t(" << boost::locale::as::number << numberOfPolygons << " features --> " << l.second << ")\n";
OGRFeature *f;
//-- check if extent is given and polygons need filtering
bool useRequestedExtent = false;
OGREnvelope extent = OGREnvelope();
if (boost::geometry::area(_requestedExtent) > 0) {
extent.MinX = bg::get<bg::min_corner, 0>(_requestedExtent);
extent.MaxX = bg::get<bg::max_corner, 0>(_requestedExtent);
extent.MinY = bg::get<bg::min_corner, 1>(_requestedExtent);
extent.MaxY = bg::get<bg::max_corner, 1>(_requestedExtent);
useRequestedExtent = true;