084b1ad1072096c95703dad71e27d080f03a0d5d
[occt.git] / src / StdPrs / StdPrs_ShadedShape.cxx
1 // Created on: 1993-09-23
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_ShadedShape.hxx>
18
19 #include <Bnd_Box.hxx>
20 #include <BRep_Builder.hxx>
21 #include <BRepBndLib.hxx>
22 #include <BRepMesh_DiscretFactory.hxx>
23 #include <BRepMesh_DiscretRoot.hxx>
24 #include <BRepTools.hxx>
25 #include <Graphic3d_ArrayOfSegments.hxx>
26 #include <Graphic3d_ArrayOfTriangles.hxx>
27 #include <Graphic3d_AspectFillArea3d.hxx>
28 #include <Graphic3d_Group.hxx>
29 #include <gp_Dir.hxx>
30 #include <gp_Vec.hxx>
31 #include <gp_Pnt.hxx>
32 #include <NCollection_List.hxx>
33 #include <Precision.hxx>
34 #include <Prs3d.hxx>
35 #include <Prs3d_Drawer.hxx>
36 #include <Prs3d_LineAspect.hxx>
37 #include <Prs3d_Presentation.hxx>
38 #include <Prs3d_ShadingAspect.hxx>
39 #include <Poly_Connect.hxx>
40 #include <Poly_PolygonOnTriangulation.hxx>
41 #include <Poly_Triangulation.hxx>
42 #include <StdPrs_ToolShadedShape.hxx>
43 #include <StdPrs_WFShape.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopoDS.hxx>
47 #include <TopoDS_Compound.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Shape.hxx>
50 #include <TColgp_Array1OfDir.hxx>
51 #include <TColgp_Array1OfPnt2d.hxx>
52 #include <TColgp_HArray1OfPnt.hxx>
53 #include <TopTools_ListOfShape.hxx>
54 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
55
56 namespace
57 {
58
59   //! Computes wireframe presentation for free wires and vertices
60   void wireframeFromShape (const Handle (Prs3d_Presentation)& thePrs,
61                            const TopoDS_Shape&                theShape,
62                            const Handle (Prs3d_Drawer)&       theDrawer)
63   {
64     if (theShape.ShapeType() != TopAbs_COMPOUND)
65     {
66       return;
67     }
68
69     TopExp_Explorer aShapeIter (theShape, TopAbs_FACE);
70     if (!aShapeIter.More())
71     {
72       // compound contains no shaded elements at all
73       StdPrs_WFShape::Add (thePrs, theShape, theDrawer);
74       return;
75     }
76
77     TopoDS_Compound aCompoundWF;
78     BRep_Builder aBuilder;
79     aBuilder.MakeCompound (aCompoundWF);
80     Standard_Boolean hasElement = Standard_False;
81
82     // isolated edges
83     for (aShapeIter.Init (theShape, TopAbs_EDGE, TopAbs_FACE); aShapeIter.More(); aShapeIter.Next())
84     {
85       hasElement = Standard_True;
86       aBuilder.Add (aCompoundWF, aShapeIter.Current());
87     }
88     // isolated vertices
89     for (aShapeIter.Init (theShape, TopAbs_VERTEX, TopAbs_EDGE); aShapeIter.More(); aShapeIter.Next())
90     {
91       hasElement = Standard_True;
92       aBuilder.Add (aCompoundWF, aShapeIter.Current());
93     }
94     if (hasElement)
95     {
96       StdPrs_WFShape::Add (thePrs, aCompoundWF, theDrawer);
97     }
98   }
99
100   //! Gets triangulation of every face of shape and fills output array of triangles
101   static Handle(Graphic3d_ArrayOfTriangles) fillTriangles (const TopoDS_Shape&    theShape,
102                                                            const Standard_Boolean theHasTexels,
103                                                            const gp_Pnt2d&        theUVOrigin,
104                                                            const gp_Pnt2d&        theUVRepeat,
105                                                            const gp_Pnt2d&        theUVScale)
106   {
107     Handle(Poly_Triangulation) aT;
108     TopLoc_Location aLoc;
109     gp_Pnt aPoint;
110     Standard_Integer aNbTriangles = 0;
111     Standard_Integer aNbVertices  = 0;
112
113     // Precision for compare square distances
114     const Standard_Real aPreci = Precision::SquareConfusion();
115
116     TopExp_Explorer aFaceIt(theShape, TopAbs_FACE);
117     for (; aFaceIt.More(); aFaceIt.Next())
118     {
119       const TopoDS_Face& aFace = TopoDS::Face(aFaceIt.Current());
120       aT = StdPrs_ToolShadedShape::Triangulation (aFace, aLoc);
121       if (!aT.IsNull())
122       {
123         aNbTriangles += aT->NbTriangles();
124         aNbVertices  += aT->NbNodes();
125       }
126     }
127     if (aNbVertices  <  3 || aNbTriangles <= 0)
128     {
129       return Handle(Graphic3d_ArrayOfTriangles)();
130     }
131
132     Handle(Graphic3d_ArrayOfTriangles) anArray = new Graphic3d_ArrayOfTriangles (aNbVertices, 3 * aNbTriangles,
133                                                                                  Standard_True, Standard_False, theHasTexels);
134     Standard_Real aUmin (0.0), aUmax (0.0), aVmin (0.0), aVmax (0.0), dUmax (0.0), dVmax (0.0);
135     for (aFaceIt.Init (theShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
136     {
137       const TopoDS_Face& aFace = TopoDS::Face(aFaceIt.Current());
138       aT = StdPrs_ToolShadedShape::Triangulation (aFace, aLoc);
139       if (aT.IsNull())
140       {
141         continue;
142       }
143       const gp_Trsf& aTrsf = aLoc.Transformation();
144       Poly_Connect aPolyConnect (aT);
145       // Extracts vertices & normals from nodes
146       const TColgp_Array1OfPnt&   aNodes   = aT->Nodes();
147       const TColgp_Array1OfPnt2d& aUVNodes = aT->UVNodes();
148       TColgp_Array1OfDir aNormals (aNodes.Lower(), aNodes.Upper());
149       StdPrs_ToolShadedShape::Normal (aFace, aPolyConnect, aNormals);
150
151       if (theHasTexels)
152       {
153         BRepTools::UVBounds (aFace, aUmin, aUmax, aVmin, aVmax);
154         dUmax = (aUmax - aUmin);
155         dVmax = (aVmax - aVmin);
156       }
157
158       const Standard_Integer aDecal = anArray->VertexNumber();
159       for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
160       {
161         aPoint = aNodes (aNodeIter);
162         if (!aLoc.IsIdentity())
163         {
164           aPoint.Transform (aTrsf);
165           aNormals (aNodeIter).Transform (aTrsf);
166         }
167
168         if (theHasTexels && aUVNodes.Upper() == aNodes.Upper())
169         {
170           const gp_Pnt2d aTexel = gp_Pnt2d ((-theUVOrigin.X() + (theUVRepeat.X() * (aUVNodes (aNodeIter).X() - aUmin)) / dUmax) / theUVScale.X(),
171                                             (-theUVOrigin.Y() + (theUVRepeat.Y() * (aUVNodes (aNodeIter).Y() - aVmin)) / dVmax) / theUVScale.Y());
172           anArray->AddVertex (aPoint, aNormals (aNodeIter), aTexel);
173         }
174         else
175         {
176           anArray->AddVertex (aPoint, aNormals (aNodeIter));
177         }
178       }
179
180       // Fill array with vertex and edge visibility info
181       const Poly_Array1OfTriangle& aTriangles = aT->Triangles();
182       Standard_Integer anIndex[3];
183       for (Standard_Integer aTriIter = 1; aTriIter <= aT->NbTriangles(); ++aTriIter)
184       {
185         if (aFace.Orientation() == TopAbs_REVERSED)
186         {
187           aTriangles (aTriIter).Get (anIndex[0], anIndex[2], anIndex[1]);
188         }
189         else
190         {
191           aTriangles (aTriIter).Get (anIndex[0], anIndex[1], anIndex[2]);
192         }
193
194         gp_Pnt aP1 = aNodes (anIndex[0]);
195         gp_Pnt aP2 = aNodes (anIndex[1]);
196         gp_Pnt aP3 = aNodes (anIndex[2]);
197
198         gp_Vec aV1 (aP1, aP2);
199         if (aV1.SquareMagnitude() <= aPreci)
200         {
201           continue;
202         }
203         gp_Vec aV2 (aP2, aP3);
204         if (aV2.SquareMagnitude() <= aPreci)
205         {
206           continue;
207         }
208         gp_Vec aV3 (aP3, aP1);
209         if (aV3.SquareMagnitude() <= aPreci)
210         {
211           continue;
212         }
213         aV1.Normalize();
214         aV2.Normalize();
215         aV1.Cross (aV2);
216         if (aV1.SquareMagnitude() > aPreci)
217         {
218           anArray->AddEdge (anIndex[0] + aDecal);
219           anArray->AddEdge (anIndex[1] + aDecal);
220           anArray->AddEdge (anIndex[2] + aDecal);
221         }
222       }
223     }
224     return anArray;
225   }
226
227   //! Searches closed and unclosed subshapes in shape structure
228   //! and puts them into two compounds for separate processing of closed and unclosed sub-shapes.
229   static void exploreSolids (const TopoDS_Shape& theShape,
230                              const BRep_Builder& theBuilder,
231                              TopoDS_Compound&    theCompoundForClosed,
232                              TopoDS_Compound&    theCompoundForOpened)
233   {
234     if (theShape.IsNull())
235     {
236       return;
237     }
238
239     switch (theShape.ShapeType())
240     {
241       case TopAbs_COMPOUND:
242       case TopAbs_COMPSOLID:
243       {
244         for (TopoDS_Iterator anIter (theShape); anIter.More(); anIter.Next())
245         {
246           exploreSolids (anIter.Value(), theBuilder, theCompoundForClosed, theCompoundForOpened);
247         }
248         return;
249       }
250       case TopAbs_SOLID:
251       {
252         theBuilder.Add (StdPrs_ToolShadedShape::IsClosed (theShape) ? theCompoundForClosed : theCompoundForOpened, theShape);
253         return;
254       }
255       case TopAbs_SHELL:
256       case TopAbs_FACE:
257       {
258         theBuilder.Add (theCompoundForOpened, theShape);
259         return;
260       }
261       case TopAbs_WIRE:
262       case TopAbs_EDGE:
263       case TopAbs_VERTEX:
264       case TopAbs_SHAPE:
265       default:
266         return;
267     }
268   }
269
270   //! Prepare shaded presentation for specified shape
271   static Standard_Boolean shadeFromShape (const TopoDS_Shape&               theShape,
272                                           const Handle(Prs3d_Presentation)& thePrs,
273                                           const Handle(Prs3d_Drawer)&       theDrawer,
274                                           const Standard_Boolean            theHasTexels,
275                                           const gp_Pnt2d&                   theUVOrigin,
276                                           const gp_Pnt2d&                   theUVRepeat,
277                                           const gp_Pnt2d&                   theUVScale,
278                                           const Standard_Boolean            theIsClosed)
279   {
280     Handle(Graphic3d_ArrayOfTriangles) aPArray = fillTriangles (theShape, theHasTexels, theUVOrigin, theUVRepeat, theUVScale);
281     if (aPArray.IsNull())
282     {
283       return Standard_False;
284     }
285
286     Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup (thePrs);
287     aGroup->SetClosed (theIsClosed);
288     if (!theDrawer->ShadingAspectGlobal())
289     {
290       Handle(Graphic3d_AspectFillArea3d) anAsp = theDrawer->ShadingAspect()->Aspect();
291       theIsClosed ? anAsp->SuppressBackFace() : anAsp->AllowBackFace();
292       aGroup->SetGroupPrimitivesAspect (anAsp);
293     }
294     aGroup->AddPrimitiveArray (aPArray);
295     return Standard_True;
296   }
297
298   //! Compute boundary presentation for faces of the shape.
299   static void computeFaceBoundaries (const TopoDS_Shape&               theShape,
300                                      const Handle(Prs3d_Presentation)& thePrs,
301                                      const Handle(Prs3d_Drawer)&       theDrawer)
302   {
303     // collection of all triangulation nodes on edges
304     // for computing boundaries presentation
305     NCollection_List<Handle(TColgp_HArray1OfPnt)> aNodeCollection;
306     Standard_Integer aNodeNumber = 0;
307
308     TopLoc_Location aTrsf;
309
310     // explore all boundary edges
311     TopTools_IndexedDataMapOfShapeListOfShape anEdgesMap;
312     TopExp::MapShapesAndAncestors (
313       theShape, TopAbs_EDGE, TopAbs_FACE, anEdgesMap);
314
315     Standard_Integer anEdgeIdx = 1;
316     for ( ; anEdgeIdx <= anEdgesMap.Extent (); anEdgeIdx++)
317     {
318       // reject free edges
319       const TopTools_ListOfShape& aFaceList = anEdgesMap.FindFromIndex (anEdgeIdx);
320       if (aFaceList.Extent() == 0)
321         continue;
322
323       // take one of the shared edges and get edge triangulation
324       const TopoDS_Face& aFace  = TopoDS::Face (aFaceList.First ());
325       const TopoDS_Edge& anEdge = TopoDS::Edge (anEdgesMap.FindKey (anEdgeIdx));
326
327       Handle(Poly_Triangulation) aTriangulation =
328         BRep_Tool::Triangulation (aFace, aTrsf);
329
330       if (aTriangulation.IsNull ())
331         continue;
332
333       Handle(Poly_PolygonOnTriangulation) anEdgePoly =
334         BRep_Tool::PolygonOnTriangulation (anEdge, aTriangulation, aTrsf);
335
336       if (anEdgePoly.IsNull ())
337         continue;
338
339       // get edge nodes indexes from face triangulation
340       const TColgp_Array1OfPnt& aTriNodes = aTriangulation->Nodes ();
341       const TColStd_Array1OfInteger& anEdgeNodes = anEdgePoly->Nodes ();
342
343       if (anEdgeNodes.Length () < 2)
344         continue;
345
346       // collect the edge nodes
347       Handle(TColgp_HArray1OfPnt) aCollected =
348         new TColgp_HArray1OfPnt (anEdgeNodes.Lower (), anEdgeNodes.Upper ());
349
350       Standard_Integer aNodeIdx = anEdgeNodes.Lower ();
351       for ( ; aNodeIdx <= anEdgeNodes.Upper (); aNodeIdx++)
352       {
353         // node index in face triangulation
354         Standard_Integer aTriIndex = anEdgeNodes.Value (aNodeIdx);
355
356         // get node and apply location transformation to the node
357         gp_Pnt aTriNode = aTriNodes.Value (aTriIndex);
358         if (!aTrsf.IsIdentity ())
359           aTriNode.Transform (aTrsf);
360
361         // add node to the boundary array
362         aCollected->SetValue (aNodeIdx, aTriNode);
363       }
364
365       aNodeNumber += anEdgeNodes.Length ();
366       aNodeCollection.Append (aCollected);
367     }
368
369     // check if it possible to continue building the presentation
370     if (aNodeNumber == 0)
371       return;
372
373     // allocate polyline array for presentation
374     Standard_Integer aSegmentEdgeNb = 
375       (aNodeNumber - aNodeCollection.Extent()) * 2;
376
377     Handle(Graphic3d_ArrayOfSegments) aSegments = 
378       new Graphic3d_ArrayOfSegments (aNodeNumber, aSegmentEdgeNb);
379
380     // build presentation for edge bondaries
381     NCollection_List<Handle(TColgp_HArray1OfPnt)>::Iterator 
382       aCollIt (aNodeCollection);
383
384     // the edge index is increased in each iteration step to
385     // avoid contiguous segments between different face edges.
386     for ( ; aCollIt.More(); aCollIt.Next () )
387     {
388       const Handle(TColgp_HArray1OfPnt)& aNodeArray = aCollIt.Value ();
389
390       Standard_Integer aNodeIdx = aNodeArray->Lower ();
391
392       // add first node (this node is not shared with previous segment).
393       // for each face edge, indices for sharing nodes 
394       // between segments begin from the first added node.
395       Standard_Integer aSegmentEdge = 
396         aSegments->AddVertex (aNodeArray->Value (aNodeIdx));
397
398       // add subsequent nodes and provide edge indexes for sharing
399       // the nodes between the sequential segments.
400       for ( aNodeIdx++; aNodeIdx <= aNodeArray->Upper (); aNodeIdx++ )
401       {
402         aSegments->AddVertex (aNodeArray->Value (aNodeIdx));
403         aSegments->AddEdge (  aSegmentEdge);
404         aSegments->AddEdge (++aSegmentEdge);
405       }
406     }
407
408     // set up aspect and add polyline data
409     Handle(Graphic3d_AspectLine3d) aBoundaryAspect = 
410       theDrawer->FaceBoundaryAspect ()->Aspect ();
411
412     Handle(Graphic3d_Group) aPrsGrp = Prs3d_Root::CurrentGroup (thePrs);
413     aPrsGrp->SetGroupPrimitivesAspect (aBoundaryAspect);
414     aPrsGrp->AddPrimitiveArray (aSegments);
415   }
416 };
417
418 // =======================================================================
419 // function : Add
420 // purpose  :
421 // =======================================================================
422 void StdPrs_ShadedShape::Add (const Handle(Prs3d_Presentation)& thePrs,
423                               const TopoDS_Shape&               theShape,
424                               const Handle(Prs3d_Drawer)&       theDrawer,
425                               const Standard_Boolean            theToExploreSolids)
426 {
427   gp_Pnt2d aDummy;
428   StdPrs_ShadedShape::Add (thePrs, theShape, theDrawer,
429                            Standard_False, aDummy, aDummy, aDummy, theToExploreSolids);
430 }
431
432 // =======================================================================
433 // function : Tessellate
434 // purpose  :
435 // =======================================================================
436 void StdPrs_ShadedShape::Tessellate (const TopoDS_Shape&          theShape,
437                                      const Handle (Prs3d_Drawer)& theDrawer)
438 {
439   // Check if it is possible to avoid unnecessary recomputation of shape triangulation
440   Standard_Real aDeflection = Prs3d::GetDeflection (theShape, theDrawer);
441   if (BRepTools::Triangulation (theShape, aDeflection))
442   {
443     return;
444   }
445
446   // retrieve meshing tool from Factory
447   BRepTools::Clean (theShape);
448   Handle(BRepMesh_DiscretRoot) aMeshAlgo = BRepMesh_DiscretFactory::Get().Discret (theShape,
449                                                                                    aDeflection,
450                                                                                    theDrawer->HLRAngle());
451   if (!aMeshAlgo.IsNull())
452   {
453     aMeshAlgo->Perform();
454   }
455 }
456
457 // =======================================================================
458 // function : Add
459 // purpose  :
460 // =======================================================================
461 void StdPrs_ShadedShape::Add (const Handle (Prs3d_Presentation)& thePrs,
462                               const TopoDS_Shape&                theShape,
463                               const Handle (Prs3d_Drawer)&       theDrawer,
464                               const Standard_Boolean             theHasTexels,
465                               const gp_Pnt2d&                    theUVOrigin,
466                               const gp_Pnt2d&                    theUVRepeat,
467                               const gp_Pnt2d&                    theUVScale,
468                               const Standard_Boolean             theToExploreSolids)
469 {
470   if (theShape.IsNull())
471   {
472     return;
473   }
474
475   // add wireframe presentation for isolated edges and vertices
476   wireframeFromShape (thePrs, theShape, theDrawer);
477
478   // IsClosed also verifies triangulation completeness - perform tessellation beforehand
479   Tessellate (theShape, theDrawer);
480   const Standard_Boolean isClosed = StdPrs_ToolShadedShape::IsClosed (theShape);
481   if ((theShape.ShapeType() == TopAbs_COMPOUND
482     || theShape.ShapeType() == TopAbs_COMPSOLID)
483    && !isClosed
484    &&  theToExploreSolids)
485   {
486     // collect two compounds: for opened and closed (solid) sub-shapes
487     TopoDS_Compound anOpened, aClosed;
488     BRep_Builder aBuilder;
489     aBuilder.MakeCompound (aClosed);
490     aBuilder.MakeCompound (anOpened);
491     exploreSolids (theShape, aBuilder, aClosed, anOpened);
492
493     TopoDS_Iterator aShapeIter (aClosed);
494     if (aShapeIter.More())
495     {
496       shadeFromShape (aClosed, thePrs, theDrawer,
497                       theHasTexels, theUVOrigin, theUVRepeat, theUVScale, Standard_True);
498     }
499
500     aShapeIter.Initialize (anOpened);
501     if (aShapeIter.More())
502     {
503       shadeFromShape (anOpened, thePrs, theDrawer,
504                       theHasTexels, theUVOrigin, theUVRepeat, theUVScale, Standard_False);
505     }
506   }
507   else
508   {
509     shadeFromShape (theShape, thePrs, theDrawer,
510                     theHasTexels, theUVOrigin, theUVRepeat, theUVScale, isClosed);
511   }
512
513   if (theDrawer->IsFaceBoundaryDraw())
514   {
515     computeFaceBoundaries (theShape, thePrs, theDrawer);
516   }
517 }