0029729: Visualization, Graphic3d_ClipPlane - add support of clipping plane chains
[occt.git] / src / SelectMgr / SelectMgr_ViewerSelector.cxx
1 // Created on: 1995-02-15
2 // Created by: Roberc Coublanc
3 // Copyright (c) 1995-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 <SelectMgr_ViewerSelector.hxx>
18
19 #include <BVH_Tree.hxx>
20 #include <gp_GTrsf.hxx>
21 #include <gp_Pnt.hxx>
22 #include <OSD_Environment.hxx>
23 #include <Precision.hxx>
24 #include <SelectBasics_EntityOwner.hxx>
25 #include <SelectBasics_SensitiveEntity.hxx>
26 #include <SelectBasics_PickResult.hxx>
27 #include <SelectMgr_EntityOwner.hxx>
28 #include <SelectMgr_SortCriterion.hxx>
29 #include <SelectMgr_SensitiveEntitySet.hxx>
30 #include <TColStd_Array1OfInteger.hxx>
31 #include <TCollection_AsciiString.hxx>
32 #include <TColStd_HArray1OfInteger.hxx>
33 #include <TColStd_ListOfInteger.hxx>
34
35 #include <algorithm>
36
37 IMPLEMENT_STANDARD_RTTIEXT(SelectMgr_ViewerSelector, Standard_Transient)
38
39 namespace {
40   // Comparison operator for sorting selection results
41   class CompareResults
42   {
43   public:
44    
45     CompareResults (const SelectMgr_IndexedDataMapOfOwnerCriterion& aMapOfCriterion)
46       : myMapOfCriterion (aMapOfCriterion)
47     {
48     }
49
50     Standard_Boolean operator() (Standard_Integer theLeft, Standard_Integer theRight) const
51     {
52       return myMapOfCriterion.FindFromIndex(theLeft) > myMapOfCriterion.FindFromIndex(theRight);
53     }
54
55   private:
56     void operator = (const CompareResults&);
57
58   private:
59     const SelectMgr_IndexedDataMapOfOwnerCriterion&  myMapOfCriterion;
60   };
61
62   static const Graphic3d_Mat4d SelectMgr_ViewerSelector_THE_IDENTITY_MAT;
63 }
64
65 //=======================================================================
66 // function : updatePoint3d
67 // purpose  :
68 //=======================================================================
69 void SelectMgr_ViewerSelector::updatePoint3d (SelectMgr_SortCriterion& theCriterion,
70                                               const Handle(SelectBasics_SensitiveEntity)& theEntity,
71                                               const gp_GTrsf& theInversedTrsf,
72                                               const SelectMgr_SelectingVolumeManager& theMgr) const
73 {
74   if (theMgr.GetActiveSelectionType() != SelectMgr_SelectingVolumeManager::Point)
75   {
76     return;
77   }
78
79   theCriterion.Point = theMgr.DetectedPoint (theCriterion.Depth);
80   gp_GTrsf anInvTrsf = theInversedTrsf;
81   if (theCriterion.Entity->HasInitLocation())
82   {
83     anInvTrsf = theCriterion.Entity->InvInitLocation() * anInvTrsf;
84   }
85   if (anInvTrsf.Form() != gp_Identity)
86   {
87     anInvTrsf.Inverted().Transforms (theCriterion.Point.ChangeCoord());
88   }
89
90   if (mySelectingVolumeMgr.Camera().IsNull())
91   {
92     theCriterion.Tolerance = theEntity->SensitivityFactor() / 33.0;
93   }
94   else if (mySelectingVolumeMgr.Camera()->IsOrthographic())
95   {
96     theCriterion.Tolerance = myCameraScale * theEntity->SensitivityFactor();
97   }
98   else
99   {
100     const Standard_Real aDistFromEye = (theCriterion.Point.XYZ() - myCameraEye.XYZ()).Dot (myCameraDir.XYZ());
101     theCriterion.Tolerance = aDistFromEye * myCameraScale * theEntity->SensitivityFactor();
102   }
103 }
104
105 //==================================================
106 // Function: Initialize
107 // Purpose :
108 //==================================================
109 SelectMgr_ViewerSelector::SelectMgr_ViewerSelector():
110 preferclosest(Standard_True),
111 myToUpdateTolerance (Standard_True),
112 myCameraScale (1.0),
113 myCurRank (0),
114 myIsLeftChildQueuedFirst (Standard_False),
115 myEntityIdx (0)
116 {
117   myEntitySetBuilder = new BVH_BinnedBuilder<Standard_Real, 3, 4> (BVH_Constants_LeafNodeSizeSingle, BVH_Constants_MaxTreeDepth, Standard_True);
118 }
119
120 //==================================================
121 // Function: Activate
122 // Purpose :
123 //==================================================
124 void SelectMgr_ViewerSelector::Activate (const Handle(SelectMgr_Selection)& theSelection)
125 {
126   for (NCollection_Vector<Handle(SelectMgr_SensitiveEntity)>::Iterator aSelEntIter (theSelection->Entities()); aSelEntIter.More(); aSelEntIter.Next())
127   {
128     aSelEntIter.Value()->SetActiveForSelection();
129   }
130
131   theSelection->SetSelectionState (SelectMgr_SOS_Activated);
132
133   myTolerances.Add (theSelection->Sensitivity());
134   myToUpdateTolerance = Standard_True;
135 }
136
137 //==================================================
138 // Function: Deactivate
139 // Purpose :
140 //==================================================
141 void SelectMgr_ViewerSelector::Deactivate (const Handle(SelectMgr_Selection)& theSelection)
142 {
143   for (NCollection_Vector<Handle(SelectMgr_SensitiveEntity)>::Iterator aSelEntIter (theSelection->Entities()); aSelEntIter.More(); aSelEntIter.Next())
144   {
145     aSelEntIter.Value()->ResetSelectionActiveStatus();
146   }
147
148   theSelection->SetSelectionState (SelectMgr_SOS_Deactivated);
149
150   myTolerances.Decrement (theSelection->Sensitivity());
151   myToUpdateTolerance = Standard_True;
152 }
153
154 //==================================================
155 // Function: Clear
156 // Purpose :
157 //==================================================
158 void SelectMgr_ViewerSelector::Clear()
159 {
160   mystored.Clear();
161 }
162
163 //=======================================================================
164 // function: isToScaleFrustum
165 // purpose : Checks if the entity given requires to scale current selecting frustum
166 //=======================================================================
167 Standard_Boolean SelectMgr_ViewerSelector::isToScaleFrustum (const Handle(SelectBasics_SensitiveEntity)& theEntity)
168 {
169   return mySelectingVolumeMgr.GetActiveSelectionType() == SelectMgr_SelectingVolumeManager::Point
170     && sensitivity (theEntity) < myTolerances.Tolerance();
171 }
172
173 //=======================================================================
174 // function: sensitivity
175 // purpose : In case if custom tolerance is set, this method will return sum of entity
176 //           sensitivity and custom tolerance.
177 //=======================================================================
178 Standard_Integer SelectMgr_ViewerSelector::sensitivity (const Handle(SelectBasics_SensitiveEntity)& theEntity) const
179 {
180   return myTolerances.IsCustomTolSet() ?
181     theEntity->SensitivityFactor() + myTolerances.CustomTolerance() : theEntity->SensitivityFactor();
182 }
183
184 //=======================================================================
185 // function: checkOverlap
186 // purpose : Internal function that checks if a particular sensitive
187 //           entity theEntity overlaps current selecting volume precisely
188 //=======================================================================
189 void SelectMgr_ViewerSelector::checkOverlap (const Handle(SelectBasics_SensitiveEntity)& theEntity,
190                                              const gp_GTrsf& theInversedTrsf,
191                                              SelectMgr_SelectingVolumeManager& theMgr)
192 {
193   Handle(SelectMgr_EntityOwner) anOwner (Handle(SelectMgr_EntityOwner)::DownCast (theEntity->OwnerId()));
194   Handle(SelectMgr_SelectableObject) aSelectable;
195   Standard_Boolean toRestoresViewClipEnabled = Standard_False;
196   if (!anOwner.IsNull())
197   {
198     aSelectable = anOwner->Selectable();
199   }
200   if (!aSelectable.IsNull())
201   {
202     if (!aSelectable->ClipPlanes().IsNull()
203       && aSelectable->ClipPlanes()->ToOverrideGlobal())
204     {
205       theMgr.SetViewClippingEnabled (Standard_False);
206       toRestoresViewClipEnabled = Standard_True;
207     }
208     else if (!aSelectable->TransformPersistence().IsNull())
209     {
210       if (aSelectable->TransformPersistence()->IsZoomOrRotate()
211       && !theMgr.ViewClipping().IsNull())
212       {
213         // Zoom/rotate persistence object lives in two worlds at the same time.
214         // Global clipping planes can not be trivially applied without being converted
215         // into local space of transformation persistence object.
216         // As more simple alternative - just clip entire object by its anchor point defined in the world space.
217         const Handle(Graphic3d_SequenceOfHClipPlane)& aViewPlanes = theMgr.ViewClipping();
218
219         const gp_Pnt anAnchor = aSelectable->TransformPersistence()->AnchorPoint();
220         for (Graphic3d_SequenceOfHClipPlane::Iterator aPlaneIt (*aViewPlanes); aPlaneIt.More(); aPlaneIt.Next())
221         {
222           const Handle(Graphic3d_ClipPlane)& aPlane = aPlaneIt.Value();
223           if (!aPlane->IsOn())
224           {
225             continue;
226           }
227
228           const Graphic3d_Vec4d aCheckPnt (anAnchor.X(), anAnchor.Y(), anAnchor.Z(), 1.0);
229           if (aPlane->ProbePoint (aCheckPnt) == Graphic3d_ClipState_Out)
230           {
231             return;
232           }
233         }
234       }
235
236       theMgr.SetViewClippingEnabled (Standard_False);
237       toRestoresViewClipEnabled = Standard_True;
238     }
239   }
240
241   SelectBasics_PickResult aPickResult;
242   const Standard_Boolean isMatched = theEntity->Matches(theMgr, aPickResult);
243   if (toRestoresViewClipEnabled)
244   {
245     theMgr.SetViewClippingEnabled (Standard_True);
246   }
247
248   if (!isMatched
249     || anOwner.IsNull())
250   {
251     return;
252   }
253
254   if (HasDepthClipping (anOwner)
255   && !aSelectable.IsNull()
256   &&  theMgr.GetActiveSelectionType() == SelectMgr_SelectingVolumeManager::Point)
257   {
258     Standard_Boolean isClipped = mySelectingVolumeMgr.IsClipped (*aSelectable->ClipPlanes(),
259                                                                   aPickResult.Depth());
260     if (isClipped)
261       return;
262   }
263
264   SelectMgr_SortCriterion aCriterion;
265   myZLayerOrderMap.Find (!aSelectable.IsNull() ? aSelectable->ZLayer() : Graphic3d_ZLayerId_Default, aCriterion.ZLayerPosition);
266   aCriterion.Entity    = theEntity;
267   aCriterion.Priority  = anOwner->Priority();
268   aCriterion.Depth     = aPickResult.Depth();
269   aCriterion.MinDist   = aPickResult.DistToGeomCenter();
270   aCriterion.ToPreferClosest = preferclosest;
271
272   if (SelectMgr_SortCriterion* aPrevCriterion = mystored.ChangeSeek (anOwner))
273   {
274     ++aPrevCriterion->NbOwnerMatches;
275     aCriterion.NbOwnerMatches = aPrevCriterion->NbOwnerMatches;
276     if (theMgr.GetActiveSelectionType() != SelectBasics_SelectingVolumeManager::Box)
277     {
278       if (aCriterion > *aPrevCriterion)
279       {
280         updatePoint3d (aCriterion, theEntity, theInversedTrsf, theMgr);
281         *aPrevCriterion = aCriterion;
282       }
283     }
284   }
285   else
286   {
287     aCriterion.NbOwnerMatches = 1;
288     updatePoint3d (aCriterion, theEntity, theInversedTrsf, theMgr);
289     mystored.Add (anOwner, aCriterion);
290   }
291 }
292
293 //=======================================================================
294 // function: computeFrustum
295 // purpose : Internal function that checks if a current selecting frustum
296 //           needs to be scaled and transformed for the entity and performs
297 //           necessary calculations
298 //=======================================================================
299 void SelectMgr_ViewerSelector::computeFrustum (const Handle(SelectBasics_SensitiveEntity)& theEnt,
300                                                const SelectMgr_SelectingVolumeManager&     theMgr,
301                                                const gp_GTrsf&                             theInvTrsf,
302                                                SelectMgr_FrustumCache&                     theCachedMgrs,
303                                                SelectMgr_SelectingVolumeManager&           theResMgr)
304 {
305   Standard_Integer aScale = isToScaleFrustum (theEnt) ? sensitivity (theEnt) : 1;
306   const gp_GTrsf aTrsfMtr = theEnt->HasInitLocation() ? theEnt->InvInitLocation() * theInvTrsf : theInvTrsf;
307   const Standard_Boolean toScale = aScale != 1;
308   const Standard_Boolean toTransform = aTrsfMtr.Form() != gp_Identity;
309   if (toScale && toTransform)
310   {
311     theResMgr = theMgr.ScaleAndTransform (aScale, aTrsfMtr, NULL);
312   }
313   else if (toScale)
314   {
315     if (!theCachedMgrs.IsBound (aScale))
316     {
317       theCachedMgrs.Bind (aScale, theMgr.ScaleAndTransform (aScale, gp_Trsf(), NULL));
318     }
319     theResMgr = theCachedMgrs.Find (aScale);
320   }
321   else if (toTransform)
322   {
323     theResMgr = theMgr.ScaleAndTransform (1, aTrsfMtr, NULL);
324   }
325 }
326
327 //=======================================================================
328 // function: traverseObject
329 // purpose : Internal function that checks if there is possible overlap
330 //           between some entity of selectable object theObject and
331 //           current selecting volume
332 //=======================================================================
333 void SelectMgr_ViewerSelector::traverseObject (const Handle(SelectMgr_SelectableObject)& theObject,
334                                                const SelectMgr_SelectingVolumeManager& theMgr,
335                                                const Handle(Graphic3d_Camera)& theCamera,
336                                                const Graphic3d_Mat4d& theProjectionMat,
337                                                const Graphic3d_Mat4d& theWorldViewMat,
338                                                const Standard_Integer theViewportWidth,
339                                                const Standard_Integer theViewportHeight)
340 {
341   Handle(SelectMgr_SensitiveEntitySet)& anEntitySet = myMapOfObjectSensitives.ChangeFind (theObject);
342   if (anEntitySet->Size() == 0)
343   {
344     return;
345   }
346
347   const opencascade::handle<BVH_Tree<Standard_Real, 3> >& aSensitivesTree = anEntitySet->BVH();
348   gp_GTrsf aInversedTrsf;
349   if (theObject->HasTransformation() || !theObject->TransformPersistence().IsNull())
350   {
351     if (theObject->TransformPersistence().IsNull())
352     {
353       aInversedTrsf = theObject->InversedTransformation();
354     }
355     else
356     {
357       gp_GTrsf aTPers;
358       Graphic3d_Mat4d aMat = theObject->TransformPersistence()->Compute (theCamera, theProjectionMat, theWorldViewMat, theViewportWidth, theViewportHeight);
359
360       aTPers.SetValue (1, 1, aMat.GetValue (0, 0));
361       aTPers.SetValue (1, 2, aMat.GetValue (0, 1));
362       aTPers.SetValue (1, 3, aMat.GetValue (0, 2));
363       aTPers.SetValue (2, 1, aMat.GetValue (1, 0));
364       aTPers.SetValue (2, 2, aMat.GetValue (1, 1));
365       aTPers.SetValue (2, 3, aMat.GetValue (1, 2));
366       aTPers.SetValue (3, 1, aMat.GetValue (2, 0));
367       aTPers.SetValue (3, 2, aMat.GetValue (2, 1));
368       aTPers.SetValue (3, 3, aMat.GetValue (2, 2));
369       aTPers.SetTranslationPart (gp_XYZ (aMat.GetValue (0, 3), aMat.GetValue (1, 3), aMat.GetValue (2, 3)));
370
371       aInversedTrsf = (aTPers * gp_GTrsf (theObject->Transformation())).Inverted();
372     }
373   }
374
375   SelectMgr_SelectingVolumeManager aMgr = aInversedTrsf.Form() != gp_Identity
376                                         ? theMgr.ScaleAndTransform (1, aInversedTrsf, NULL)
377                                         : theMgr;
378
379   SelectMgr_FrustumCache aScaledTrnsfFrustums;
380
381   Standard_Integer aNode = 0; // a root node
382   if (!aMgr.Overlaps (aSensitivesTree->MinPoint (0),
383                       aSensitivesTree->MaxPoint (0)))
384   {
385     return;
386   }
387
388   const Standard_Integer aFirstStored = mystored.Extent() + 1;
389
390   Standard_Integer aStack[BVH_Constants_MaxTreeDepth];
391   Standard_Integer aHead = -1;
392   for (;;)
393   {
394     if (!aSensitivesTree->IsOuter (aNode))
395     {
396       const Standard_Integer aLeftChildIdx  = aSensitivesTree->Child<0> (aNode);
397       const Standard_Integer aRightChildIdx = aSensitivesTree->Child<1> (aNode);
398       const Standard_Boolean isLeftChildIn  =  aMgr.Overlaps (aSensitivesTree->MinPoint (aLeftChildIdx),
399                                                               aSensitivesTree->MaxPoint (aLeftChildIdx));
400       const Standard_Boolean isRightChildIn = aMgr.Overlaps (aSensitivesTree->MinPoint (aRightChildIdx),
401                                                              aSensitivesTree->MaxPoint (aRightChildIdx));
402       if (isLeftChildIn
403           && isRightChildIn)
404       {
405         aNode = aLeftChildIdx;
406         ++aHead;
407         aStack[aHead] = aRightChildIdx;
408       }
409       else if (isLeftChildIn
410         || isRightChildIn)
411       {
412         aNode = isLeftChildIn ? aLeftChildIdx : aRightChildIdx;
413       }
414       else
415       {
416         if (aHead < 0)
417         {
418           break;
419         }
420
421         aNode = aStack[aHead];
422         --aHead;
423       }
424     }
425     else
426     {
427       Standard_Integer aStartIdx = aSensitivesTree->BegPrimitive (aNode);
428       Standard_Integer anEndIdx = aSensitivesTree->EndPrimitive (aNode);
429       for (Standard_Integer anIdx = aStartIdx; anIdx <= anEndIdx; ++anIdx)
430       {
431         const Handle(SelectMgr_SensitiveEntity)& aSensitive = anEntitySet->GetSensitiveById (anIdx);
432         if (aSensitive->IsActiveForSelection())
433         {
434           const Handle(SelectBasics_SensitiveEntity)& anEnt = aSensitive->BaseSensitive();
435           SelectMgr_SelectingVolumeManager aTmpMgr = aMgr;
436           computeFrustum (anEnt, theMgr, aInversedTrsf, aScaledTrnsfFrustums, aTmpMgr);
437           checkOverlap (anEnt, aInversedTrsf, aTmpMgr);
438         }
439       }
440       if (aHead < 0)
441       {
442         break;
443       }
444
445       aNode = aStack[aHead];
446       --aHead;
447     }
448   }
449
450   // in case of Box/Polyline selection - keep only Owners having all Entities detected
451   if (mySelectingVolumeMgr.IsOverlapAllowed()
452   || (theMgr.GetActiveSelectionType() != SelectBasics_SelectingVolumeManager::Box
453    && theMgr.GetActiveSelectionType() != SelectBasics_SelectingVolumeManager::Polyline))
454   {
455     return;
456   }
457
458   for (Standard_Integer aStoredIter = mystored.Extent(); aStoredIter >= aFirstStored; --aStoredIter)
459   {
460     const SelectMgr_SortCriterion& aCriterion = mystored.FindFromIndex (aStoredIter);
461     const Handle(SelectBasics_EntityOwner)& anOwner = aCriterion.Entity->OwnerId();
462     Standard_Integer aNbOwnerEntities = 0;
463     for (SelectMgr_IndexedMapOfHSensitive::Iterator aSensIter (anEntitySet->Sensitives()); aSensIter.More(); aSensIter.Next())
464     {
465       if (aSensIter.Value()->BaseSensitive()->OwnerId() == anOwner)
466       {
467         if (++aNbOwnerEntities > aCriterion.NbOwnerMatches)
468         {
469           // Remove from index map.
470           // Considering NCollection_IndexedDataMap implementation, the values for lower indexes will not be modified.
471           // Hence, just keep iterating in backward direction.
472           mystored.RemoveFromIndex (aStoredIter);
473           break;
474         }
475       }
476     }
477   }
478 }
479
480 //=======================================================================
481 // function: TraverseSensitives
482 // purpose : Traverses BVH containing all added selectable objects and
483 //           finds candidates for further search of overlap
484 //=======================================================================
485 void SelectMgr_ViewerSelector::TraverseSensitives()
486 {
487   mystored.Clear();
488
489   Standard_Integer aWidth;
490   Standard_Integer aHeight;
491   mySelectingVolumeMgr.WindowSize (aWidth, aHeight);
492   mySelectableObjects.UpdateBVH (mySelectingVolumeMgr.Camera(),
493                                  mySelectingVolumeMgr.ProjectionMatrix(),
494                                  mySelectingVolumeMgr.WorldViewMatrix(),
495                                  mySelectingVolumeMgr.WorldViewProjState(),
496                                  aWidth, aHeight);
497   const Handle(Graphic3d_Camera)& aCamera = mySelectingVolumeMgr.Camera();
498   if (!aCamera.IsNull())
499   {
500     myCameraEye = aCamera->Eye().XYZ();
501     myCameraDir = aCamera->Direction().XYZ();
502     myCameraScale = aCamera->IsOrthographic()
503                   ? aCamera->Scale()
504                   : 2.0 * Tan (aCamera->FOVy() * M_PI / 360.0);
505     const double aPixelSize = Max (1.0 / aWidth, 1.0 / aHeight);
506     myCameraScale *= aPixelSize;
507   }
508
509   for (Standard_Integer aBVHSetIt = 0; aBVHSetIt < SelectMgr_SelectableObjectSet::BVHSubsetNb; ++aBVHSetIt)
510   {
511     SelectMgr_SelectableObjectSet::BVHSubset aBVHSubset =
512       static_cast<SelectMgr_SelectableObjectSet::BVHSubset> (aBVHSetIt);
513
514     if (mySelectableObjects.IsEmpty (aBVHSubset))
515     {
516       continue;
517     }
518
519     gp_GTrsf aTFrustum;
520
521     SelectMgr_SelectingVolumeManager aMgr (Standard_False);
522
523     // for 2D space selection transform selecting volumes to perform overap testing
524     // directly in camera's eye space omitting the camera position, which is not
525     // needed there at all
526     if (aBVHSubset == SelectMgr_SelectableObjectSet::BVHSubset_2dPersistent)
527     {
528       const Graphic3d_Mat4d& aMat = mySelectingVolumeMgr.WorldViewMatrix();
529       aTFrustum.SetValue (1, 1, aMat.GetValue (0, 0));
530       aTFrustum.SetValue (1, 2, aMat.GetValue (0, 1));
531       aTFrustum.SetValue (1, 3, aMat.GetValue (0, 2));
532       aTFrustum.SetValue (2, 1, aMat.GetValue (1, 0));
533       aTFrustum.SetValue (2, 2, aMat.GetValue (1, 1));
534       aTFrustum.SetValue (2, 3, aMat.GetValue (1, 2));
535       aTFrustum.SetValue (3, 1, aMat.GetValue (2, 0));
536       aTFrustum.SetValue (3, 2, aMat.GetValue (2, 1));
537       aTFrustum.SetValue (3, 3, aMat.GetValue (2, 2));
538       aTFrustum.SetTranslationPart (gp_XYZ (aMat.GetValue (0, 3), aMat.GetValue (1, 3), aMat.GetValue (2, 3)));
539
540       // define corresponding frustum builder parameters
541       Handle(SelectMgr_FrustumBuilder) aBuilder = new SelectMgr_FrustumBuilder();
542       aBuilder->SetProjectionMatrix (mySelectingVolumeMgr.ProjectionMatrix());
543       aBuilder->SetWorldViewMatrix (SelectMgr_ViewerSelector_THE_IDENTITY_MAT);
544       aBuilder->SetWindowSize (aWidth, aHeight);
545       aMgr = mySelectingVolumeMgr.ScaleAndTransform (1, aTFrustum, aBuilder);
546     }
547     else
548     {
549       aMgr = mySelectingVolumeMgr;
550     }
551
552     const Graphic3d_Mat4d& aProjectionMat   = mySelectingVolumeMgr.ProjectionMatrix();
553     const Graphic3d_Mat4d& aWorldViewMat    = aBVHSubset != SelectMgr_SelectableObjectSet::BVHSubset_2dPersistent
554                                             ? mySelectingVolumeMgr.WorldViewMatrix()
555                                             : SelectMgr_ViewerSelector_THE_IDENTITY_MAT;
556
557     const opencascade::handle<BVH_Tree<Standard_Real, 3> >& aBVHTree = mySelectableObjects.BVH (aBVHSubset);
558
559     Standard_Integer aNode = 0;
560     if (!aMgr.Overlaps (aBVHTree->MinPoint (0), aBVHTree->MaxPoint (0)))
561     {
562       continue;
563     }
564
565     Standard_Integer aStack[BVH_Constants_MaxTreeDepth];
566     Standard_Integer aHead = -1;
567     for (;;)
568     {
569       if (!aBVHTree->IsOuter (aNode))
570       {
571         const Standard_Integer aLeftChildIdx  = aBVHTree->Child<0> (aNode);
572         const Standard_Integer aRightChildIdx = aBVHTree->Child<1> (aNode);
573         const Standard_Boolean isLeftChildIn  =
574           aMgr.Overlaps (aBVHTree->MinPoint (aLeftChildIdx), aBVHTree->MaxPoint (aLeftChildIdx));
575         const Standard_Boolean isRightChildIn =
576           aMgr.Overlaps (aBVHTree->MinPoint (aRightChildIdx), aBVHTree->MaxPoint (aRightChildIdx));
577         if (isLeftChildIn
578           && isRightChildIn)
579         {
580           aNode = aLeftChildIdx;
581           ++aHead;
582           aStack[aHead] = aRightChildIdx;
583         }
584         else if (isLeftChildIn
585           || isRightChildIn)
586         {
587           aNode = isLeftChildIn ? aLeftChildIdx : aRightChildIdx;
588         }
589         else
590         {
591           if (aHead < 0)
592           {
593             break;
594           }
595
596           aNode = aStack[aHead];
597           --aHead;
598         }
599       }
600       else
601       {
602         Standard_Integer aStartIdx = aBVHTree->BegPrimitive (aNode);
603         Standard_Integer anEndIdx  = aBVHTree->EndPrimitive (aNode);
604         for (Standard_Integer anIdx = aStartIdx; anIdx <= anEndIdx; ++anIdx)
605         {
606           const Handle(SelectMgr_SelectableObject)& aSelectableObject =
607             mySelectableObjects.GetObjectById (aBVHSubset, anIdx);
608
609           traverseObject (aSelectableObject, aMgr, aCamera, aProjectionMat, aWorldViewMat, aWidth, aHeight);
610         }
611         if (aHead < 0)
612         {
613           break;
614         }
615
616         aNode = aStack[aHead];
617         --aHead;
618       }
619     }
620   }
621
622   SortResult();
623 }
624
625 //==================================================
626 // Function: ClearPicked
627 // Purpose :
628 //==================================================
629 void SelectMgr_ViewerSelector::ClearPicked()
630 {
631   mystored.Clear();
632 }
633
634 //==================================================
635 // Function: Picked
636 // Purpose :
637 //==================================================
638 Handle(SelectMgr_EntityOwner) SelectMgr_ViewerSelector
639 ::Picked() const
640 {
641   Standard_Integer RankInMap = myIndexes->Value (myCurRank);
642   const Handle(SelectBasics_EntityOwner)& toto = mystored.FindKey(RankInMap);
643   Handle(SelectMgr_EntityOwner) Ownr = Handle(SelectMgr_EntityOwner)::DownCast (toto);
644   return Ownr;
645 }
646
647 //=======================================================================
648 //function : Picked
649 //purpose  :
650 //=======================================================================
651 Handle(SelectMgr_EntityOwner) SelectMgr_ViewerSelector::Picked (const Standard_Integer theRank) const
652 {
653   Handle(SelectMgr_EntityOwner) anOwner;
654   if (theRank < 1 || theRank > NbPicked())
655   {
656     return anOwner;
657   }
658
659   const Standard_Integer anOwnerIdx = myIndexes->Value (theRank);
660   const Handle(SelectBasics_EntityOwner)& aStoredOwner = mystored.FindKey (anOwnerIdx);
661   anOwner = Handle(SelectMgr_EntityOwner)::DownCast (aStoredOwner);
662   return anOwner;
663 }
664
665 //=======================================================================
666 //function : PickedData
667 //purpose  :
668 //=======================================================================
669 const SelectMgr_SortCriterion& SelectMgr_ViewerSelector::PickedData(const Standard_Integer theRank) const
670 {
671   Standard_OutOfRange_Raise_if (theRank < 1 || theRank > NbPicked(), "SelectMgr_ViewerSelector::PickedData() out of range index");
672   const Standard_Integer anOwnerIdx = myIndexes->Value (theRank);
673   return mystored.FindFromIndex (anOwnerIdx);
674 }
675
676 //===================================================
677 //
678 //       INTERNAL METHODS ....
679 //
680 //==================================================
681
682 //==================================================
683 // Function: SetEntitySetBuilder
684 // Purpose :
685 //==================================================
686 void SelectMgr_ViewerSelector::SetEntitySetBuilder (const Handle(Select3D_BVHBuilder3d)& theBuilder)
687 {
688   myEntitySetBuilder = theBuilder;
689   for (SelectMgr_MapOfObjectSensitives::Iterator aSetIter (myMapOfObjectSensitives); aSetIter.More(); aSetIter.Next())
690   {
691     aSetIter.ChangeValue()->SetBuilder (myEntitySetBuilder);
692   }
693 }
694
695 //==================================================
696 // Function: Contains
697 // Purpose :
698 //==================================================
699 Standard_Boolean SelectMgr_ViewerSelector::Contains (const Handle(SelectMgr_SelectableObject)& theObject) const
700 {
701   return mySelectableObjects.Contains (theObject);
702 }
703
704 //==================================================
705 // Function: ActiveModes
706 // Purpose : return all the  modes with a given state for an object
707 //==================================================
708 Standard_Boolean SelectMgr_ViewerSelector::Modes (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
709                                                   TColStd_ListOfInteger& theModeList,
710                                                   const SelectMgr_StateOfSelection theWantedState) const
711 {
712   Standard_Boolean hasActivatedStates = Contains (theSelectableObject);
713   for (SelectMgr_SequenceOfSelection::Iterator aSelIter (theSelectableObject->Selections()); aSelIter.More(); aSelIter.Next())
714   {
715       if (theWantedState == SelectMgr_SOS_Any)
716       {
717         theModeList.Append (aSelIter.Value()->Mode());
718       }
719       else if (theWantedState == aSelIter.Value()->GetSelectionState())
720       {
721         theModeList.Append (aSelIter.Value()->Mode());
722       }
723   }
724
725   return hasActivatedStates;
726 }
727
728 //==================================================
729 // Function: IsActive
730 // Purpose :
731 //==================================================
732 Standard_Boolean SelectMgr_ViewerSelector::IsActive (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
733                                                      const Standard_Integer theMode) const
734 {
735   if (!Contains (theSelectableObject))
736     return Standard_False;
737
738   const Handle(SelectMgr_Selection)& aSel = theSelectableObject->Selection (theMode);
739   return !aSel.IsNull()
740        && aSel->GetSelectionState() == SelectMgr_SOS_Activated;
741 }
742
743 //==================================================
744 // Function: IsInside
745 // Purpose :
746 //==================================================
747 Standard_Boolean SelectMgr_ViewerSelector::IsInside (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
748                                                      const Standard_Integer theMode) const
749 {
750   if (!Contains (theSelectableObject))
751     return Standard_False;
752
753   const Handle(SelectMgr_Selection)& aSel = theSelectableObject->Selection (theMode);
754   return !aSel.IsNull()
755        && aSel->GetSelectionState() != SelectMgr_SOS_Unknown;
756 }
757
758
759 //=======================================================================
760 //function : Status
761 //purpose  :
762 //=======================================================================
763
764 SelectMgr_StateOfSelection SelectMgr_ViewerSelector::Status (const Handle(SelectMgr_Selection)& theSelection) const
765 {
766   return theSelection->GetSelectionState();
767 }
768
769 //==================================================
770 // Function: Status
771 // Purpose : gives Information about selectors
772 //==================================================
773
774 TCollection_AsciiString SelectMgr_ViewerSelector::Status (const Handle(SelectMgr_SelectableObject)& theSelectableObject) const
775 {
776   TCollection_AsciiString aStatus ("Status Object :\n\t");
777   for (SelectMgr_SequenceOfSelection::Iterator aSelIter (theSelectableObject->Selections()); aSelIter.More(); aSelIter.Next())
778   {
779     if (aSelIter.Value()->GetSelectionState() != SelectMgr_SOS_Unknown)
780     {
781       aStatus = aStatus + "Mode " + TCollection_AsciiString (aSelIter.Value()->Mode()) + " present - "
782               + (aSelIter.Value()->GetSelectionState() == SelectMgr_SOS_Activated ? " Active \n\t" : " Inactive \n\t");
783     }
784   }
785
786   if (!Contains (theSelectableObject))
787   {
788     aStatus = aStatus + "Not Present in the selector\n\n";
789   }
790
791   return aStatus;
792 }
793
794 //=======================================================================
795 //function : SortResult
796 //purpose  :  there is a certain number of entities ranged by criteria
797 //            (depth, size, priority, mouse distance from borders or
798 //            CDG of the detected primitive. Parsing :
799 //             maximum priorities .
800 //             then a reasonable compromise between depth and distance...
801 // finally the ranges are stored in myindexes depending on the parsing.
802 // so, it is possible to only read
803 //=======================================================================
804 void SelectMgr_ViewerSelector::SortResult()
805 {
806   if(mystored.IsEmpty()) return;
807
808   const Standard_Integer anExtent = mystored.Extent();
809   if(myIndexes.IsNull() || anExtent != myIndexes->Length())
810     myIndexes = new TColStd_HArray1OfInteger (1, anExtent);
811
812   TColStd_Array1OfInteger& anIndexArray = myIndexes->ChangeArray1();
813   for (Standard_Integer anIndexIter = 1; anIndexIter <= anExtent; ++anIndexIter)
814   {
815     anIndexArray.SetValue (anIndexIter, anIndexIter);
816   }
817   std::sort (anIndexArray.begin(), anIndexArray.end(), CompareResults (mystored));
818 }
819
820 //=======================================================================
821 //function : HasDepthClipping
822 //purpose  : Stub
823 //=======================================================================
824 Standard_Boolean SelectMgr_ViewerSelector::HasDepthClipping (const Handle(SelectMgr_EntityOwner)& /*theOwner*/) const
825 {
826   return Standard_False;
827 }
828
829 //=======================================================================
830 // function : AddSelectableObject
831 // purpose  : Adds new object to the map of selectable objects
832 //=======================================================================
833 void SelectMgr_ViewerSelector::AddSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject)
834 {
835   if (!myMapOfObjectSensitives.IsBound (theObject))
836   {
837     mySelectableObjects.Append (theObject);
838     Handle(SelectMgr_SensitiveEntitySet) anEntitySet = new SelectMgr_SensitiveEntitySet (myEntitySetBuilder);
839     myMapOfObjectSensitives.Bind (theObject, anEntitySet);
840   }
841 }
842
843 //=======================================================================
844 // function : AddSelectionToObject
845 // purpose  : Adds new selection to the object and builds its BVH tree
846 //=======================================================================
847 void SelectMgr_ViewerSelector::AddSelectionToObject (const Handle(SelectMgr_SelectableObject)& theObject,
848                                                      const Handle(SelectMgr_Selection)& theSelection)
849 {
850   if (Handle(SelectMgr_SensitiveEntitySet)* anEntitySet = myMapOfObjectSensitives.ChangeSeek (theObject))
851   {
852     (*anEntitySet)->Append (theSelection);
853     (*anEntitySet)->BVH();
854   }
855   else
856   {
857     AddSelectableObject (theObject);
858     AddSelectionToObject (theObject, theSelection);
859   }
860 }
861
862 //=======================================================================
863 // function : MoveSelectableObject
864 // purpose  :
865 //=======================================================================
866 void SelectMgr_ViewerSelector::MoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject)
867 {
868   mySelectableObjects.ChangeSubset (theObject);
869 }
870
871 //=======================================================================
872 // function : RemoveSelectableObject
873 // purpose  : Removes selectable object from map of selectable ones
874 //=======================================================================
875 void SelectMgr_ViewerSelector::RemoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject)
876 {
877   Handle(SelectMgr_SelectableObject) anObj = theObject;
878   if (myMapOfObjectSensitives.UnBind (theObject))
879   {
880     mySelectableObjects.Remove (theObject);
881   }
882 }
883
884 //=======================================================================
885 // function : RemoveSelectionOfObject
886 // purpose  : Removes selection of the object and marks its BVH tree
887 //            for rebuild
888 //=======================================================================
889 void SelectMgr_ViewerSelector::RemoveSelectionOfObject (const Handle(SelectMgr_SelectableObject)& theObject,
890                                                         const Handle(SelectMgr_Selection)& theSelection)
891 {
892   if (Handle(SelectMgr_SensitiveEntitySet)* anEntitySet = myMapOfObjectSensitives.ChangeSeek (theObject))
893   {
894     (*anEntitySet)->Remove (theSelection);
895   }
896 }
897
898 //=======================================================================
899 // function : RebuildObjectsTree
900 // purpose  : Marks BVH of selectable objects for rebuild
901 //=======================================================================
902 void SelectMgr_ViewerSelector::RebuildObjectsTree (const Standard_Boolean theIsForce)
903 {
904   mySelectableObjects.MarkDirty();
905
906   if (theIsForce)
907   {
908     Standard_Integer aViewportWidth, aViewportHeight;
909     mySelectingVolumeMgr.WindowSize (aViewportWidth, aViewportHeight);
910
911     Standard_Integer aWidth;
912     Standard_Integer aHeight;
913     mySelectingVolumeMgr.WindowSize (aWidth, aHeight);
914     mySelectableObjects.UpdateBVH (mySelectingVolumeMgr.Camera(),
915                                    mySelectingVolumeMgr.ProjectionMatrix(),
916                                    mySelectingVolumeMgr.WorldViewMatrix(),
917                                    mySelectingVolumeMgr.WorldViewProjState(),
918                                    aWidth, aHeight);
919   }
920 }
921
922 //=======================================================================
923 // function : RebuildSensitivesTree
924 // purpose  : Marks BVH of sensitive entities of particular selectable
925 //            object for rebuild
926 //=======================================================================
927 void SelectMgr_ViewerSelector::RebuildSensitivesTree (const Handle(SelectMgr_SelectableObject)& theObject,
928                                                       const Standard_Boolean theIsForce)
929 {
930   if (!Contains (theObject))
931     return;
932
933   Handle(SelectMgr_SensitiveEntitySet)& anEntitySet = myMapOfObjectSensitives.ChangeFind (theObject);
934   anEntitySet->MarkDirty();
935
936   if (theIsForce)
937   {
938     anEntitySet->BVH();
939   }
940 }
941
942 //=======================================================================
943 // function : resetSelectionActivationStatus
944 // purpose  : Marks all added sensitive entities of all objects as
945 //            non-selectable
946 //=======================================================================
947 void SelectMgr_ViewerSelector::ResetSelectionActivationStatus()
948 {
949   for (SelectMgr_MapOfObjectSensitivesIterator aSensitivesIter (myMapOfObjectSensitives); aSensitivesIter.More(); aSensitivesIter.Next())
950   {
951     Handle(SelectMgr_SensitiveEntitySet)& anEntitySet = aSensitivesIter.ChangeValue();
952     const Standard_Integer anEntitiesNb = anEntitySet->Size();
953     for (Standard_Integer anIdx = 0; anIdx < anEntitiesNb; ++anIdx)
954     {
955       anEntitySet->GetSensitiveById (anIdx)->ResetSelectionActiveStatus();
956     }
957   }
958 }
959
960 //=======================================================================
961 // function : DetectedEntity
962 // purpose  : Returns sensitive entity that was detected during the
963 //            previous run of selection algorithm
964 //=======================================================================
965 const Handle(SelectBasics_SensitiveEntity)& SelectMgr_ViewerSelector::DetectedEntity() const
966 {
967   const Standard_Integer aRankInMap = myIndexes->Value(myCurRank);
968   return mystored.FindFromIndex (aRankInMap).Entity;
969 }
970
971 //=======================================================================
972 // function : ActiveOwners
973 // purpose  : Returns the list of active entity owners
974 //=======================================================================
975 void SelectMgr_ViewerSelector::ActiveOwners (NCollection_List<Handle(SelectBasics_EntityOwner)>& theOwners) const
976 {
977   for (SelectMgr_MapOfObjectSensitivesIterator anIter (myMapOfObjectSensitives); anIter.More(); anIter.Next())
978   {
979     const Handle(SelectMgr_SensitiveEntitySet)& anEntitySet = anIter.Value();
980     const Standard_Integer anEntitiesNb = anEntitySet->Size();
981     for (Standard_Integer anIdx = 0; anIdx < anEntitiesNb; ++anIdx)
982     {
983       const Handle(SelectMgr_SensitiveEntity)& aSensitive = anEntitySet->GetSensitiveById (anIdx);
984       if (aSensitive->IsActiveForSelection())
985       {
986         theOwners.Append (aSensitive->BaseSensitive()->OwnerId());
987       }
988     }
989   }
990 }
991
992 //=======================================================================
993 //function : AllowOverlapDetection
994 //purpose  : Sets the detection type: if theIsToAllow is false,
995 //           only fully included sensitives will be detected, otherwise
996 //           the algorithm will mark both included and overlapped entities
997 //           as matched
998 //=======================================================================
999 void SelectMgr_ViewerSelector::AllowOverlapDetection (const Standard_Boolean theIsToAllow)
1000 {
1001   mySelectingVolumeMgr.AllowOverlapDetection (theIsToAllow);
1002 }