deal.II version GIT relicensing-6960-g70e9c5b7be 2026-10-22 20:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
utilities.cc
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2014 - 2026 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13#include <deal.II/base/config.h>
14
16
17#ifdef DEAL_II_WITH_OPENCASCADE
18
20# include <deal.II/base/point.h>
22
24
25# include <BRepAdaptor_Curve.hxx>
26# include <IGESControl_Controller.hxx>
27# include <IGESControl_Reader.hxx>
28# include <IGESControl_Writer.hxx>
29# include <STEPControl_Controller.hxx>
30# include <STEPControl_Reader.hxx>
31# include <STEPControl_Writer.hxx>
32# include <Standard_Transient.hxx>
33# include <TopExp_Explorer.hxx>
34# include <TopoDS.hxx>
35# include <TopoDS_Edge.hxx>
36# include <TopoDS_Face.hxx>
37# include <TopoDS_Shape.hxx>
38
39# include <cstdio>
40# include <iostream>
41# if DEAL_II_OPENCASCADE_VERSION_GTE(7, 6, 0)
42# include <BRepAlgoAPI_Section.hxx>
43# else
44# include <BRepAdaptor_HCompCurve.hxx>
45# include <BRepAdaptor_HCurve.hxx>
46# include <BRepAlgo_Section.hxx>
47# endif
48# include <BRepAdaptor_Surface.hxx>
49# include <BRepBndLib.hxx>
50# include <BRepBuilderAPI_MakeEdge.hxx>
51# include <BRepBuilderAPI_Sewing.hxx>
52# include <BRepBuilderAPI_Transform.hxx>
53# include <BRepMesh_IncrementalMesh.hxx>
54# include <BRepTools.hxx>
55# include <BRep_Builder.hxx>
56# include <GCPnts_AbscissaPoint.hxx>
57# include <GeomAPI_Interpolate.hxx>
58# include <GeomAPI_ProjectPointOnCurve.hxx>
59# include <GeomAPI_ProjectPointOnSurf.hxx>
60# include <GeomConvert_CompCurveToBSplineCurve.hxx>
61# include <GeomLProp_SLProps.hxx>
62# include <Geom_BoundedCurve.hxx>
63# include <Geom_Plane.hxx>
64# include <IntCurvesFace_ShapeIntersector.hxx>
65# include <Poly_Triangulation.hxx>
66# include <ShapeAnalysis_Surface.hxx>
67# include <StlAPI_Reader.hxx>
68# include <StlAPI_Writer.hxx>
69# include <TColStd_HSequenceOfTransient.hxx>
70# include <TColStd_SequenceOfTransient.hxx>
71# include <TColgp_HArray1OfPnt.hxx>
72# include <TopLoc_Location.hxx>
73# include <gp_Lin.hxx>
74# include <gp_Pnt.hxx>
75# include <gp_Vec.hxx>
76
77# include <algorithm>
78# include <vector>
79
80
81#endif
82
84
85#ifdef DEAL_II_WITH_OPENCASCADE
86
87namespace OpenCASCADE
88{
89 std::tuple<unsigned int, unsigned int, unsigned int>
90 count_elements(const TopoDS_Shape &shape)
91 {
92 TopExp_Explorer exp;
93 unsigned int n_faces = 0, n_edges = 0, n_vertices = 0;
94 for (exp.Init(shape, TopAbs_FACE); exp.More(); exp.Next(), ++n_faces)
95 {
96 }
97 for (exp.Init(shape, TopAbs_EDGE); exp.More(); exp.Next(), ++n_edges)
98 {
99 }
100 for (exp.Init(shape, TopAbs_VERTEX); exp.More(); exp.Next(), ++n_vertices)
101 {
102 }
103 return std::tuple<unsigned int, unsigned int, unsigned int>(n_faces,
104 n_edges,
105 n_vertices);
106 }
107
108 void
109 extract_geometrical_shapes(const TopoDS_Shape &shape,
110 std::vector<TopoDS_Face> &faces,
111 std::vector<TopoDS_Edge> &edges,
112 std::vector<TopoDS_Vertex> &vertices)
113 {
114 faces.resize(0);
115 edges.resize(0);
116 vertices.resize(0);
117
118 TopExp_Explorer exp;
119 for (exp.Init(shape, TopAbs_FACE); exp.More(); exp.Next())
120 {
121 faces.push_back(TopoDS::Face(exp.Current()));
122 }
123 for (exp.Init(shape, TopAbs_EDGE); exp.More(); exp.Next())
124 {
125 edges.push_back(TopoDS::Edge(exp.Current()));
126 }
127 for (exp.Init(shape, TopAbs_VERTEX); exp.More(); exp.Next())
128 {
129 vertices.push_back(TopoDS::Vertex(exp.Current()));
130 }
131 }
132
133
134 void
135 extract_compound_shapes(const TopoDS_Shape &shape,
136 std::vector<TopoDS_Compound> &compounds,
137 std::vector<TopoDS_CompSolid> &compsolids,
138 std::vector<TopoDS_Solid> &solids,
139 std::vector<TopoDS_Shell> &shells,
140 std::vector<TopoDS_Wire> &wires)
141 {
142 compounds.resize(0);
143 compsolids.resize(0);
144 solids.resize(0);
145 shells.resize(0);
146 wires.resize(0);
147
148 TopExp_Explorer exp;
149 for (exp.Init(shape, TopAbs_COMPOUND); exp.More(); exp.Next())
150 {
151 compounds.push_back(TopoDS::Compound(exp.Current()));
152 }
153 for (exp.Init(shape, TopAbs_COMPSOLID); exp.More(); exp.Next())
154 {
155 compsolids.push_back(TopoDS::CompSolid(exp.Current()));
156 }
157 for (exp.Init(shape, TopAbs_SOLID); exp.More(); exp.Next())
158 {
159 solids.push_back(TopoDS::Solid(exp.Current()));
160 }
161 for (exp.Init(shape, TopAbs_SHELL); exp.More(); exp.Next())
162 {
163 shells.push_back(TopoDS::Shell(exp.Current()));
164 }
165 for (exp.Init(shape, TopAbs_WIRE); exp.More(); exp.Next())
166 {
167 wires.push_back(TopoDS::Wire(exp.Current()));
168 }
169 }
170
171 template <int spacedim>
172 gp_Pnt
174 {
175 switch (spacedim)
176 {
177 case 1:
178 return gp_Pnt(p[0], 0, 0);
179 case 2:
180 return gp_Pnt(p[0], p[1], 0);
181 case 3:
182 return gp_Pnt(p[0], p[1], p[2]);
183 }
185 return {};
186 }
187
188 template <int spacedim>
190 point(const gp_Pnt &p, const double tolerance)
191 {
192 (void)tolerance;
193 switch (spacedim)
194 {
195 case 1:
196 Assert(std::abs(p.Y()) <= tolerance,
198 "Cannot convert OpenCASCADE point to 1d if p.Y() != 0."));
199 Assert(std::abs(p.Z()) <= tolerance,
201 "Cannot convert OpenCASCADE point to 1d if p.Z() != 0."));
202 return Point<spacedim>(p.X());
203 case 2:
204 Assert(std::abs(p.Z()) <= tolerance,
206 "Cannot convert OpenCASCADE point to 2d if p.Z() != 0."));
207 return Point<spacedim>(p.X(), p.Y());
208 case 3:
209 return Point<spacedim>(p.X(), p.Y(), p.Z());
210 }
212 return {};
213 }
214
215 template <int dim>
216 bool
218 const Point<dim> &p2,
219 const Tensor<1, dim> &direction,
220 const double tolerance)
221 {
222 const double rel_tol =
223 std::max(tolerance, std::max(p1.norm(), p2.norm()) * tolerance);
224 if (direction.norm() > 0.0)
225 return (p1 * direction < p2 * direction - rel_tol);
226 else
227 for (int d = dim; d >= 0; --d)
228 if (p1[d] < p2[d] - rel_tol)
229 return true;
230 else if (p2[d] < p1[d] - rel_tol)
231 return false;
232
233 // If we got here, for all d, none of the conditions above was
234 // satisfied. The two points are equal up to tolerance
235 return false;
236 }
237
238
239 TopoDS_Shape
240 read_IGES(const std::string &filename, const double scale_factor)
241 {
242 IGESControl_Reader reader;
243 IFSelect_ReturnStatus stat;
244 stat = reader.ReadFile(filename.c_str());
245 AssertThrow(stat == IFSelect_RetDone, ExcMessage("Error in reading file!"));
246
247 Standard_Boolean failsonly = Standard_False;
248 IFSelect_PrintCount mode = IFSelect_ItemsByEntity;
249 reader.PrintCheckLoad(failsonly, mode);
250
251 Standard_Integer nRoots = reader.TransferRoots();
252 // selects all IGES entities (including non visible ones) in the
253 // file and puts them into a list called MyList,
254
255 AssertThrow(nRoots > 0, ExcMessage("Read nothing from file."));
256
257 // Handle IGES Scale here.
258 gp_Pnt Origin;
259 gp_Trsf scale;
260 scale.SetScale(Origin, scale_factor);
261
262 TopoDS_Shape sh = reader.OneShape();
263 BRepBuilderAPI_Transform trans(sh, scale);
264
265 return trans.Shape(); // this is the actual translation
266 }
267
268 void
269 write_IGES(const TopoDS_Shape &shape, const std::string &filename)
270 {
271 IGESControl_Controller::Init();
272 IGESControl_Writer ICW("MM", 0);
273 Standard_Boolean ok = ICW.AddShape(shape);
274 AssertThrow(ok, ExcMessage("Failed to add shape to IGES controller."));
275 ICW.ComputeModel();
276 Standard_Boolean OK = ICW.Write(filename.c_str());
277 AssertThrow(OK, ExcMessage("Failed to write IGES file."));
278 }
279
280
281 TopoDS_Shape
282 read_STL(const std::string &filename)
283 {
284 StlAPI_Reader reader;
285 TopoDS_Shape shape;
286 reader.Read(shape, filename.c_str());
287 return shape;
288 }
289
290
291 void
292 write_STL(const TopoDS_Shape &shape,
293 const std::string &filename,
294 const double deflection,
295 const bool sew_different_faces,
296 const double sewer_tolerance,
297 const bool is_relative,
298 const double angular_deflection,
299 const bool in_parallel)
300 {
301 TopLoc_Location Loc;
302 std::vector<TopoDS_Vertex> vertices;
303 std::vector<TopoDS_Edge> edges;
304 std::vector<TopoDS_Face> faces;
305 OpenCASCADE::extract_geometrical_shapes(shape, faces, edges, vertices);
306 const bool mesh_is_present =
307 std::none_of(faces.begin(), faces.end(), [&Loc](const TopoDS_Face &face) {
308 opencascade::handle<Poly_Triangulation> theTriangulation =
309 BRep_Tool::Triangulation(face, Loc);
310
311 return theTriangulation.IsNull();
312 });
313 TopoDS_Shape shape_to_be_written = shape;
314 if (!mesh_is_present)
315 {
316 if (sew_different_faces)
317 {
318 BRepBuilderAPI_Sewing sewer(sewer_tolerance);
319 sewer.Add(shape_to_be_written);
320 sewer.Perform();
321 shape_to_be_written = sewer.SewedShape();
322 }
323 else
324 shape_to_be_written = shape;
325 // BRepMesh_IncrementalMesh automatically calls the perform method to
326 // create the triangulation which is stored in the argument
327 // `shape_to_be_written`.
328 BRepMesh_IncrementalMesh mesh_im(shape_to_be_written,
329 deflection,
330 is_relative,
331 angular_deflection,
332 in_parallel);
333 }
334
335 StlAPI_Writer writer;
336
337
338 // opencascade versions 6.9.0 onwards return an error status
339 const auto error = writer.Write(shape_to_be_written, filename.c_str());
340
341 // which is a custom type between 6.9.0 and 7.1.0
342# if !DEAL_II_OPENCASCADE_VERSION_GTE(7, 2, 0)
343 AssertThrow(error == StlAPI_StatusOK,
344 ExcMessage("Error writing STL from shape. Status: " +
345 std::to_string(static_cast<int>(error))));
346# else
347 // and a boolean from version 7.2.0 onwards
348 AssertThrow(error == true, ExcMessage("Error writing STL from shape."));
349# endif
350 }
351
352 TopoDS_Shape
353 read_STEP(const std::string &filename, const double scale_factor)
354 {
355 STEPControl_Reader reader;
356 IFSelect_ReturnStatus stat;
357 stat = reader.ReadFile(filename.c_str());
358 AssertThrow(stat == IFSelect_RetDone, ExcMessage("Error in reading file!"));
359
360 Standard_Boolean failsonly = Standard_False;
361 IFSelect_PrintCount mode = IFSelect_ItemsByEntity;
362 reader.PrintCheckLoad(failsonly, mode);
363
364 Standard_Integer nRoots = reader.TransferRoots();
365 // selects all IGES entities (including non visible ones) in the
366 // file and puts them into a list called MyList,
367
368 AssertThrow(nRoots > 0, ExcMessage("Read nothing from file."));
369
370 // Handle STEP Scale here.
371 gp_Pnt Origin;
372 gp_Trsf scale;
373 scale.SetScale(Origin, scale_factor);
374
375 TopoDS_Shape sh = reader.OneShape();
376 BRepBuilderAPI_Transform trans(sh, scale);
377
378 return trans.Shape(); // this is the actual translation
379 }
380
381 void
382 write_STEP(const TopoDS_Shape &shape, const std::string &filename)
383 {
384 STEPControl_Controller::Init();
385 STEPControl_Writer SCW;
386 IFSelect_ReturnStatus status;
387 status = SCW.Transfer(shape, STEPControl_AsIs);
388 AssertThrow(status == IFSelect_RetDone,
389 ExcMessage("Failed to add shape to STEP controller."));
390
391 status = SCW.Write(filename.c_str());
392
393 AssertThrow(status == IFSelect_RetDone,
394 ExcMessage("Failed to write translated shape to STEP file."));
395 }
396
397 double
398 get_shape_tolerance(const TopoDS_Shape &shape)
399 {
400 double tolerance = 0.0;
401
402 std::vector<TopoDS_Face> faces;
403 std::vector<TopoDS_Edge> edges;
404 std::vector<TopoDS_Vertex> vertices;
405
406 extract_geometrical_shapes(shape, faces, edges, vertices);
407
408 for (const auto &vertex : vertices)
409 tolerance = std::fmax(tolerance, BRep_Tool::Tolerance(vertex));
410
411 for (const auto &edge : edges)
412 tolerance = std::fmax(tolerance, BRep_Tool::Tolerance(edge));
413
414 for (const auto &face : faces)
415 tolerance = std::fmax(tolerance, BRep_Tool::Tolerance(face));
416
417
418 return tolerance;
419 }
420
421 TopoDS_Shape
422 intersect_plane(const TopoDS_Shape &in_shape,
423 const double c_x,
424 const double c_y,
425 const double c_z,
426 const double c,
427 const double /*tolerance*/)
428 {
429 opencascade::handle<Geom_Plane> plane = new Geom_Plane(c_x, c_y, c_z, c);
430
431# if DEAL_II_OPENCASCADE_VERSION_GTE(7, 6, 0)
432 BRepAlgoAPI_Section section(in_shape, plane);
433# else
434 BRepAlgo_Section section(in_shape, plane);
435# endif
436 TopoDS_Shape edges = section.Shape();
437 return edges;
438 }
439
440 TopoDS_Edge
441 join_edges(const TopoDS_Shape &in_shape, const double tolerance)
442 {
443 TopoDS_Edge out_shape;
444 const TopoDS_Shape &edges = in_shape;
445
446 std::vector<opencascade::handle<Geom_BoundedCurve>> intersections;
447
448 TopLoc_Location L;
449 Standard_Real First;
450 Standard_Real Last;
451 gp_Pnt PIn(0.0, 0.0, 0.0);
452 gp_Pnt PFin(0.0, 0.0, 0.0);
453 gp_Pnt PMid(0.0, 0.0, 0.0);
454 TopExp_Explorer edgeExplorer(edges, TopAbs_EDGE);
455 TopoDS_Edge edge;
456 while (edgeExplorer.More())
457 {
458 edge = TopoDS::Edge(edgeExplorer.Current());
459 opencascade::handle<Geom_Curve> curve =
460 BRep_Tool::Curve(edge, L, First, Last);
461 intersections.push_back(
462 opencascade::handle<Geom_BoundedCurve>::DownCast(curve));
463
464 edgeExplorer.Next();
465 }
466
467 // Now we build a single bspline out of all the geometrical
468 // curves, in Lexycographical order
469 unsigned int numIntersEdges = intersections.size();
470 Assert(numIntersEdges > 0, ExcMessage("No curves to process!"));
471
472 GeomConvert_CompCurveToBSplineCurve convert_bspline(intersections[0]);
473
474 bool check = false, one_added = true, one_failed = true;
475 std::vector<bool> added(numIntersEdges, false);
476 added[0] = true;
477 while (one_added == true)
478 {
479 one_added = false;
480 one_failed = false;
481 for (unsigned int i = 1; i < numIntersEdges; ++i)
482 if (added[i] == false)
483 {
484 opencascade::handle<Geom_Curve> curve = intersections[i];
485
486 opencascade::handle<Geom_BoundedCurve> bcurve =
487 opencascade::handle<Geom_BoundedCurve>::DownCast(curve);
488
489 check = convert_bspline.Add(bcurve, tolerance, false, true, 0);
490 if (check ==
491 false) // If we failed, try again with the reversed curve
492 {
493 curve->Reverse();
494
495 opencascade::handle<Geom_BoundedCurve> bcurve =
496 opencascade::handle<Geom_BoundedCurve>::DownCast(curve);
497
498 check =
499 convert_bspline.Add(bcurve, tolerance, false, true, 0);
500 }
501 one_failed = one_failed || (check == false);
502 one_added = one_added || (check == true);
503 added[i] = check;
504 }
505 }
506
507 Assert(one_failed == false,
508 ExcMessage("Joining some of the Edges failed."));
509
510 opencascade::handle<Geom_Curve> bspline = convert_bspline.BSplineCurve();
511
512 out_shape = BRepBuilderAPI_MakeEdge(bspline);
513 return out_shape;
514 }
515
516 template <int dim>
518 line_intersection(const TopoDS_Shape &in_shape,
519 const Point<dim> &origin,
520 const Tensor<1, dim> &direction,
521 const double tolerance)
522 {
523 // translating original Point<dim> to gp point
524
525 gp_Pnt P0 = point(origin);
526 gp_Ax1 gpaxis(P0,
527 gp_Dir(direction[0],
528 dim > 1 ? direction[1] : 0,
529 dim > 2 ? direction[2] : 0));
530 gp_Lin line(gpaxis);
531
532 // destination point
533 gp_Pnt Pproj(0.0, 0.0, 0.0);
534
535 // we prepare now the surface for the projection we get the whole
536 // shape from the iges model
537 IntCurvesFace_ShapeIntersector Inters;
538 Inters.Load(in_shape, tolerance);
539
540 // Keep in mind: PerformNearest sounds pretty but DOESN'T WORK!!!
541 // The closest point must be found by hand
542 Inters.Perform(line, -RealLast(), +RealLast());
543 Assert(Inters.IsDone(), ExcMessage("Could not project point."));
544
545 double minDistance = 1e7;
546 Point<dim> result;
547 for (int i = 0; i < Inters.NbPnt(); ++i)
548 {
549 const double distance = point(origin).Distance(Inters.Pnt(i + 1));
550 // cout<<"Point "<<i<<": "<<point(Inters.Pnt(i+1))<<" distance:
551 // "<<distance<<endl;
552 if (distance < minDistance)
553 {
554 minDistance = distance;
555 result = point<dim>(Inters.Pnt(i + 1));
556 }
557 }
558
559 return result;
560 }
561
562 template <int dim>
563 TopoDS_Edge
564 interpolation_curve(std::vector<Point<dim>> &curve_points,
565 const Tensor<1, dim> &direction,
566 const bool closed,
567 const double tolerance)
568 {
569 unsigned int n_vertices = curve_points.size();
570
571 if (direction * direction > 0)
572 {
573 std::sort(curve_points.begin(),
574 curve_points.end(),
575 [&](const Point<dim> &p1, const Point<dim> &p2) {
576 return OpenCASCADE::point_compare(p1,
577 p2,
578 direction,
579 tolerance);
580 });
581 }
582
583 // set up array of vertices
584 opencascade::handle<TColgp_HArray1OfPnt> vertices =
585 new TColgp_HArray1OfPnt(1, n_vertices);
586
587
588 for (unsigned int vertex = 0; vertex < n_vertices; ++vertex)
589 {
590 vertices->SetValue(vertex + 1, point(curve_points[vertex]));
591 }
592
593 GeomAPI_Interpolate bspline_generator(vertices, closed, tolerance);
594 bspline_generator.Perform();
595 Assert((bspline_generator.IsDone()),
596 ExcMessage("Interpolated bspline generation failed"));
597
598 opencascade::handle<Geom_BSplineCurve> bspline = bspline_generator.Curve();
599 TopoDS_Edge out_shape = BRepBuilderAPI_MakeEdge(bspline);
600 out_shape.Closed(closed);
601 return out_shape;
602 }
603
604
605
606 template <int spacedim>
607 std::vector<TopoDS_Edge>
609 const Triangulation<2, spacedim> &triangulation,
610 const Mapping<2, spacedim> &mapping)
611
612 {
613 // store maps from global vertex index to pairs of global face indices
614 // and from global face index to pairs of global vertex indices
615 std::map<unsigned int, std::pair<unsigned int, unsigned int>> vert_to_faces;
616 std::map<unsigned int, std::pair<unsigned int, unsigned int>> face_to_verts;
617 std::map<unsigned int, bool> visited_faces;
618 std::map<unsigned int, Point<spacedim>> vert_to_point;
619
620 unsigned int face_index;
621
622 for (const auto &cell : triangulation.active_cell_iterators())
623 for (const unsigned int f : GeometryInfo<2>::face_indices())
624 if (cell->face(f)->at_boundary())
625 {
626 // get global face and vertex indices
627 face_index = cell->face(f)->index();
628 const unsigned int v0 = cell->face(f)->vertex_index(0);
629 const unsigned int v1 = cell->face(f)->vertex_index(1);
630 face_to_verts[face_index].first = v0;
631 face_to_verts[face_index].second = v1;
632 visited_faces[face_index] = false;
633
634 // extract mapped vertex locations
635 const auto verts = mapping.get_vertices(cell);
636 vert_to_point[v0] = verts[GeometryInfo<2>::face_to_cell_vertices(
637 f, 0, true, false, false)];
638 vert_to_point[v1] = verts[GeometryInfo<2>::face_to_cell_vertices(
639 f, 1, true, false, false)];
640
641 // distribute indices into maps
642 if (vert_to_faces.find(v0) == vert_to_faces.end())
643 {
644 vert_to_faces[v0].first = face_index;
645 }
646 else
647 {
648 vert_to_faces[v0].second = face_index;
649 }
650 if (vert_to_faces.find(v1) == vert_to_faces.end())
651 {
652 vert_to_faces[v1].first = face_index;
653 }
654 else
655 {
656 vert_to_faces[v1].second = face_index;
657 }
658 }
659
660 // run through maps in an orderly fashion, i.e., through the
661 // boundary in one cycle and add points to pointlist.
662 std::vector<TopoDS_Edge> interpolation_curves;
663 bool finished = (face_to_verts.empty());
664 face_index = finished ? 0 : face_to_verts.begin()->first;
665
666 while (finished == false)
667 {
668 const unsigned int start_point_index = face_to_verts[face_index].first;
669 unsigned int point_index = start_point_index;
670
671 // point_index and face_index always run together
672 std::vector<Point<spacedim>> pointlist;
673 do
674 {
675 visited_faces[face_index] = true;
676 auto current_point = vert_to_point[point_index];
677 pointlist.push_back(current_point);
678
679 // Get next point
680 if (face_to_verts[face_index].first != point_index)
681 point_index = face_to_verts[face_index].first;
682 else
683 point_index = face_to_verts[face_index].second;
684
685 // Get next face
686 if (vert_to_faces[point_index].first != face_index)
687 face_index = vert_to_faces[point_index].first;
688 else
689 face_index = vert_to_faces[point_index].second;
690 }
691 while (point_index != start_point_index);
692
693 interpolation_curves.push_back(
694 interpolation_curve(pointlist, Tensor<1, spacedim>(), true));
695
696 finished = true;
697 for (const auto &f : visited_faces)
698 if (f.second == false)
699 {
700 face_index = f.first;
701 finished = false;
702 break;
703 }
704 }
705 return interpolation_curves;
706 }
707
708
709 template <int dim>
710 std::tuple<Point<dim>, TopoDS_Shape, double, double>
711 project_point_and_pull_back(const TopoDS_Shape &in_shape,
712 const Point<dim> &origin,
713 const double tolerance)
714 {
715 TopExp_Explorer exp;
716 gp_Pnt Pproj = point(origin);
717
718 double minDistance = 1e7;
719 gp_Pnt tmp_proj(0.0, 0.0, 0.0);
720
721 unsigned int counter = 0;
722 unsigned int face_counter = 0;
723
724 TopoDS_Shape out_shape;
725 double u = 0;
726 double v = 0;
727
728 for (exp.Init(in_shape, TopAbs_FACE); exp.More(); exp.Next())
729 {
730 TopoDS_Face face = TopoDS::Face(exp.Current());
731
732 // the projection function needs a surface, so we obtain the
733 // surface upon which the face is defined
734 opencascade::handle<Geom_Surface> SurfToProj = BRep_Tool::Surface(face);
735 ShapeAnalysis_Surface projector(SurfToProj);
736 gp_Pnt2d proj_params = projector.ValueOfUV(point(origin), tolerance);
737
738 SurfToProj->D0(proj_params.X(), proj_params.Y(), tmp_proj);
739
740 double distance = point<dim>(tmp_proj).distance(origin);
741 if (distance < minDistance)
742 {
743 minDistance = distance;
744 Pproj = tmp_proj;
745 out_shape = face;
746 u = proj_params.X();
747 v = proj_params.Y();
748 ++counter;
749 }
750 ++face_counter;
751 }
752
753 // face counter tells us if the shape contained faces: if it does, there is
754 // no need to loop on edges. Even if the closest point lies on the boundary
755 // of a parametric surface, we need in fact to retain the face and both u
756 // and v, if we want to use this method to retrieve the surface normal
757 if (face_counter == 0)
758 for (exp.Init(in_shape, TopAbs_EDGE); exp.More(); exp.Next())
759 {
760 TopoDS_Edge edge = TopoDS::Edge(exp.Current());
761 if (!BRep_Tool::Degenerated(edge))
762 {
763 TopLoc_Location L;
764 Standard_Real First;
765 Standard_Real Last;
766
767 // the projection function needs a Curve, so we obtain the
768 // curve upon which the edge is defined
769 opencascade::handle<Geom_Curve> CurveToProj =
770 BRep_Tool::Curve(edge, L, First, Last);
771
772 GeomAPI_ProjectPointOnCurve Proj(point(origin), CurveToProj);
773 unsigned int num_proj_points = Proj.NbPoints();
774 if ((num_proj_points > 0) && (Proj.LowerDistance() < minDistance))
775 {
776 minDistance = Proj.LowerDistance();
777 Pproj = Proj.NearestPoint();
778 out_shape = edge;
779 u = Proj.LowerDistanceParameter();
780 ++counter;
781 }
782 }
783 }
784
785 Assert(counter > 0, ExcMessage("Could not find projection points."));
786 return std::tuple<Point<dim>, TopoDS_Shape, double, double>(
787 point<dim>(Pproj), out_shape, u, v);
788 }
789
790
791 template <int dim>
793 closest_point(const TopoDS_Shape &in_shape,
794 const Point<dim> &origin,
795 const double tolerance)
796 {
797 std::tuple<Point<dim>, TopoDS_Shape, double, double> ref =
798 project_point_and_pull_back(in_shape, origin, tolerance);
799 return std::get<0>(ref);
800 }
801
802 std::tuple<Point<3>, Tensor<1, 3>, double, double>
803 closest_point_and_differential_forms(const TopoDS_Shape &in_shape,
804 const Point<3> &origin,
805 const double tolerance)
806
807 {
808 std::tuple<Point<3>, TopoDS_Shape, double, double> shape_and_params =
809 project_point_and_pull_back(in_shape, origin, tolerance);
810
811 TopoDS_Shape &out_shape = std::get<1>(shape_and_params);
812 double &u = std::get<2>(shape_and_params);
813 double &v = std::get<3>(shape_and_params);
814
815 // just a check here: the number of faces in out_shape must be 1, otherwise
816 // something is wrong
817 std::tuple<unsigned int, unsigned int, unsigned int> numbers =
818 count_elements(out_shape);
819 (void)numbers;
820
821 Assert(
822 std::get<0>(numbers) > 0,
824 "Could not find normal: the shape containing the closest point has 0 faces."));
825 Assert(
826 std::get<0>(numbers) < 2,
828 "Could not find normal: the shape containing the closest point has more than 1 face."));
829
830
831 TopExp_Explorer exp;
832 exp.Init(out_shape, TopAbs_FACE);
833 TopoDS_Face face = TopoDS::Face(exp.Current());
834 return push_forward_and_differential_forms(face, u, v, tolerance);
835 }
836
837 template <int dim>
839 push_forward(const TopoDS_Shape &in_shape, const double u, const double v)
840 {
841 switch (in_shape.ShapeType())
842 {
843 case TopAbs_FACE:
844 {
845 BRepAdaptor_Surface surf(TopoDS::Face(in_shape));
846 return point<dim>(surf.Value(u, v));
847 }
848 case TopAbs_EDGE:
849 {
850 BRepAdaptor_Curve curve(TopoDS::Edge(in_shape));
851 return point<dim>(curve.Value(u));
852 }
853 default:
854 Assert(false, ExcUnsupportedShape());
855 }
856 return {};
857 }
858
859 std::tuple<Point<3>, Tensor<1, 3>, double, double>
860 push_forward_and_differential_forms(const TopoDS_Face &face,
861 const double u,
862 const double v,
863 const double /*tolerance*/)
864 {
865 opencascade::handle<Geom_Surface> SurfToProj = BRep_Tool::Surface(face);
866 GeomLProp_SLProps props(SurfToProj, u, v, 1, 1e-7);
867 gp_Pnt Value = props.Value();
868 Assert(props.IsNormalDefined(), ExcMessage("Normal is not well defined!"));
869 gp_Dir Normal = props.Normal();
870 Assert(props.IsCurvatureDefined(),
871 ExcMessage("Curvature is not well defined!"));
872 Standard_Real Min_Curvature = props.MinCurvature();
873 Standard_Real Max_Curvature = props.MaxCurvature();
874 Tensor<1, 3> normal = Point<3>(Normal.X(), Normal.Y(), Normal.Z());
875
876 // In the case your manifold changes from convex to concave or vice-versa
877 // the normal could jump from "inner" to "outer" normal.
878 // However, you should be able to change the normal sense preserving
879 // the manifold orientation:
880 if (face.Orientation() == TopAbs_REVERSED)
881 {
882 normal *= -1;
883 Min_Curvature *= -1;
884 Max_Curvature *= -1;
885 }
886
887 return std::tuple<Point<3>, Tensor<1, 3>, double, double>(point<3>(Value),
888 normal,
889 Min_Curvature,
890 Max_Curvature);
891 }
892
893
894
895 template <int spacedim>
896 void
897 create_triangulation(const TopoDS_Face &face,
899 {
900 BRepAdaptor_Surface surf(face);
901 const double u0 = surf.FirstUParameter();
902 const double u1 = surf.LastUParameter();
903 const double v0 = surf.FirstVParameter();
904 const double v1 = surf.LastVParameter();
905
906 std::vector<CellData<2>> cells;
907 std::vector<Point<spacedim>> vertices;
908 SubCellData t;
909
910 vertices.push_back(point<spacedim>(surf.Value(u0, v0)));
911 vertices.push_back(point<spacedim>(surf.Value(u1, v0)));
912 vertices.push_back(point<spacedim>(surf.Value(u0, v1)));
913 vertices.push_back(point<spacedim>(surf.Value(u1, v1)));
914
915 CellData<2> cell;
916 for (unsigned int i = 0; i < 4; ++i)
917 cell.vertices[i] = i;
918
919 cells.push_back(cell);
920 tria.create_triangulation(vertices, cells, t);
921 }
922
923// We don't build the .inst file if deal.II isn't configured
924// with GMSH, but doxygen doesn't know that and tries to find that
925// file anyway for parsing -- which then of course it fails on. So
926// exclude the following from doxygen consideration.
927# ifndef DOXYGEN
928# include "opencascade/utilities.inst"
929# endif
930
931} // namespace OpenCASCADE
932
933
934#endif
935
Abstract base class for mapping classes.
Definition mapping.h:318
virtual boost::container::small_vector< Point< spacedim >, ReferenceCells::max_n_vertices< dim >() > get_vertices(const typename Triangulation< dim, spacedim >::cell_iterator &cell) const
Definition point.h:111
numbers::NumberTraits< Number >::real_type norm() const
virtual void create_triangulation(const std::vector< Point< spacedim > > &vertices, const std::vector< CellData< dim > > &cells, const SubCellData &subcelldata)
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
Point< 2 > first
Definition grid_out.cc:4639
const unsigned int v0
const unsigned int v1
IteratorRange< active_cell_iterator > active_cell_iterators() const
static ::ExceptionBase & ExcNotImplemented()
#define Assert(cond, exc)
static ::ExceptionBase & ExcUnsupportedShape()
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
TopoDS_Edge interpolation_curve(std::vector< Point< dim > > &curve_points, const Tensor< 1, dim > &direction=Tensor< 1, dim >(), const bool closed=false, const double tolerance=1e-7)
Definition utilities.cc:564
std::tuple< Point< 3 >, Tensor< 1, 3 >, double, double > push_forward_and_differential_forms(const TopoDS_Face &face, const double u, const double v, const double tolerance=1e-7)
Definition utilities.cc:860
void extract_compound_shapes(const TopoDS_Shape &shape, std::vector< TopoDS_Compound > &compounds, std::vector< TopoDS_CompSolid > &compsolids, std::vector< TopoDS_Solid > &solids, std::vector< TopoDS_Shell > &shells, std::vector< TopoDS_Wire > &wires)
Definition utilities.cc:135
Point< dim > push_forward(const TopoDS_Shape &in_shape, const double u, const double v)
Definition utilities.cc:839
std::tuple< unsigned int, unsigned int, unsigned int > count_elements(const TopoDS_Shape &shape)
Definition utilities.cc:90
void write_STEP(const TopoDS_Shape &shape, const std::string &filename)
Definition utilities.cc:382
std::tuple< Point< 3 >, Tensor< 1, 3 >, double, double > closest_point_and_differential_forms(const TopoDS_Shape &in_shape, const Point< 3 > &origin, const double tolerance=1e-7)
Definition utilities.cc:803
void extract_geometrical_shapes(const TopoDS_Shape &shape, std::vector< TopoDS_Face > &faces, std::vector< TopoDS_Edge > &edges, std::vector< TopoDS_Vertex > &vertices)
Definition utilities.cc:109
TopoDS_Edge join_edges(const TopoDS_Shape &in_shape, const double tolerance=1e-7)
Definition utilities.cc:441
TopoDS_Shape read_STEP(const std::string &filename, const double scale_factor=1e-3)
Definition utilities.cc:353
bool point_compare(const Point< dim > &p1, const Point< dim > &p2, const Tensor< 1, dim > &direction=Tensor< 1, dim >(), const double tolerance=1e-10)
Definition utilities.cc:217
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
Definition utilities.cc:190
Point< dim > closest_point(const TopoDS_Shape &in_shape, const Point< dim > &origin, const double tolerance=1e-7)
Definition utilities.cc:793
std::tuple< Point< dim >, TopoDS_Shape, double, double > project_point_and_pull_back(const TopoDS_Shape &in_shape, const Point< dim > &origin, const double tolerance=1e-7)
Definition utilities.cc:711
Point< dim > line_intersection(const TopoDS_Shape &in_shape, const Point< dim > &origin, const Tensor< 1, dim > &direction, const double tolerance=1e-7)
Definition utilities.cc:518
void write_STL(const TopoDS_Shape &shape, const std::string &filename, const double deflection, const bool sew_different_faces=false, const double sewer_tolerance=1e-6, const bool is_relative=false, const double angular_deflection=0.5, const bool in_parallel=false)
Definition utilities.cc:292
void create_triangulation(const TopoDS_Face &face, Triangulation< 2, spacedim > &tria)
Definition utilities.cc:897
TopoDS_Shape read_STL(const std::string &filename)
Definition utilities.cc:282
TopoDS_Shape intersect_plane(const TopoDS_Shape &in_shape, const double c_x, const double c_y, const double c_z, const double c, const double tolerance=1e-7)
Definition utilities.cc:422
std::vector< TopoDS_Edge > create_curves_from_triangulation_boundary(const Triangulation< 2, spacedim > &triangulation, const Mapping< 2, spacedim > &mapping=StaticMappingQ1< 2, spacedim >::mapping)
Definition utilities.cc:608
double get_shape_tolerance(const TopoDS_Shape &shape)
Definition utilities.cc:398
void write_IGES(const TopoDS_Shape &shape, const std::string &filename)
Definition utilities.cc:269
TopoDS_Shape read_IGES(const std::string &filename, const double scale_factor=1e-3)
Definition utilities.cc:240
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > abs(const ::VectorizedArray< Number, width > &)
std_cxx26::inplace_vector< unsigned int, ReferenceCells::max_n_vertices< structdim >()> vertices
Definition cell_data.h:84
static unsigned int face_to_cell_vertices(const unsigned int face, const unsigned int vertex, const bool face_orientation=true, const bool face_flip=false, const bool face_rotation=false)
static std_cxx20::ranges::iota_view< unsigned int, unsigned int > face_indices()