07db4abeaf0338887741bb98a24607c020af78e3
[occt.git] / src / StdPrs / StdPrs_ToolTriangulatedShape.cxx
1 // Created on: 1993-10-27
2 // Created by: Jean-LOuis FRENKEL
3 // Copyright (c) 1993-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 #include <StdPrs_ToolTriangulatedShape.hxx>
18
19 #include <BRepMesh_DiscretFactory.hxx>
20 #include <BRepMesh_DiscretRoot.hxx>
21 #include <BRepTools.hxx>
22 #include <BRep_Tool.hxx>
23 #include <GeomAbs_SurfaceType.hxx>
24 #include <GeomLib.hxx>
25 #include <gp_XYZ.hxx>
26 #include <Poly.hxx>
27 #include <Poly_Connect.hxx>
28 #include <Poly_Triangulation.hxx>
29 #include <Precision.hxx>
30 #include <Prs3d.hxx>
31 #include <Prs3d_Drawer.hxx>
32 #include <TColgp_Array1OfPnt.hxx>
33 #include <TColgp_Array1OfPnt2d.hxx>
34 #include <TopAbs_Orientation.hxx>
35 #include <TopLoc_Location.hxx>
36 #include <TShort_HArray1OfShortReal.hxx>
37 #include <TShort_Array1OfShortReal.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopoDS.hxx>
40 #include <TopoDS_Face.hxx>
41
42 //=======================================================================
43 //function : IsTriangulated
44 //purpose  :
45 //=======================================================================
46 Standard_Boolean StdPrs_ToolTriangulatedShape::IsTriangulated (const TopoDS_Shape& theShape)
47 {
48   TopLoc_Location aLocDummy;
49   for (TopExp_Explorer aFaceIter (theShape, TopAbs_FACE); aFaceIter.More(); aFaceIter.Next())
50   {
51     const TopoDS_Face&                aFace = TopoDS::Face (aFaceIter.Current());
52     const Handle(Poly_Triangulation)& aTri  = BRep_Tool::Triangulation (aFace, aLocDummy);
53     if (aTri.IsNull())
54     {
55       return Standard_False;
56     }
57   }
58   return Standard_True;
59 }
60
61 //=======================================================================
62 //function : IsClosed
63 //purpose  :
64 //=======================================================================
65 Standard_Boolean StdPrs_ToolTriangulatedShape::IsClosed (const TopoDS_Shape& theShape)
66 {
67   if (theShape.IsNull())
68   {
69     return Standard_True;
70   }
71
72   switch (theShape.ShapeType())
73   {
74     case TopAbs_COMPOUND:
75     case TopAbs_COMPSOLID:
76     default:
77     {
78       // check that compound consists of closed solids
79       for (TopoDS_Iterator anIter (theShape); anIter.More(); anIter.Next())
80       {
81         const TopoDS_Shape& aShape = anIter.Value();
82         if (!IsClosed (aShape))
83         {
84           return Standard_False;
85         }
86       }
87       return Standard_True;
88     }
89     case TopAbs_SOLID:
90     {
91       // Check for non-manifold topology first of all:
92       // have to use BRep_Tool::IsClosed() because it checks the face connectivity
93       // inside the shape
94       if (!BRep_Tool::IsClosed (theShape))
95         return Standard_False;
96
97       for (TopoDS_Iterator anIter (theShape); anIter.More(); anIter.Next())
98       {
99         const TopoDS_Shape& aShape = anIter.Value();
100         if (aShape.IsNull())
101         {
102           continue;
103         }
104
105         if (aShape.ShapeType() == TopAbs_FACE)
106         {
107           // invalid solid
108           return Standard_False;
109         }
110         else if (!IsTriangulated (aShape))
111         {
112           // mesh contains holes
113           return Standard_False;
114         }
115       }
116       return Standard_True;
117     }
118     case TopAbs_SHELL:
119     case TopAbs_FACE:
120     {
121       // free faces / shell are not allowed
122       return Standard_False;
123     }
124     case TopAbs_WIRE:
125     case TopAbs_EDGE:
126     case TopAbs_VERTEX:
127     {
128       // ignore
129       return Standard_True;
130     }
131   }
132 }
133
134 //=======================================================================
135 //function : ComputeNormals
136 //purpose  :
137 //=======================================================================
138 void StdPrs_ToolTriangulatedShape::ComputeNormals (const TopoDS_Face& theFace,
139                                                    const Handle(Poly_Triangulation)& theTris,
140                                                    Poly_Connect& thePolyConnect)
141 {
142   if (theTris.IsNull()
143    || theTris->HasNormals())
144   {
145     return;
146   }
147
148   // take in face the surface location
149   const TopoDS_Face    aZeroFace = TopoDS::Face (theFace.Located (TopLoc_Location()));
150   Handle(Geom_Surface) aSurf     = BRep_Tool::Surface (aZeroFace);
151   const Poly_Array1OfTriangle& aTriangles = theTris->Triangles();
152   if (!theTris->HasUVNodes() || aSurf.IsNull())
153   {
154     // compute normals by averaging triangulation normals sharing the same vertex
155     Poly::ComputeNormals (theTris);
156     return;
157   }
158
159   const Standard_Real aTol = Precision::Confusion();
160   Handle(TShort_HArray1OfShortReal) aNormals = new TShort_HArray1OfShortReal (1, theTris->NbNodes() * 3);
161   const TColgp_Array1OfPnt2d& aNodesUV = theTris->UVNodes();
162   Standard_Integer aTri[3];
163   const TColgp_Array1OfPnt& aNodes = theTris->Nodes();
164   gp_Dir aNorm;
165   for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
166   {
167     // try to retrieve normal from real surface first, when UV coordinates are available
168     if (GeomLib::NormEstim (aSurf, aNodesUV.Value (aNodeIter), aTol, aNorm) > 1)
169     {
170       if (thePolyConnect.Triangulation() != theTris)
171       {
172         thePolyConnect.Load (theTris);
173       }
174
175       // compute flat normals
176       gp_XYZ eqPlan (0.0, 0.0, 0.0);
177       for (thePolyConnect.Initialize (aNodeIter); thePolyConnect.More(); thePolyConnect.Next())
178       {
179         aTriangles (thePolyConnect.Value()).Get (aTri[0], aTri[1], aTri[2]);
180         const gp_XYZ v1 (aNodes (aTri[1]).Coord() - aNodes (aTri[0]).Coord());
181         const gp_XYZ v2 (aNodes (aTri[2]).Coord() - aNodes (aTri[1]).Coord());
182         const gp_XYZ vv = v1 ^ v2;
183         const Standard_Real aMod = vv.Modulus();
184         if (aMod >= aTol)
185         {
186           eqPlan += vv / aMod;
187         }
188       }
189       const Standard_Real aModMax = eqPlan.Modulus();
190       aNorm = (aModMax > aTol) ? gp_Dir (eqPlan) : gp::DZ();
191     }
192
193     const Standard_Integer anId = (aNodeIter - aNodes.Lower()) * 3;
194     aNormals->SetValue (anId + 1, (Standard_ShortReal )aNorm.X());
195     aNormals->SetValue (anId + 2, (Standard_ShortReal )aNorm.Y());
196     aNormals->SetValue (anId + 3, (Standard_ShortReal )aNorm.Z());
197   }
198   theTris->SetNormals (aNormals);
199 }
200
201 //=======================================================================
202 //function : Normal
203 //purpose  :
204 //=======================================================================
205 void StdPrs_ToolTriangulatedShape::Normal (const TopoDS_Face&  theFace,
206                                            Poly_Connect&       thePolyConnect,
207                                            TColgp_Array1OfDir& theNormals)
208 {
209   const Handle(Poly_Triangulation)& aPolyTri = thePolyConnect.Triangulation();
210   if (!aPolyTri->HasNormals())
211   {
212     ComputeNormals (theFace, aPolyTri, thePolyConnect);
213   }
214
215   const TColgp_Array1OfPnt&       aNodes   = aPolyTri->Nodes();
216   const TShort_Array1OfShortReal& aNormals = aPolyTri->Normals();
217   const Standard_ShortReal*       aNormArr = &aNormals.First();
218   for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
219   {
220     const Standard_Integer anId = 3 * (aNodeIter - aNodes.Lower());
221     const gp_Dir aNorm (aNormArr[anId + 0],
222                         aNormArr[anId + 1],
223                         aNormArr[anId + 2]);
224     theNormals (aNodeIter) = aNorm;
225   }
226
227   if (theFace.Orientation() == TopAbs_REVERSED)
228   {
229     for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
230     {
231       theNormals.ChangeValue (aNodeIter).Reverse();
232     }
233   }
234 }
235
236 //=======================================================================
237 //function : IsTessellated
238 //purpose  :
239 //=======================================================================
240 Standard_Boolean StdPrs_ToolTriangulatedShape::IsTessellated (const TopoDS_Shape&         theShape,
241                                                               const Handle(Prs3d_Drawer)& theDrawer)
242 {
243   return BRepTools::Triangulation (theShape, Prs3d::GetDeflection (theShape, theDrawer), true);
244 }
245
246 // =======================================================================
247 // function : Tessellate
248 // purpose  :
249 // =======================================================================
250 Standard_Boolean StdPrs_ToolTriangulatedShape::Tessellate (const TopoDS_Shape&         theShape,
251                                                            const Handle(Prs3d_Drawer)& theDrawer)
252 {
253   Standard_Boolean wasRecomputed = Standard_False;
254   // Check if it is possible to avoid unnecessary recomputation of shape triangulation
255   if (IsTessellated (theShape, theDrawer))
256   {
257     return wasRecomputed;
258   }
259
260   Standard_Real aDeflection = Prs3d::GetDeflection (theShape, theDrawer);
261
262   // retrieve meshing tool from Factory
263   Handle(BRepMesh_DiscretRoot) aMeshAlgo = BRepMesh_DiscretFactory::Get().Discret (theShape,
264                                                                                    aDeflection,
265                                                                                    theDrawer->HLRAngle());
266   if (!aMeshAlgo.IsNull())
267   {
268     aMeshAlgo->Perform();
269     wasRecomputed = Standard_True;
270   }
271
272   return wasRecomputed;
273 }
274
275 // =======================================================================
276 // function : ClearOnOwnDeflectionChange
277 // purpose  :
278 // =======================================================================
279 void StdPrs_ToolTriangulatedShape::ClearOnOwnDeflectionChange (const TopoDS_Shape&         theShape,
280                                                                const Handle(Prs3d_Drawer)& theDrawer,
281                                                                const Standard_Boolean      theToResetCoeff)
282 {
283   if (!theDrawer->IsAutoTriangulation()
284     || theShape.IsNull())
285   {
286     return;
287   }
288
289   const Standard_Boolean isOwnDeviationAngle       = theDrawer->HasOwnDeviationAngle();
290   const Standard_Boolean isOwnDeviationCoefficient = theDrawer->HasOwnDeviationCoefficient();
291   const Standard_Real anAngleNew  = theDrawer->DeviationAngle();
292   const Standard_Real anAnglePrev = theDrawer->PreviousDeviationAngle();
293   const Standard_Real aCoeffNew   = theDrawer->DeviationCoefficient();
294   const Standard_Real aCoeffPrev  = theDrawer->PreviousDeviationCoefficient();
295   if ((!isOwnDeviationAngle       || Abs (anAngleNew - anAnglePrev) <= Precision::Angular())
296    && (!isOwnDeviationCoefficient || Abs (aCoeffNew  - aCoeffPrev)  <= Precision::Confusion()))
297   {
298     return;
299   }
300
301   BRepTools::Clean (theShape);
302   if (theToResetCoeff)
303   {
304     theDrawer->UpdatePreviousDeviationAngle();
305     theDrawer->UpdatePreviousDeviationCoefficient();
306   }
307 }