-
-
Notifications
You must be signed in to change notification settings - Fork 901
Expand file tree
/
Copy pathIfcConvert.cpp
More file actions
1739 lines (1523 loc) · 68.5 KB
/
IfcConvert.cpp
File metadata and controls
1739 lines (1523 loc) · 68.5 KB
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
/********************************************************************************
* *
* This file is part of IfcOpenShell. *
* *
* IfcOpenShell is free software: you can redistribute it and/or modify *
* it under the terms of the Lesser GNU General Public License as published by *
* the Free Software Foundation, either version 3.0 of the License, or *
* (at your option) any later version. *
* *
* IfcOpenShell 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 *
* Lesser GNU General Public License for more details. *
* *
* You should have received a copy of the Lesser GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
/********************************************************************************
* *
* This started as a brief example of how IfcOpenShell can be interfaced from *
* within a C++ context, it has since then evolved into a fullfledged command *
* line application that is able to convert geometry in an IFC files into *
* several tessellated and topological output formats. *
* *
********************************************************************************/
// windows stuff: defines max as a macro when including windows.h
// error C2589: '(': illegal token on right side of '::'
#define NOMINMAX
#include "../serializers/ColladaSerializer.h"
#include "../serializers/GltfSerializer.h"
#include "../serializers/HdfSerializer.h"
#include "../serializers/IgesSerializer.h"
#include "../serializers/StepSerializer.h"
#include "../serializers/WavefrontObjSerializer.h"
#include "../serializers/XmlSerializer.h"
#include "../serializers/SvgSerializer.h"
#include "../serializers/USDSerializer.h"
#include "../serializers/TtlWktSerializer.h"
#include "../serializers/RocksDbSerializer.h"
#include "../serializers/JsonSerializer.h"
#include "../ifcgeom/IfcGeomFilter.h"
#include "../ifcgeom/Iterator.h"
#include "../ifcgeom/IfcGeomRenderStyles.h"
#include "../ifcgeom/hybrid_kernel.h"
#include "../ifcparse/utils.h"
#ifdef IFOPSH_WITH_OPENCASCADE
#include <Standard_Version.hxx>
#if OCC_VERSION_HEX < 0x60900
#include <IGESControl_Controller.hxx>
#endif
#endif
#include <boost/program_options.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
#include <sstream>
#include <set>
#include <time.h>
#include <iomanip>
#if USE_VLD
#include <vld.h>
#endif
#ifdef _MSC_VER
#include <io.h>
#include <fcntl.h>
#endif
#include <random>
#include <thread>
#if defined(_MSC_VER) && defined(_UNICODE)
typedef std::wstring path_t;
typedef std::wofstream ofstream_t;
static std::wostream& cout_ = std::wcout;
static std::wostream& cerr_ = std::wcerr;
#else
typedef std::string path_t;
typedef std::ofstream ofstream_t;
static std::ostream& cout_ = std::cout;
static std::ostream& cerr_ = std::cerr;
#endif
const std::string DEFAULT_EXTENSION = ".obj";
const std::string TEMP_FILE_EXTENSION = ".tmp";
namespace po = boost::program_options;
void print_version()
{
cout_ << "IfcOpenShell IfcConvert " << IFCOPENSHELL_VERSION;
#ifdef IFOPSH_WITH_OPENCASCADE
cout_ << " (OCC " << OCC_VERSION_STRING_EXT << ")";
#endif
cout_ << "\n";
}
void print_usage(bool suggest_help = true)
{
cout_ << "Usage: IfcConvert [options] <input.ifc> [<output>]\n"
<< "\n"
<< "Converts (the geometry in) an IFC file into one of the following formats:\n"
<< " .obj WaveFront OBJ (a .mtl file is also created)\n"
#ifdef WITH_OPENCOLLADA
<< " .dae Collada Digital Assets Exchange\n"
#endif
#ifdef WITH_GLTF
<< " .glb glTF Binary glTF v2.0\n"
#endif
#ifdef WITH_USD
<< " .usd USD Universal Scene Description\n"
#endif
<< " .stp STEP Standard for the Exchange of Product Data\n"
<< " .igs IGES Initial Graphics Exchange Specification\n"
<< " .xml XML Property definitions and decomposition tree\n"
#ifdef WITH_GLTF
<< " .json JSON Property definitions and decomposition tree in xeokit json format\n"
#endif
<< " .rdb RocksDB RocksDB Key-Value store serialization of IFC data\n"
<< " .svg SVG Scalable Vector Graphics (2D floor plan)\n"
#ifdef WITH_HDF5
<< " .h5 HDF Hierarchical Data Format storing positions, normals and indices\n"
#endif
<< " .ttl TTL/WKT RDF Turtle with Well-Known-Text geometry\n"
<< " .ifc IFC-SPF Industry Foundation Classes\n"
<< "\n"
<< "If no output filename given, <input>" << IfcUtil::path::from_utf8(DEFAULT_EXTENSION) << " will be used as the output file.\n";
if (suggest_help) {
cout_ << "\nRun 'IfcConvert --help' for more information.";
}
cout_ << std::endl;
}
/// @todo Add help for single option
void print_options(const po::options_description& options)
{
#if defined(_MSC_VER) && defined(_UNICODE)
// See issue https://svn.boost.org/trac10/ticket/10952
std::ostringstream temp;
temp << options;
cout_ << "\n" << temp.str().c_str();
#else
cout_ << "\n" << options;
#endif
cout_ << std::endl;
}
template <typename T>
T change_extension(const T& fn, const T& ext) {
typename T::size_type dot = fn.find_last_of('.');
if (dot != T::npos) {
return fn.substr(0, dot) + ext;
} else {
return fn + ext;
}
}
bool file_exists(const std::string& filename) {
std::ifstream file(IfcUtil::path::from_utf8(filename).c_str());
return file.good();
}
static std::basic_stringstream<path_t::value_type> log_stream;
void write_log(bool);
void fix_quantities(IfcParse::IfcFile&, bool, bool, bool);
std::string format_duration(time_t start, time_t end);
/// @todo make the filters non-global
IfcGeom::entity_filter entity_filter; // Entity filter is used always by default.
IfcGeom::layer_filter layer_filter;
IfcGeom::attribute_filter attribute_filter;
struct geom_filter
{
geom_filter(bool include, bool traverse) : type(UNUSED), include(include), traverse(traverse) {}
geom_filter() : type(UNUSED), include(false), traverse(false) {}
enum filter_type { UNUSED, ENTITY_TYPE, LAYER_NAME, ENTITY_ARG };
filter_type type;
bool include;
bool traverse;
std::string arg;
std::set<std::string> values;
};
// Specialized classes for knowing which type of filter we are validating within validate().
// Could not figure out easily how else to know it if using single type for both.
struct inclusion_filter : public geom_filter { inclusion_filter() : geom_filter(true, false) {} };
struct inclusion_traverse_filter : public geom_filter { inclusion_traverse_filter() : geom_filter(true, true) {} };
struct exclusion_filter : public geom_filter { exclusion_filter() : geom_filter(false, false) {} };
struct exclusion_traverse_filter : public geom_filter { exclusion_traverse_filter() : geom_filter(false, true) {} };
size_t read_filters_from_file(const std::string&, inclusion_filter&, inclusion_traverse_filter&, exclusion_filter&, exclusion_traverse_filter&);
void parse_filter(geom_filter &, const std::vector<std::string>&);
std::vector<IfcGeom::filter_t> setup_filters(const std::vector<geom_filter>&, const std::string&);
bool init_input_file(const std::string& filename, IfcParse::IfcFile*& ifc_file, bool no_progress, bool mmap, bool bypass_properties=false);
// from https://stackoverflow.com/questions/31696328/boost-program-options-using-zero-parameter-options-multiple-times
struct verbosity_counter {
int count;
verbosity_counter(int c = 0) {
count = c;
}
};
#if defined(_MSC_VER) && defined(_UNICODE)
int wmain(int argc, wchar_t** argv) {
typedef po::wcommand_line_parser command_line_parser;
typedef wchar_t char_t;
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stderr), _O_U16TEXT);
#else
int main(int argc, char** argv) {
typedef po::command_line_parser command_line_parser;
typedef char char_t;
#endif
inclusion_filter include_filter;
inclusion_traverse_filter include_traverse_filter;
exclusion_filter exclude_filter;
exclusion_traverse_filter exclude_traverse_filter;
path_t filter_filename;
path_t default_material_filename;
path_t log_file;
path_t cache_file;
std::string log_format;
std::string geometry_kernel;
po::options_description generic_options("Command line options");
verbosity_counter vcounter;
generic_options.add_options()
("help,h", "display usage information")
("version", "display version information")
("verbose,v", po::value(&vcounter)->zero_tokens(), "more verbose log messages. Use twice (-vv) for debugging level.")
("quiet,q", "less status and progress output")
#ifdef WITH_HDF5
("cache", "cache geometry creation. Use --cache-file to specify cache file path.")
#endif
("stderr-progress", "output progress to stderr stream")
("yes,y", "answer 'yes' automatically to possible confirmation queries (e.g. overwriting an existing output file)")
("no-progress", "suppress possible progress bar type of prints that use carriage return")
("log-format", po::value<std::string>(&log_format), "log format: plain or json")
("log-file", new po::typed_value<path_t, char_t>(&log_file), "redirect log output to file");
po::options_description fileio_options;
fileio_options.add_options()
#ifdef USE_MMAP
("mmap", "use memory-mapped file for input")
#endif
("input-file", new po::typed_value<path_t, char_t>(0), "input IFC file")
("output-file", new po::typed_value<path_t, char_t>(0), "output geometry file")
#ifdef WITH_HDF5
("cache-file", new po::typed_value<path_t, char_t>(&cache_file), "geometry cache file")
#endif
("stream", "Use streaming conversion (currently supported with conversion to RocksDB)")
;
po::options_description ifc_options("IFC options");
ifc_options.add_options()
("calculate-quantities", "Calculate or fix the physical quantity definitions "
"based on an interpretation of the geometry when exporting IFC");
int num_threads;
std::string offset_str, rotation_str;
std::string default_kernel;
#ifdef IFOPSH_WITH_CGAL
default_kernel = "cgal";
#endif
#ifdef IFOPSH_WITH_OPENCASCADE
default_kernel = "opencascade";
#endif
// none, convex-decomposition, minkowski-triangles or halfspace-snapping
std::string exterior_only_algo;
ifcopenshell::geometry::Settings geometry_settings;
po::options_description geom_options("Geometry options");
geom_options.add_options()
("kernel", po::value<std::string>(&geometry_kernel)->default_value(default_kernel),
"Geometry kernel to use (opencascade, cgal, cgal-simple, hybrid-cgal-simple-opencascade).")
("threads,j", po::value<int>(&num_threads)->default_value(1),
"Number of parallel processing threads for geometry interpretation.")
("center-model",
"Centers the elements by applying the center point of all placements as an offset."
"Can take several minutes on large models.")
("center-model-geometry",
"Centers the elements by applying the center point of all mesh vertices as an offset.")
("model-offset", po::value<std::string>(&offset_str),
"Applies an arbitrary offset of form 'x;y;z' to all placements.")
("model-rotation", po::value<std::string>(&rotation_str),
"Applies an arbitrary quaternion rotation of form 'x;y;z;w' to all placements.")
("include", po::value<inclusion_filter>(&include_filter)->multitoken(),
"Specifies that the instances that match a specific filtering criteria are to be included in the geometrical output:\n"
"1) 'entities': the following list of types should be included. SVG output defaults "
"to IfcSpace to be included. The entity names are handled case-insensitively.\n"
"2) 'layers': the instances that are assigned to presentation layers of which names "
"match the given values should be included.\n"
"3) 'attribute <AttributeName>': products whose value for <AttributeName> should be included\n. "
"Currently supported arguments are GlobalId, Name, Description, and Tag.\n\n"
"The values for 'layers' and 'arg' are handled case-sensitively (wildcards supported)."
"--include and --exclude cannot be placed right before input file argument and "
"only single of each argument supported for now. See also --exclude.")
("include+", po::value<inclusion_traverse_filter>(&include_traverse_filter)->multitoken(),
"Same as --include but applies filtering also to the decomposition and/or containment (IsDecomposedBy, "
"HasOpenings, FillsVoid, ContainedInStructure) of the filtered entity, e.g. --include+=arg Name \"Level 1\" "
"includes entity with name \"Level 1\" and all of its children. See --include for more information. ")
("exclude", po::value<exclusion_filter>(&exclude_filter)->multitoken(),
"Specifies that the entities that match a specific filtering criteria are to be excluded in the geometrical output."
"See --include for syntax and more details. The default value is '--exclude=entities IfcOpeningElement IfcSpace'.")
("exclude+", po::value<exclusion_traverse_filter>(&exclude_traverse_filter)->multitoken(),
"Same as --exclude but applies filtering also to the decomposition and/or containment "
"of the filtered entity. See --include+ for more details.")
("filter-file", new po::typed_value<path_t, char_t>(&filter_filename),
"Specifies a filter file that describes the used filtering criteria. Supported formats "
"are '--include=arg GlobalId ...' and 'include arg GlobalId ...'. Spaces and tabs can be used as delimiters."
"Multiple filters of same type with different values can be inserted on their own lines. "
"See --include, --include+, --exclude, and --exclude+ for more details.")
("default-material-file", new po::typed_value<path_t, char_t>(&default_material_filename),
"Specifies a material file that describes the material object types will have"
"if an object does not have any specified material in the IFC file.")
("exterior-only",
po::value<std::string>(&exterior_only_algo)->default_value("none")->implicit_value("minkowski-triangles"),
"Export only the exterior shell of the building found by geometric analysis. convex-decomposition, minkowski-triangles or halfspace-snapping")
("plan", "Specifies whether to include curves in the output result. Typically "
"these are representations of type Plan or Axis. Excluded by default.")
("model", "Specifies whether to include surfaces and solids in the output result. "
"Typically these are representations of type Body or Facetation. ")
;
geometry_settings.define_options(geom_options);
std::string bounds;
#ifdef HAVE_ICU
std::string unicode_mode;
#endif
short precision;
double section_height;
std::string svg_scale, svg_center;
std::string section_ref, elevation_ref, elevation_ref_guid;
// "none", "full" or "left"
std::string storey_height_display;
#ifdef IFOPSH_WITH_OPENCASCADE
SvgSerializer::storey_height_display_types svg_storey_height_display = SvgSerializer::SH_NONE;
#endif
ifcopenshell::geometry::SerializerSettings serializer_settings;
po::options_description serializer_options("Serialization options");
serializer_options.add_options()
#ifdef HAVE_ICU
("unicode", po::value<std::string>(&unicode_mode),
"Specifies the Unicode handling behavior when parsing the IFC file. "
"Accepted values 'utf8' (the default) and 'escape'.")
#endif
("bounds", po::value<std::string>(&bounds),
"Specifies the bounding rectangle, for example 512x512, to which the "
"output will be scaled. Only used when converting to SVG.")
("scale", po::value<std::string>(&svg_scale),
"Interprets SVG bounds in mm, centers layout and draw elements to scale. "
"Only used when converting to SVG. Example 1:100.")
("center", po::value<std::string>(&svg_center),
"When using --scale, specifies the location in the range [0 1]x[0 1] around which"
"to center the drawings. Example 0.5x0.5 (default).")
("section-ref", po::value<std::string>(§ion_ref),
"Element at which cross sections should be created")
("elevation-ref", po::value<std::string>(&elevation_ref),
"Element at which drawings should be created")
("elevation-ref-guid", po::value<std::string>(&elevation_ref_guid),
"Element guids at which drawings should be created")
("auto-section",
"Creates SVG cross section drawings automatically based on model extents")
("auto-elevation",
"Creates SVG elevation drawings automatically based on model extents")
("draw-storey-heights",
po::value<std::string>(&storey_height_display)->default_value("none")->implicit_value("full"),
"Draws a horizontal line at the height of building storeys in vertical drawings")
("storey-height-line-length", po::value<double>(),
"Length of the line when --draw-storey-heights=left")
("svg-xmlns",
"Stores name and guid in a separate namespace as opposed to data-name, data-guid")
("svg-poly",
"Uses the polygonal algorithm for hidden line rendering")
("svg-prefilter",
"Prefilter faces and shapes before feeding to HLR algorithm")
("svg-segment-projection",
"Segment result of projection wrt original products")
("svg-write-poly",
"Approximate every curve as polygonal in SVG output")
("svg-project",
"Always enable hidden line rendering instead of only on elevations")
("svg-without-storeys", "Don't emit drawings for building storeys")
("svg-no-css", "Don't emit CSS style declarations")
("door-arcs", "Draw door openings arcs for IfcDoor elements")
("section-height", po::value<double>(§ion_height),
"Specifies the cut section height for SVG 2D geometry.")
("section-height-from-storeys", "Derives section height from storey elevation. Use --section-height to override default offset of 1.2")
("print-space-names", "Prints IfcSpace LongName and Name in the geometry output. Applicable for SVG output")
("print-space-areas", "Prints calculated IfcSpace areas in square meters. Applicable for SVG output")
("space-name-transform", po::value<std::string>(),
"Additional transform to the space labels in SVG")
;
serializer_settings.define_options(serializer_options);
po::options_description cmdline_options;
cmdline_options.add(generic_options).add(fileio_options).add(geom_options).add(ifc_options).add(serializer_options);
po::positional_options_description positional_options;
positional_options.add("input-file", 1);
positional_options.add("output-file", 1);
po::variables_map vmap;
try {
po::store(command_line_parser(argc, argv).
options(cmdline_options).positional(positional_options).run(), vmap);
} catch (const po::unknown_option& e) {
cerr_ << "[Error] Unknown option '" << e.get_option_name().c_str() << "'\n\n";
print_usage();
return EXIT_FAILURE;
} catch (const po::error_with_option_name& e) {
cerr_ << "[Error] Invalid usage of '" << e.get_option_name().c_str() << "': " << e.what() << "\n\n";
return EXIT_FAILURE;
} catch (const std::exception& e) {
cerr_ << "[Error] " << e.what() << "\n\n";
print_usage();
return EXIT_FAILURE;
} catch (...) {
cerr_ << "[Error] Unknown error parsing command line options\n\n";
print_usage();
return EXIT_FAILURE;
}
po::notify(vmap);
const bool mmap = vmap.count("mmap") != 0;
const bool no_progress = vmap.count("no-progress") != 0;
const bool quiet = vmap.count("quiet") != 0;
const bool stderr_progress = vmap.count("stderr-progress") != 0;
const bool center_model = vmap.count("center-model") != 0;
const bool center_model_geometry = vmap.count("center-model-geometry") != 0;
const bool model_offset = vmap.count("model-offset") != 0;
const bool model_rotation = vmap.count("model-rotation") != 0;
if (!quiet || vmap.count("version")) {
print_version();
}
if (vmap.count("version")) {
return EXIT_SUCCESS;
} else if (vmap.count("help")) {
print_usage(false);
print_options(generic_options.add(geom_options).add(serializer_options));
return EXIT_SUCCESS;
} else if (!vmap.count("input-file")) {
cerr_ << "[Error] Input file not specified" << std::endl;
print_usage();
return EXIT_FAILURE;
}
#ifdef IFOPSH_WITH_OPENCASCADE
if (vmap.count("draw-storey-heights")) {
boost::to_lower(storey_height_display);
if (storey_height_display == "none") {
svg_storey_height_display = SvgSerializer::SH_NONE;
} else if (storey_height_display == "full") {
svg_storey_height_display = SvgSerializer::SH_FULL;
} else if (storey_height_display == "left") {
svg_storey_height_display = SvgSerializer::SH_LEFT;
} else {
cerr_ << "[Error] --draw-storey-heights should be none|full|left" << std::endl;
print_usage();
return EXIT_FAILURE;
}
}
#endif
if (num_threads <= 0) {
num_threads = std::thread::hardware_concurrency();
Logger::Notice("Using " + std::to_string(num_threads) + " threads");
}
if (vmap.count("log-format") == 1) {
boost::to_lower(log_format);
if (log_format == "plain") {
Logger::OutputFormat(Logger::FMT_PLAIN);
} else if (log_format == "json") {
Logger::OutputFormat(Logger::FMT_JSON);
} else {
cerr_ << "[Error] --log-format should be either plain or json" << std::endl;
print_usage();
return EXIT_FAILURE;
}
}
if (!filter_filename.empty()) {
size_t num_filters = read_filters_from_file(IfcUtil::path::to_utf8(filter_filename), include_filter, include_traverse_filter, exclude_filter, exclude_traverse_filter);
if (num_filters) {
Logger::Notice(boost::lexical_cast<std::string>(num_filters) + " filters read from specifified file.");
} else {
cerr_ << "[Error] No filters read from specifified file.\n";
return EXIT_FAILURE;
}
}
#ifdef HAVE_ICU
if (!unicode_mode.empty()) {
if (unicode_mode == "utf8") {
IfcParse::IfcCharacterDecoder::mode = IfcParse::IfcCharacterDecoder::UTF8;
} else if (unicode_mode == "escape") {
IfcParse::IfcCharacterDecoder::mode = IfcParse::IfcCharacterDecoder::JSON;
} else {
cerr_ << "[Error] Invalid value for --unicode" << std::endl;
print_options(serializer_options);
return 1;
}
}
#endif
if (!default_material_filename.empty()) {
try {
IfcGeom::set_default_style_file(IfcUtil::path::to_utf8(default_material_filename));
} catch (const std::exception& e) {
cerr_ << "[Error] Could not read default material file:" << std::endl;
cerr_ << e.what() << std::endl;
return EXIT_FAILURE;
}
}
boost::optional<double> bounding_width, bounding_height, relative_center_x, relative_center_y;
if (vmap.count("bounds") == 1) {
int w, h;
if (sscanf(bounds.c_str(), "%ux%u", &w, &h) == 2 && w > 0 && h > 0) {
bounding_width = w;
bounding_height = h;
} else {
cerr_ << "[Error] Invalid use of --bounds" << std::endl;
print_options(serializer_options);
return EXIT_FAILURE;
}
}
if (vmap.count("center") == 1) {
double cx, cy;
if (sscanf(svg_center.c_str(), "%lfx%lf", &cx, &cy) == 2 && cx >= 0. && cy >= 0. && cx <= 1. && cy <= 1.) {
relative_center_x = cx;
relative_center_y = cy;
} else {
cerr_ << "[Error] Invalid use of --bounds" << std::endl;
print_options(serializer_options);
return EXIT_FAILURE;
}
}
const path_t input_filename = vmap["input-file"].as<path_t>();
/*
// todo also allow rocksdb dir
if (!file_exists(IfcUtil::path::to_utf8(input_filename))) {
cerr_ << "[Error] Input file '" << input_filename << "' does not exist" << std::endl;
return EXIT_FAILURE;
}*/
// If no output filename is specified a Wavefront OBJ file will be output
// to maintain backwards compatibility with the obsolete IfcObj executable.
const path_t output_filename = vmap.count("output-file") == 1
? vmap["output-file"].as<path_t>()
: change_extension(input_filename, IfcUtil::path::from_utf8(DEFAULT_EXTENSION));
if (output_filename.size() < 5) {
cerr_ << "[Error] Invalid or unsupported output file '" << output_filename << "' given" << std::endl;
print_usage();
return EXIT_FAILURE;
}
if (file_exists(IfcUtil::path::to_utf8(output_filename)) && !vmap.count("yes")) {
std::string answer;
cout_ << "A file '" << output_filename << "' already exists. Overwrite the existing file? y/n" << std::endl;
std::cin >> answer;
if (!boost::iequals(answer, "yes") && !boost::iequals(answer, "y")) {
return EXIT_SUCCESS;
}
}
ofstream_t log_fs;
if (vmap.count("log-file")) {
log_fs.open(log_file.c_str(), std::ios::app);
Logger::SetOutput(quiet ? nullptr : &cout_, &log_fs);
} else {
Logger::SetOutput(quiet ? nullptr : &cout_, vcounter.count > 1 ? &cout_ : &log_stream);
}
switch (vcounter.count) {
case 0:
Logger::Verbosity(Logger::LOG_ERROR);
break;
case 1:
Logger::Verbosity(Logger::LOG_NOTICE);
break;
case 2:
Logger::Verbosity(Logger::LOG_DEBUG);
break;
case 3:
Logger::Verbosity(Logger::LOG_PERF);
break;
case 4:
Logger::Verbosity(Logger::LOG_PERF);
Logger::PrintPerformanceStatsOnElement(true);
break;
}
path_t output_temp_filename = output_filename + IfcUtil::path::from_utf8(TEMP_FILE_EXTENSION);
std::vector<path_t> tokens;
split(tokens, output_filename, boost::is_any_of("."));
std::vector<path_t>::iterator tok_iter;
path_t ext = *(tokens.end() - 1);
path_t dot;
dot = '.';
path_t output_extension = dot + ext;
boost::to_lower(output_extension);
IfcParse::IfcFile* ifc_file = 0;
boost::optional<std::list<IfcGeom::Element*>> elems_from_adaptor;
const path_t OBJ = IfcUtil::path::from_utf8(".obj"),
MTL = IfcUtil::path::from_utf8(".mtl"),
DAE = IfcUtil::path::from_utf8(".dae"),
GLB = IfcUtil::path::from_utf8(".glb"),
STP = IfcUtil::path::from_utf8(".stp"),
IGS = IfcUtil::path::from_utf8(".igs"),
SVG = IfcUtil::path::from_utf8(".svg"),
CACHE = IfcUtil::path::from_utf8(".cache"),
HDF = IfcUtil::path::from_utf8(".h5"),
XML = IfcUtil::path::from_utf8(".xml"),
JSON = IfcUtil::path::from_utf8(".json"),
// @todo this is just temporary as it doesn't make sense to require an extension for a DB
RDB = IfcUtil::path::from_utf8(".rdb"),
IFC = IfcUtil::path::from_utf8(".ifc"),
USD = IfcUtil::path::from_utf8(".usd"),
USDA = IfcUtil::path::from_utf8(".usda"),
USDC = IfcUtil::path::from_utf8(".usdc"),
TTL = IfcUtil::path::from_utf8(".ttl");
// @todo clean up serializer selection
// @todo detect program options that conflict with the chosen serializer
if (output_extension == XML || output_extension == JSON) {
int exit_code = EXIT_FAILURE;
try {
if (init_input_file(IfcUtil::path::to_utf8(input_filename), ifc_file, no_progress || quiet, mmap)) {
time_t start, end;
time(&start);
if (output_extension == XML) {
XmlSerializer s(ifc_file, IfcUtil::path::to_utf8(output_temp_filename));
Logger::Status("Writing XML output...");
s.finalize();
} else {
#ifdef WITH_GLTF
JsonSerializer s(ifc_file, IfcUtil::path::to_utf8(output_temp_filename), JsonSerializer::JSON_DIALECT_CREOOX);
Logger::Status("Writing JSON output...");
s.finalize();
#endif
}
time(&end);
Logger::Status("Done! Conversion took " + format_duration(start, end));
IfcUtil::path::rename_file(IfcUtil::path::to_utf8(output_temp_filename), IfcUtil::path::to_utf8(output_filename));
exit_code = EXIT_SUCCESS;
}
} catch (const std::exception& e) {
Logger::Error(e);
}
write_log(!quiet);
return exit_code;
} else if (output_extension == IFC) {
int exit_code = EXIT_FAILURE;
try {
if (init_input_file(IfcUtil::path::to_utf8(input_filename), ifc_file, no_progress || quiet, mmap)) {
time_t start, end;
time(&start);
std::ofstream fs(output_filename.c_str());
if (fs.is_open()) {
if (vmap.count("calculate-quantities")) {
fix_quantities(*ifc_file, no_progress, quiet, stderr_progress);
}
fs << *ifc_file;
exit_code = EXIT_SUCCESS;
} else {
Logger::Error("Unable to open output file for writing");
}
time(&end);
Logger::Status("Done! Writing IFC took " + format_duration(start, end));
}
} catch (const std::exception& e) {
Logger::Error(e);
}
write_log(!quiet);
return exit_code;
}
#ifdef WITH_ROCKSDB
else if (output_extension == RDB) {
int exit_code = EXIT_FAILURE;
try {
if (vmap.count("stream")) {
time_t start, end;
time(&start);
RocksDbSerializer s(IfcUtil::path::to_utf8(input_filename), IfcUtil::path::to_utf8(output_filename), true);
Logger::Status("Populating RocksDB Key-Value store...");
s.finalize();
time(&end);
Logger::Status("Done! Conversion took " + format_duration(start, end));
exit_code = EXIT_SUCCESS;
} else {
if (init_input_file(IfcUtil::path::to_utf8(input_filename), ifc_file, no_progress || quiet, mmap)) {
time_t start, end;
time(&start);
RocksDbSerializer s(ifc_file, IfcUtil::path::to_utf8(output_filename));
Logger::Status("Populating RocksDB Key-Value store...");
s.finalize();
time(&end);
Logger::Status("Done! Conversion took " + format_duration(start, end));
exit_code = EXIT_SUCCESS;
}
}
} catch (const std::exception& e) {
Logger::Error(e);
}
write_log(!quiet);
return exit_code;
}
#endif
/// @todo Clean up this filter code further.
std::vector<geom_filter> used_filters;
if (include_filter.type != geom_filter::UNUSED) { used_filters.push_back(include_filter); }
if (include_traverse_filter.type != geom_filter::UNUSED) { used_filters.push_back(include_traverse_filter); }
if (exclude_filter.type != geom_filter::UNUSED) { used_filters.push_back(exclude_filter); }
if (exclude_traverse_filter.type != geom_filter::UNUSED) { used_filters.push_back(exclude_traverse_filter); }
std::vector<IfcGeom::filter_t> filter_funcs = setup_filters(used_filters, IfcUtil::path::to_utf8(output_extension));
if (filter_funcs.empty()) {
cerr_ << "[Error] Failed to set up geometry filters\n";
return EXIT_FAILURE;
}
if (!entity_filter.entity_names.empty()) { entity_filter.update_description(); Logger::Notice(entity_filter.description); }
if (!layer_filter.values.empty()) { layer_filter.update_description(); Logger::Notice(layer_filter.description); }
if (!attribute_filter.attribute_name.empty()) { attribute_filter.update_description(); Logger::Notice(attribute_filter.description); }
#ifdef _MSC_VER
if (output_extension == DAE || output_extension == STP || output_extension == IGS) {
#else
if (output_extension == DAE) {
#endif
// These serializers do not support opening unicode paths. Therefore
// a random temp file is generated using only ASCII characters instead.
std::random_device rng;
std::uniform_int_distribution<int> index_dist('A', 'Z');
{
std::string v = ".ifcopenshell.";
output_temp_filename = path_t(v.begin(), v.end());
}
for (int i = 0; i < 8; ++i) {
output_temp_filename.push_back(static_cast<path_t::value_type>(index_dist(rng)));
}
{
std::string v = ".tmp";
output_temp_filename += path_t(v.begin(), v.end());
}
}
// The OS will clean up for us if there is a leak
geometry_settings.get<ifcopenshell::geometry::settings::OcctNoCleanTriangulation>().value = true;
if (geometry_settings.get<ifcopenshell::geometry::settings::PermissiveShapeReuse>().get()) {
geometry_settings.get<ifcopenshell::geometry::settings::NoParallelMapping>().value = true;
}
if (geometry_settings.get<ifcopenshell::geometry::settings::UseElementHierarchy>().get() && output_extension != DAE && output_extension != USD && output_extension != USDA && output_extension != USDC && output_extension != GLB) {
cerr_ << "[Error] --use-element-hierarchy can be used only with .dae or .usd or .glb output.\n";
/// @todo Lots of duplicate error-and-exit code.
write_log(!quiet);
print_usage();
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename));
return EXIT_FAILURE;
}
if (vmap[ifcopenshell::geometry::settings::WeldVertices::name].defaulted()) {
geometry_settings.get<ifcopenshell::geometry::settings::WeldVertices>().value = false;
}
if (geometry_settings.get<ifcopenshell::geometry::settings::ForceSpaceTransparency>().has()) {
IfcGeom::update_default_style("IfcSpace")->transparency = geometry_settings.get<ifcopenshell::geometry::settings::ForceSpaceTransparency>().get();
}
if (output_extension == OBJ || output_extension == STP || output_extension == IGS) {
geometry_settings.get<ifcopenshell::geometry::settings::UseWorldCoords>().value = true;
}
if (output_extension == TTL) {
geometry_settings.get<ifcopenshell::geometry::settings::TriangulationType>().value = ifcopenshell::geometry::settings::TriangulationMethod::POLYHEDRON_WITH_HOLES;
}
if (output_extension == SVG) {
// SVG serialiazation depends on element hierarchy now to look up the parent
geometry_settings.get<ifcopenshell::geometry::settings::UseElementHierarchy>().value = true;
}
boost::shared_ptr<GeometrySerializer> serializer; /**< @todo use std::unique_ptr when possible */
if (output_extension == OBJ) {
// Do not use temp file for MTL as it's such a small file.
const path_t mtl_filename = change_extension(output_filename, MTL);
serializer = boost::make_shared<WaveFrontOBJSerializer>(IfcUtil::path::to_utf8(output_temp_filename), IfcUtil::path::to_utf8(mtl_filename), geometry_settings, serializer_settings);
#ifdef WITH_OPENCOLLADA
} else if (output_extension == DAE) {
serializer = boost::make_shared<ColladaSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
#endif
#ifdef WITH_GLTF
} else if (output_extension == GLB) {
serializer = boost::make_shared<GltfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
#endif
#ifdef WITH_USD
} else if (output_extension == USD || output_extension == USDA || output_extension == USDC) {
serializer = boost::make_shared<USDSerializer>(IfcUtil::path::to_utf8(output_filename), geometry_settings, serializer_settings);
#endif
#ifdef IFOPSH_WITH_OPENCASCADE
} else if (output_extension == STP) {
serializer = boost::make_shared<StepSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
} else if (output_extension == IGS) {
#if OCC_VERSION_HEX < 0x60900
// According to https://tracker.dev.opencascade.org/view.php?id=25689 something has been fixed in 6.9.0
IGESControl_Controller::Init(); // work around Open Cascade bug
#endif
serializer = boost::make_shared<IgesSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
} else if (output_extension == SVG) {
geometry_settings.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
serializer = boost::make_shared<SvgSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
#ifdef WITH_HDF5
} else if (output_extension == HDF) {
geometry_settings.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
serializer = boost::make_shared<HdfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
#endif
#endif
} else if (output_extension == TTL) {
serializer = boost::make_shared<TtlWktSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings);
} else {
cerr_ << "[Error] Unknown output filename extension '" << output_extension << "'\n";
write_log(!quiet);
print_usage();
return EXIT_FAILURE;
}
const bool is_tesselated = serializer->isTesselated(); // isTesselated() doesn't change at run-time
if (!is_tesselated) {
if (geometry_settings.get<ifcopenshell::geometry::settings::WeldVertices>().get()) {
Logger::Notice("Weld vertices setting ignored when writing non-tesselated output");
}
if (geometry_settings.get<ifcopenshell::geometry::settings::GenerateUvs>().get()) {
Logger::Notice("Generate UVs setting ignored when writing non-tesselated output");
}
if (center_model || center_model_geometry) {
Logger::Notice("Centering/offsetting model setting ignored when writing non-tesselated output");
}
geometry_settings.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
}
if (!serializer->ready()) {
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename));
write_log(!quiet);
return EXIT_FAILURE;
}
time_t start,end;
time(&start);
// @nb last argument true -> bypass_properties which are not read by any of the geometry serializers
// XML, RocksDB, IFC are already special-cased above
// SVG requires properties for IfcAnnotation/DRAWING properties
if (!init_input_file(IfcUtil::path::to_utf8(input_filename), ifc_file, no_progress || quiet, mmap, output_extension != SVG)) {
write_log(!quiet);
serializer.reset();
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename)); /**< @todo Windows Unicode support */
return EXIT_FAILURE;
}
if (vmap.count("log-file")) {
Logger::SetOutput(quiet ? nullptr : &cout_, &log_fs);
} else {
Logger::SetOutput(quiet ? nullptr : &cout_, vcounter.count > 1 ? &cout_ : &log_stream);
}
if (model_rotation) {
std::vector<double> rotation(4);
int n = 0;
if (sscanf(rotation_str.c_str(), "%lf;%lf;%lf;%lf %n", &rotation[0], &rotation[1], &rotation[2], &rotation[3], &n) != 4 || n != rotation_str.size()) {
cerr_ << "[Error] Invalid use of --model-rotation\n";
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename));
print_options(serializer_options);
return EXIT_FAILURE;
}
std::stringstream msg;
msg << "Using model rotation (" << rotation[0] << "," << rotation[1] << "," << rotation[2] << "," << rotation[3] << ")";
Logger::Notice(msg.str());
geometry_settings.get<ifcopenshell::geometry::settings::ModelRotation>().value = rotation;
}
if (model_offset && (center_model || center_model_geometry)) {
Logger::Notice("--model-offset ignored with --center-model or --center-model-geometry");
}
if (model_offset && !(center_model || center_model_geometry)) {
std::vector<double> offset(3);
int n = 0;
if (sscanf(offset_str.c_str(), "%lf;%lf;%lf %n", &offset[0], &offset[1], &offset[2], &n) != 3 || n != offset_str.size()) {
cerr_ << "[Error] Invalid use of --model-offset\n";
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename));
print_options(serializer_options);
return EXIT_FAILURE;
}
std::stringstream msg;
msg << std::setprecision(std::numeric_limits<double>::max_digits10) << "Using model offset (" << offset[0] << "," << offset[1] << "," << offset[2] << ")";
Logger::Notice(msg.str());
geometry_settings.get<ifcopenshell::geometry::settings::ModelOffset>().value = offset;
}
if (is_tesselated && (center_model || center_model_geometry)) {
std::vector<double> offset(3);
IfcGeom::Iterator tmp_context_iterator(ifcopenshell::geometry::kernels::construct(ifc_file, geometry_kernel, geometry_settings), geometry_settings, ifc_file, filter_funcs, num_threads);
time_t start, end;
time(&start);
if (!quiet) Logger::Status("Computing bounds...");
if (center_model_geometry) {
if (!tmp_context_iterator.initialize()) {
/// @todo It would be nice to know and print separate error prints for a case where we found no entities
/// and for a case we found no entities that satisfy our filtering criteria.
Logger::Notice("No geometrical elements found or none successfully converted");
serializer.reset();
IfcUtil::path::delete_file(IfcUtil::path::to_utf8(output_temp_filename));
write_log(!quiet);
return EXIT_FAILURE;
}
}
tmp_context_iterator.compute_bounds(center_model_geometry);
time(&end);
if (!quiet) Logger::Status("Done ! Bounds computed in " + format_duration(start, end));
auto center = (tmp_context_iterator.bounds_min().ccomponents() + tmp_context_iterator.bounds_max().ccomponents()) * 0.5;
offset[0] = -center(0);
offset[1] = -center(1);
offset[2] = -center(2);
std::stringstream msg;
msg << std::setprecision (std::numeric_limits<double>::max_digits10) << "Using model offset (" << offset[0] << "," << offset[1] << "," << offset[2] << ")";
Logger::Notice(msg.str());
geometry_settings.get<ifcopenshell::geometry::settings::ModelOffset>().value = offset;
}
// backwards compatibility
if (vmap.count("plan") && vmap.count("model")) {
geometry_settings.get<ifcopenshell::geometry::settings::OutputDimensionality>().value = ifcopenshell::geometry::settings::CURVES_SURFACES_AND_SOLIDS;
} else if (vmap.count("model")) {
geometry_settings.get<ifcopenshell::geometry::settings::OutputDimensionality>().value = ifcopenshell::geometry::settings::SURFACES_AND_SOLIDS;
} else if (vmap.count("plan")) {
geometry_settings.get<ifcopenshell::geometry::settings::OutputDimensionality>().value = ifcopenshell::geometry::settings::CURVES;
}
std::unique_ptr<IfcGeom::Iterator> context_iterator;
if (!elems_from_adaptor) {
context_iterator.reset(new IfcGeom::Iterator(ifcopenshell::geometry::kernels::construct(ifc_file, geometry_kernel, geometry_settings), geometry_settings, ifc_file, filter_funcs, num_threads));
}