Debian Codegraph @

src/App/ComplexGeoData.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /****************************************************************************
3 * *
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * Copyright (c) 2022 Zheng, Lei <[email protected]> *
6 * Copyright (c) 2023 FreeCAD Project Association *
7 * *
8 * This file is part of FreeCAD. *
9 * *
10 * FreeCAD is free software: you can redistribute it and/or modify it *
11 * under the terms of the GNU Lesser General Public License as *
12 * published by the Free Software Foundation, either version 2.1 of the *
13 * License, or (at your option) any later version. *
14 * *
15 * FreeCAD is distributed in the hope that it will be useful, but *
16 * WITHOUT ANY WARRANTY; without even the implied warranty of *
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
18 * Lesser General Public License for more details. *
19 * *
20 * You should have received a copy of the GNU Lesser General Public *
21 * License along with FreeCAD. If not, see *
22 * <https://www.gnu.org/licenses/>. *
23 * *
24 ***************************************************************************/
25
26 #include <cstdlib>
27 #include <limits>
28
29 #include <boost/regex.hpp>
30
31 #include "ComplexGeoData.h"
32 #include "ElementMap.h"
33 #include "ElementNamingUtils.h"
34
35 #include <Base/BoundBox.h>
36 #include <Base/Placement.h>
37 #include <Base/Reader.h>
38 #include <Base/Rotation.h>
39 #include <Base/Writer.h>
40
41 #include <boost/iostreams/device/array.hpp>
42 #include <boost/iostreams/stream.hpp>
43
44
45 using namespace Data;
46
47 TYPESYSTEM_SOURCE_ABSTRACT(Data::Segment, Base::BaseClass) // NOLINT
48 TYPESYSTEM_SOURCE_ABSTRACT(Data::ComplexGeoData, Base::Persistence) // NOLINT
49
50 FC_LOG_LEVEL_INIT("ComplexGeoData", true, true) // NOLINT
51
52 namespace bio = boost::iostreams;
53 using namespace Data;
54
55 // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
56
57 ComplexGeoData::ComplexGeoData() = default;
58
59 std::pair<std::string, unsigned long> ComplexGeoData::getTypeAndIndex(const char* Name)
60 {
61 int index = 0;
62 std::string element;
63 boost::regex ex("^([^0-9]*)([0-9]*)$");
64 boost::cmatch what;
65
66 if (Name && boost::regex_match(Name, what, ex)) {
67 element = what[1].str();
68 index = std::atoi(what[2].str().c_str());
69 }
70
71 return std::make_pair(element, index);
72 }
73
74 Data::Segment* ComplexGeoData::getSubElementByName(const char* name) const
75 {
76 auto type = getTypeAndIndex(name);
77 return getSubElement(type.first.c_str(), type.second);
78 }
79
80 void ComplexGeoData::applyTransform(const Base::Matrix4D& rclTrf)
81 {
82 setTransform(rclTrf * getTransform());
83 }
84
85 void ComplexGeoData::applyTranslation(const Base::Vector3d& mov)
86 {
87 Base::Matrix4D mat;
88 mat.move(mov);
89 setTransform(mat * getTransform());
90 }
91
92 void ComplexGeoData::applyRotation(const Base::Rotation& rot)
93 {
94 Base::Matrix4D mat;
95 rot.getValue(mat);
96 setTransform(mat * getTransform());
97 }
98
99 void ComplexGeoData::setPlacement(const Base::Placement& rclPlacement)
100 {
101 setTransform(rclPlacement.toMatrix());
102 }
103
104 Base::Placement ComplexGeoData::getPlacement() const
105 {
106 Base::Matrix4D mat = getTransform();
107
108 return {Base::Vector3d(mat[0][3], mat[1][3], mat[2][3]), Base::Rotation(mat)};
109 }
110
111 double ComplexGeoData::getAccuracy() const
112 {
113 return 0.0;
114 }
115
116 void ComplexGeoData::getLinesFromSubElement(const Segment* segment,
117 std::vector<Base::Vector3d>& Points,
118 std::vector<Line>& lines) const
119 {
120 (void)segment;
121 (void)Points;
122 (void)lines;
123 }
124
125 void ComplexGeoData::getFacesFromSubElement(const Segment* segment,
126 std::vector<Base::Vector3d>& Points,
127 std::vector<Base::Vector3d>& PointNormals,
128 std::vector<Facet>& faces) const
129 {
130 (void)segment;
131 (void)Points;
132 (void)PointNormals;
133 (void)faces;
134 }
135
136 Base::Vector3d ComplexGeoData::getPointFromLineIntersection(const Base::Vector3f& base,
137 const Base::Vector3f& dir) const
138 {
139 (void)base;
140 (void)dir;
141 return Base::Vector3d();
142 }
143
144 void ComplexGeoData::getPoints(std::vector<Base::Vector3d>& Points,
145 std::vector<Base::Vector3d>& Normals,
146 double Accuracy,
147 uint16_t flags) const
148 {
149 (void)Points;
150 (void)Normals;
151 (void)Accuracy;
152 (void)flags;
153 }
154
155 void ComplexGeoData::getLines(std::vector<Base::Vector3d>& Points,
156 std::vector<Line>& lines,
157 double Accuracy,
158 uint16_t flags) const
159 {
160 (void)Points;
161 (void)lines;
162 (void)Accuracy;
163 (void)flags;
164 }
165
166 void ComplexGeoData::getFaces(std::vector<Base::Vector3d>& Points,
167 std::vector<Facet>& faces,
168 double Accuracy,
169 uint16_t flags) const
170 {
171 (void)Points;
172 (void)faces;
173 (void)Accuracy;
174 (void)flags;
175 }
176
177 bool ComplexGeoData::getCenterOfGravity(Base::Vector3d& unused) const
178 {
179 (void)unused;
180 return false;
181 }
182
183 std::optional<Base::Vector3d> ComplexGeoData::centerOfGravity() const
184 {
185 Base::Vector3d centerOfGravity;
186
187 if (getCenterOfGravity(centerOfGravity)) {
188 return centerOfGravity;
189 }
190
191 return {};
192 }
193
194 const std::string& ComplexGeoData::elementMapPrefix()
195 {
196 static std::string prefix(ELEMENT_MAP_PREFIX);
197 return prefix;
198 }
199
200 std::string ComplexGeoData::getElementMapVersion() const
201 {
202 return "5";
203 }
204
205 bool ComplexGeoData::checkElementMapVersion(const char* ver) const
206 {
207 return !boost::ends_with(ver, "5");
208 }
209
210 size_t ComplexGeoData::getElementMapSize(bool flush) const
211 {
212 if (flush) {
213 flushElementMap();
214 #ifdef _FC_MEM_TRACE
215 FC_MSG("memory size " << (_MemSize / 1024 / 1024) << "MB, " << (_MemMaxSize / 1024 / 1024));
216 for (auto& unit : _MemUnits) {
217 FC_MSG("unit " << unit.first << ": " << unit.second.count << ", "
218 << unit.second.maxcount);
219 }
220 #endif
221 }
222 return _elementMap ? _elementMap->size() : 0;
223 }
224
225 MappedName ComplexGeoData::getMappedName(const IndexedName& element,
226 bool allowUnmapped,
227 ElementIDRefs* sid) const
228 {
229 if (!element) {
230 return {};
231 }
232 flushElementMap();
233 if (!_elementMap) {
234 if (allowUnmapped) {
235 return MappedName(element);
236 }
237 return {};
238 }
239
240 MappedName name = _elementMap->find(element, sid);
241 if (allowUnmapped && !name) {
242 return MappedName(element);
243 }
244 return name;
245 }
246
247 IndexedName ComplexGeoData::getIndexedName(const MappedName& name, ElementIDRefs* sid) const
248 {
249 flushElementMap();
250 if (!name) {
251 return IndexedName();
252 }
253 if (!_elementMap) {
254 std::string str;
255 return {name.appendToBuffer(str), getElementTypes()};
256 }
257 return _elementMap->find(name, sid);
258 }
259
260 Data::MappedElement
261 ComplexGeoData::getElementName(const char* name, ElementIDRefs* sid, bool copy) const
262 {
263 IndexedName element(name, getElementTypes());
264 if (element) {
265 return {getMappedName(element, false, sid), element};
266 }
267
268 const char* mapped = isMappedElement(name);
269 if (mapped) {
270 name = mapped;
271 }
272
273 MappedElement result;
274 // Strip out the trailing '.XXXX' if any
275 const char* dot = strchr(name, '.');
276 if (dot) {
277 result.name = MappedName(name, static_cast<int>(dot - name));
278 }
279 else if (copy) {
280 result.name = name;
281 }
282 else {
283 result.name = MappedName(name);
284 }
285 result.index = getIndexedName(result.name, sid);
286 return result;
287 }
288
289 std::vector<std::pair<MappedName, ElementIDRefs>>
290 ComplexGeoData::getElementMappedNames(const IndexedName& element, bool needUnmapped) const
291 {
292 flushElementMap();
293 if (_elementMap) {
294 auto res = _elementMap->findAll(element);
295 if (!res.empty()) {
296 return res;
297 }
298 }
299
300 if (!needUnmapped) {
301 return {};
302 }
303 return {std::make_pair(MappedName(element), ElementIDRefs())};
304 }
305
306 ElementMapPtr ComplexGeoData::resetElementMap(ElementMapPtr elementMap)
307 {
308 _elementMap.swap(elementMap);
309 // We expect that if the ComplexGeoData ( TopoShape ) has a hasher, then its elementMap will
310 // have the same one. Make sure that happens.
311 if (_elementMap && !_elementMap->hasher) {
312 _elementMap->hasher = Hasher;
313 }
314 return elementMap;
315 }
316
317 std::vector<MappedElement> ComplexGeoData::getElementMap() const
318 {
319 flushElementMap();
320 if (!_elementMap) {
321 return {};
322 }
323 return _elementMap->getAll();
324 }
325
326 ElementMapPtr ComplexGeoData::elementMap(bool flush) const
327 {
328 if (flush) {
329 flushElementMap();
330 }
331 return _elementMap;
332 }
333
334 ElementMapPtr ComplexGeoData::ensureElementMap(bool flush)
335 {
336 if (!_elementMap) {
337 resetElementMap(std::make_shared<Data::ElementMap>());
338 }
339 return elementMap(flush);
340 }
341
342 void ComplexGeoData::flushElementMap() const
343 {}
344
345 void ComplexGeoData::setElementMap(const std::vector<MappedElement>& map)
346 {
347 _elementMap = std::make_shared<Data::ElementMap>(); // Get rid of the old one, if any, but make
348 // sure the memory exists for the new data.
349 for (auto& element : map) {
350 _elementMap->setElementName(element.index, element.name, Tag);
351 }
352 }
353
354 char ComplexGeoData::elementType(const Data::MappedName& name) const
355 {
356 if (!name) {
357 return 0;
358 }
359 auto indexedName = getIndexedName(name);
360 if (indexedName) {
361 return elementType(indexedName);
362 }
363 char element_type = 0;
364 if (name.findTagInElementName(nullptr, nullptr, nullptr, &element_type) < 0) {
365 return elementType(name.toIndexedName());
366 }
367 return element_type;
368 }
369
370 char ComplexGeoData::elementType(const Data::IndexedName& element) const
371 {
372 if (!element) {
373 return 0;
374 }
375 for (auto& type : getElementTypes()) {
376 if (boost::equals(element.getType(), type)) {
377 return type[0];
378 }
379 }
380 return 0;
381 }
382
383 // The elementType function can take a char *, in which case it tries a sequence of checks to
384 // see what it got.
385 // 1) Check to see if it is an indexedName, and if so directly look up the type
386 // 2) If not:
387 // a) Remove any element map prefix that is present
388 // b) See if the name contains a dot:
389 // i) If yes, create a MappedName from the part before the dot, and set the type to the
390 // part after the dot
391 // ii) If no, create a MappedName from the whole name
392 // c) Try to get the elementType based on the MappedName. Return it if found
393 // 3) Check to make sure the discovered type is in the list of types, and return its first
394 // character if so.
395 char ComplexGeoData::elementType(const char* name) const
396 {
397 if (!name) {
398 return 0;
399 }
400
401 const char* type = nullptr;
402 IndexedName element(name, getElementTypes());
403 if (element) {
404 type = element.getType();
405 }
406 else {
407 const char* mapped = isMappedElement(name);
408 if (mapped) {
409 name = mapped;
410 }
411
412 MappedName mappedName;
413 const char* dot = strchr(name, '.');
414 if (dot) {
415 mappedName = MappedName(name, static_cast<int>(dot - name));
416 type = dot + 1;
417 }
418 else {
419 mappedName = MappedName::fromRawData(name);
420 }
421 char res = elementType(mappedName);
422 if (res != 0) {
423 return res;
424 }
425 }
426
427 if (type && (type[0] != 0)) {
428 for (auto& elementTypes : getElementTypes()) {
429 if (boost::starts_with(type, elementTypes)) {
430 return type[0];
431 }
432 }
433 }
434 return 0;
435 }
436
437 void ComplexGeoData::setPersistenceFileName(const char* filename) const
438 {
439 if (!filename) {
440 filename = "";
441 }
442 _persistenceName = filename;
443 }
444
445 void ComplexGeoData::Save(Base::Writer& writer) const
446 {
447
448 if (getElementMapSize() == 0U) {
449 writer.Stream() << writer.ind() << "<ElementMap/>\n";
450 return;
451 }
452
453 // Store some dummy map entry to trigger recompute in older version.
454 writer.Stream() << writer.ind() << R"(<ElementMap new="1" count="1">)"
455 << R"(<Element key="Dummy" value="Dummy"/>)"
456 << "</ElementMap>\n";
457
458 // New layout of element map, so we use new xml tag, ElementMap2
459 writer.Stream() << writer.ind() << "<ElementMap2";
460
461 if (!_persistenceName.empty()) {
462 writer.Stream() << " file=\"" << writer.addFile((_persistenceName + ".txt").c_str(), this)
463 << "\"/>\n";
464 return;
465 }
466 writer.Stream() << " count=\"" << _elementMap->size() << "\">\n";
467 _elementMap->save(writer.beginCharStream(Base::CharStreamFormat::Raw) << '\n');
468 writer.endCharStream() << '\n';
469 writer.Stream() << writer.ind() << "</ElementMap2>\n";
470 }
471
472 void ComplexGeoData::Restore(Base::XMLReader& reader)
473 {
474 resetElementMap();
475
476 reader.readElement("ElementMap");
477 bool newTag = false;
478 if (reader.hasAttribute("new") && reader.getAttribute<bool>("new")) {
479 reader.readEndElement("ElementMap");
480 reader.readElement("ElementMap2");
481 newTag = true;
482 }
483
484 const char* file = "";
485 if (reader.hasAttribute("file")) {
486 file = reader.getAttribute<const char*>("file");
487 }
488 if (*file != 0) {
489 reader.addFile(file, this);
490 return;
491 }
492
493 std::size_t count = 0;
494 if (reader.hasAttribute("count")) {
495 count = reader.getAttribute<unsigned long>("count");
496 }
497 if (count == 0) {
498 return;
499 }
500
501 if (newTag) {
502 resetElementMap(std::make_shared<ElementMap>());
503 _elementMap =
504 _elementMap->restore(Hasher, reader.beginCharStream(Base::CharStreamFormat::Raw));
505 reader.endCharStream();
506 reader.readEndElement("ElementMap2");
507 return;
508 }
509
510 if (reader.FileVersion > 1) {
511 restoreStream(reader.beginCharStream(Base::CharStreamFormat::Raw), count);
512 reader.endCharStream();
513 return;
514 }
515 readElements(reader, count);
516 reader.readEndElement("ElementMap");
517 }
518
519 void ComplexGeoData::readElements(Base::XMLReader& reader, size_t count)
520 {
521 size_t invalid_count = 0;
522 bool warned = false;
523
524 const auto& types = getElementTypes();
525
526 for (size_t i = 0; i < count; ++i) {
527 reader.readElement("Element");
528 ElementIDRefs sids;
529 if (reader.hasAttribute("sid")) {
530 if (!Hasher) {
531 if (!warned) {
532 warned = true;
533 FC_ERR("missing hasher"); // NOLINT
534 }
535 }
536 else {
537 const char* attr = reader.getAttribute<const char*>("sid");
538 bio::stream<bio::array_source> iss(attr, std::strlen(attr));
539 long id {};
540 while ((iss >> id)) {
541 if (id == 0) {
542 continue;
543 }
544 auto sid = Hasher->getID(id);
545 if (!sid) {
546 ++invalid_count;
547 }
548 else {
549 sids.push_back(sid);
550 }
551 char sep {};
552 iss >> sep;
553 }
554 }
555 }
556 ensureElementMap()->setElementName(IndexedName(reader.getAttribute<const char*>("value"), types),
557 MappedName(reader.getAttribute<const char*>("key")),
558 Tag,
559 &sids);
560 }
561 if (invalid_count != 0) {
562 FC_ERR("Found " << invalid_count << " invalid string id"); // NOLINT
563 }
564 }
565
566 void ComplexGeoData::restoreStream(std::istream& stream, std::size_t count)
567 {
568 resetElementMap();
569
570 size_t invalid_count = 0;
571 std::string key;
572 std::string value;
573 std::string sid;
574 bool warned = false;
575
576 const auto& types = getElementTypes();
577 try {
578 for (size_t i = 0; i < count; ++i) {
579 ElementIDRefs sids;
580 std::size_t sCount = 0;
581 if (!(stream >> value >> key >> sCount)) {
582 // NOLINTNEXTLINE
583 FC_THROWM(Base::RuntimeError, "Failed to restore element map " << _persistenceName);
584 }
585 constexpr std::size_t oneGbOfInts {(1 << 30) / sizeof(int)};
586 if (sCount > oneGbOfInts) {
587 // NOLINTNEXTLINE
588 FC_THROWM(Base::RuntimeError, "Failed to restore element map (>1GB) " << _persistenceName);
589 }
590 sids.reserve(static_cast<int>(sCount));
591 for (std::size_t j = 0; j < sCount; ++j) {
592 long id = 0;
593 if (!(stream >> id)) {
594 // NOLINTNEXTLINE
595 FC_THROWM(Base::RuntimeError,
596 "Failed to restore element map " << _persistenceName);
597 }
598 if (Hasher) {
599 auto hasherSID = Hasher->getID(id);
600 if (!hasherSID) {
601 ++invalid_count;
602 }
603 else {
604 sids.push_back(hasherSID);
605 }
606 }
607 }
608 if (sCount != 0 && !Hasher) {
609 sids.clear();
610 if (!warned) {
611 warned = true;
612 FC_ERR("missing hasher"); // NOLINT
613 }
614 }
615 _elementMap->setElementName(IndexedName(value.c_str(), types),
616 MappedName(key),
617 Tag,
618 &sids);
619 }
620 }
621 catch (Base::Exception& e) {
622 e.reportException();
623 _restoreFailed = true;
624 _elementMap.reset();
625 }
626 if (invalid_count != 0) {
627 FC_ERR("Found " << invalid_count << " invalid string id"); // NOLINT
628 }
629 }
630
631 void ComplexGeoData::SaveDocFile(Base::Writer& writer) const
632 {
633 flushElementMap();
634 if (_elementMap) {
635 writer.Stream() << "BeginElementMap v1\n";
636 _elementMap->save(writer.Stream());
637 }
638 }
639
640 void ComplexGeoData::RestoreDocFile(Base::Reader& reader)
641 {
642 std::string marker;
643 std::string ver;
644 reader >> marker;
645 if (boost::equals(marker, "BeginElementMap")) {
646 resetElementMap();
647 reader >> ver;
648 if (ver != "v1") {
649 FC_WARN("Unknown element map format"); // NOLINT
650 }
651 else {
652 resetElementMap(std::make_shared<ElementMap>());
653 _elementMap = _elementMap->restore(Hasher, reader);
654 return;
655 }
656 }
657 auto count = atoll(marker.c_str()); // Try to prevent UB if the number is unreasonably large
658 if (count < 0 || count > std::numeric_limits<int>::max()) {
659 FC_THROWM(Base::RuntimeError, "Failed to restore element map " << _persistenceName);
660 }
661 restoreStream(reader, static_cast<std::size_t>(count));
662 }
663
664 unsigned int ComplexGeoData::getMemSize() const
665 {
666 flushElementMap();
667 if (_elementMap) {
668 static const int multiplier {10};
669 return _elementMap->size() * multiplier;
670 }
671 return 0;
672 }
673
674 std::vector<IndexedName> ComplexGeoData::getHigherElements(const char*, bool) const
675 {
676 return {};
677 }
678
679 void ComplexGeoData::setMappedChildElements(
680 const std::vector<Data::ElementMap::MappedChildElements>& children)
681 {
682 // DO NOT reset element map if there is one. Because we allow mixing child
683 // mapping and normal mapping
684 if (!_elementMap) {
685 resetElementMap(std::make_shared<Data::ElementMap>());
686 }
687 _elementMap->addChildElements(Tag, children);
688 }
689
690 std::vector<Data::ElementMap::MappedChildElements> ComplexGeoData::getMappedChildElements() const
691 {
692 if (!_elementMap) {
693 return {};
694 }
695 return _elementMap->getChildElements();
696 }
697
698 void ComplexGeoData::beforeSave() const
699 {
700 flushElementMap();
701 if (this->_elementMap) {
702 this->_elementMap->beforeSave(Hasher);
703 }
704 }
705
706 void ComplexGeoData::hashChildMaps()
707 {
708 flushElementMap();
709 if (_elementMap) {
710 _elementMap->hashChildMaps(Tag);
711 }
712 }
713
714 bool ComplexGeoData::hasChildElementMap() const
715 {
716 flushElementMap();
717 return _elementMap && _elementMap->hasChildElementMap();
718 }
719
720 void ComplexGeoData::dumpElementMap(std::ostream& stream) const
721 {
722 auto map = getElementMap();
723 std::sort(map.begin(), map.end());
724 for (auto& element : map) {
725 stream << element.index << " : " << element.name << std::endl;
726 }
727 }
728
729 const std::string ComplexGeoData::dumpElementMap() const
730 {
731 std::stringstream ss;
732 dumpElementMap(ss);
733 return ss.str();
734 }
735
736 // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)