ae444bbded6b31bd35f1218d2cb9ef6f6e193620
[occt.git] / src / SelectMgr / SelectMgr_ViewerSelector.hxx
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 #ifndef _SelectMgr_ViewerSelector_HeaderFile
18 #define _SelectMgr_ViewerSelector_HeaderFile
19
20 #include <Standard_Transient.hxx>
21 #include <NCollection_DataMap.hxx>
22 #include <OSD_Chronometer.hxx>
23 #include <TColStd_SequenceOfInteger.hxx>
24 #include <TColStd_HArray1OfInteger.hxx>
25 #include <Select3D_BVHBuilder3d.hxx>
26 #include <SelectMgr_IndexedDataMapOfOwnerCriterion.hxx>
27 #include <SelectMgr_SelectingVolumeManager.hxx>
28 #include <SelectMgr_Selection.hxx>
29 #include <SelectMgr_SelectableObject.hxx>
30 #include <SelectMgr_SelectableObjectSet.hxx>
31 #include <SelectMgr_StateOfSelection.hxx>
32 #include <SelectMgr_ToleranceMap.hxx>
33 #include <Standard_OStream.hxx>
34
35 class SelectMgr_SelectionManager;
36 class SelectMgr_SensitiveEntitySet;
37 class SelectMgr_EntityOwner;
38 class SelectBasics_SensitiveEntity;
39
40 // resolve name collisions with X11 headers
41 #ifdef Status
42   #undef Status
43 #endif
44 typedef NCollection_DataMap<Handle(SelectMgr_SelectableObject), Handle(SelectMgr_SensitiveEntitySet) > SelectMgr_MapOfObjectSensitives;
45 typedef NCollection_DataMap<Handle(SelectMgr_SelectableObject), Handle(SelectMgr_SensitiveEntitySet) >::Iterator SelectMgr_MapOfObjectSensitivesIterator;
46
47 typedef NCollection_DataMap<Standard_Integer, SelectMgr_SelectingVolumeManager> SelectMgr_FrustumCache;
48
49 //! A framework to define finding, sorting the sensitive
50 //! primitives in a view. Services are also provided to
51 //! define the return of the owners of those primitives
52 //! selected. The primitives are sorted by criteria such
53 //! as priority of the primitive or its depth in the view
54 //! relative to that of other primitives.
55 //! Note that in 3D, the inheriting framework
56 //! StdSelect_ViewerSelector3d   is only to be used
57 //! if you do not want to use the services provided by
58 //! AIS.
59 //! Two tools are available to find and select objects
60 //! found at a given position in the view. If you want to
61 //! select the owners of all the objects detected at
62 //! point x,y,z you use the Init - More - Next - Picked
63 //! loop. If, on the other hand, you want to select only
64 //! one object detected at that point, you use the Init -
65 //! More - OnePicked loop. In this iteration, More is
66 //! used to see if an object was picked and
67 //! OnePicked, to get the object closest to the pick position.
68 //! Viewer selectors are driven by
69 //! SelectMgr_SelectionManager, and manipulate
70 //! the SelectMgr_Selection objects given to them by
71 //! the selection manager.
72 //!
73 //! Tolerances are applied to the entities in the following way:
74 //! 1. tolerance value stored in mytolerance will be used to calculate initial
75 //!    selecting frustum, which will be applied for intersection testing during
76 //!    BVH traverse;
77 //! 2. if tolerance of sensitive entity is less than mytolerance, the frustum for
78 //!    intersection detection will be resized according to its sensitivity.
79 class SelectMgr_ViewerSelector : public Standard_Transient
80 {
81   DEFINE_STANDARD_RTTIEXT(SelectMgr_ViewerSelector, Standard_Transient)
82   friend class SelectMgr_SelectionManager;
83 public:
84
85   //! Empties all the tables, removes all selections...
86   Standard_EXPORT void Clear();
87
88   //! returns the Sensitivity of picking
89   Standard_Real Sensitivity() const { return myTolerances.Tolerance(); }
90
91   //! Sorts the detected entites by priority and distance.
92   //!          to be redefined if other criterion are used...
93   Standard_EXPORT void SortResult();
94
95   //! Returns the picked element with the highest priority,
96   //! and which is the closest to the last successful mouse position.
97   Handle(SelectMgr_EntityOwner) OnePicked() const
98   {
99     return mystored.IsEmpty()
100          ? Handle(SelectMgr_EntityOwner)()
101          : Picked (1);
102   }
103
104   //! Set preference of selecting one object for OnePicked() method:
105   //! - If True, objects with less depth (distance fron the view plane) are
106   //!   preferred regardless of priority (priority is used then to choose among
107   //!   objects with similar depth),
108   //! - If False, objects with higher priority are preferred regardless of the
109   //!   depth which is used to choose among objects of the same priority.
110   void SetPickClosest (const Standard_Boolean theToPreferClosest) { preferclosest = theToPreferClosest; }
111
112   //! Returns the number of detected owners.
113   Standard_Integer NbPicked() const { return mystored.Extent(); }
114
115   //! Returns the entity Owner for the object picked at specified position.
116   //! @param theRank rank of detected object within range 1...NbPicked()
117   Standard_EXPORT Handle(SelectMgr_EntityOwner) Picked (const Standard_Integer theRank) const;
118
119   //! Returns the Entity for the object picked at specified position.
120   //! @param theRank rank of detected object within range 1...NbPicked()
121   Standard_EXPORT const SelectMgr_SortCriterion& PickedData (const Standard_Integer theRank) const;
122
123   //! Returns the Entity for the object picked at specified position.
124   //! @param theRank rank of detected object within range 1...NbPicked()
125   const Handle(SelectBasics_SensitiveEntity)& PickedEntity (const Standard_Integer theRank) const { return PickedData (theRank).Entity; }
126
127   //! Returns the 3D point (intersection of picking axis with the object nearest to eye)
128   //! for the object picked at specified position.
129   //! @param theRank rank of detected object within range 1...NbPicked()
130   gp_Pnt PickedPoint (const Standard_Integer theRank) const { return PickedData (theRank).Point; }
131
132   Standard_EXPORT Standard_Boolean Contains (const Handle(SelectMgr_SelectableObject)& theObject) const;
133
134   //! Returns the default builder used to construct BVH of entity set.
135   const Handle(Select3D_BVHBuilder3d) EntitySetBuilder() { return myEntitySetBuilder; }
136
137   //! Sets the default builder used to construct BVH of entity set.
138   //! The new builder will be also assigned for already defined objects, but computed BVH trees will not be invalidated.
139   Standard_EXPORT void SetEntitySetBuilder (const Handle(Select3D_BVHBuilder3d)& theBuilder);
140
141   //! Returns the list of selection modes ModeList found in
142   //! this selector for the selectable object aSelectableObject.
143   //! Returns true if aSelectableObject is referenced inside
144   //! this selector; returns false if the object is not present
145   //! in this selector.
146   Standard_EXPORT Standard_Boolean Modes (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
147                                           TColStd_ListOfInteger& theModeList,
148                                           const SelectMgr_StateOfSelection theWantedState = SelectMgr_SOS_Any) const;
149
150   //! Returns true if the selectable object
151   //! aSelectableObject having the selection mode aMode
152   //! is active in this selector.
153   Standard_EXPORT Standard_Boolean IsActive (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
154                                              const Standard_Integer theMode) const;
155
156   //! Returns true if the selectable object
157   //! aSelectableObject having the selection mode aMode
158   //! is in this selector.
159   Standard_EXPORT Standard_Boolean IsInside (const Handle(SelectMgr_SelectableObject)& theSelectableObject,
160                                              const Standard_Integer theMode) const;
161
162   //! Returns the selection status Status of the selection aSelection.
163   Standard_EXPORT SelectMgr_StateOfSelection Status (const Handle(SelectMgr_Selection)& theSelection) const;
164
165   Standard_EXPORT TCollection_AsciiString Status (const Handle(SelectMgr_SelectableObject)& theSelectableObject) const;
166
167   //! Returns the list of active entity owners
168   Standard_EXPORT void ActiveOwners (NCollection_List<Handle(SelectBasics_EntityOwner)>& theOwners) const;
169
170   //! Adds new object to the map of selectable objects
171   Standard_EXPORT void AddSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
172
173   //! Adds new selection to the object and builds its BVH tree
174   Standard_EXPORT void AddSelectionToObject (const Handle(SelectMgr_SelectableObject)& theObject,
175                                              const Handle(SelectMgr_Selection)& theSelection);
176
177   //! Moves existing object from set of not transform persistence objects
178   //! to set of transform persistence objects (or vice versa).
179   Standard_EXPORT void MoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
180
181   //! Removes selectable object from map of selectable ones
182   Standard_EXPORT void RemoveSelectableObject (const Handle(SelectMgr_SelectableObject)& theObject);
183
184   //! Removes selection of the object and marks its BVH tree for rebuild
185   Standard_EXPORT void RemoveSelectionOfObject (const Handle(SelectMgr_SelectableObject)& theObject,
186                                                 const Handle(SelectMgr_Selection)& theSelection);
187
188   //! Marks BVH of selectable objects for rebuild. Parameter theIsForce set as true
189   //! guarantees that 1st level BVH for the viewer selector will be rebuilt during this call
190   Standard_EXPORT void RebuildObjectsTree (const Standard_Boolean theIsForce = Standard_False);
191
192   //! Marks BVH of sensitive entities of particular selectable object for rebuild. Parameter
193   //! theIsForce set as true guarantees that 2nd level BVH for the object given will be
194   //! rebuilt during this call
195   Standard_EXPORT void RebuildSensitivesTree (const Handle(SelectMgr_SelectableObject)& theObject,
196                                               const Standard_Boolean theIsForce = Standard_False);
197
198   //! Returns instance of selecting volume manager of the viewer selector
199   SelectMgr_SelectingVolumeManager& GetManager() { return mySelectingVolumeMgr; }
200
201   //! Marks all added sensitive entities of all objects as non-selectable
202   Standard_EXPORT void ResetSelectionActivationStatus();
203
204   //! Is used for rectangular selection only
205   //! If theIsToAllow is false, only fully included sensitives will be detected, otherwise the algorithm will
206   //! mark both included and overlapped entities as matched
207   Standard_EXPORT void AllowOverlapDetection (const Standard_Boolean theIsToAllow);
208
209 public:
210
211   //! Begins an iteration scanning for the owners detected at a position in the view.
212   Standard_DEPRECATED("Deprecated method Init()")
213   void Init() { initPicked(); }
214
215   //! Continues the interation scanning for the owners detected at a position in the view,
216   //! or continues the iteration scanning for the owner closest to the position in the view.
217   Standard_DEPRECATED("Deprecated method More()")
218   Standard_Boolean More() { return morePicked(); }
219
220   //! Returns the next owner found in the iteration. This is
221   //! a scan for the owners detected at a position in the view.
222   Standard_DEPRECATED("Deprecated method Next()")
223   void Next() { nextPicked(); }
224
225   //! Returns the current selected entity detected by the selector;
226   Standard_DEPRECATED("Deprecated method Picked()")
227   Standard_EXPORT Handle(SelectMgr_EntityOwner) Picked() const;
228
229   //! Initializes internal iterator for stored detected sensitive entities
230   Standard_DEPRECATED("Deprecated method InitDetected()")
231   void InitDetected() { initPicked(); }
232
233   //! Makes a step along the map of detected sensitive entities and their owners
234   Standard_DEPRECATED("Deprecated method NextDetected()")
235   void NextDetected() { nextPicked(); }
236
237   //! Returns true if iterator of map of detected sensitive entities has reached its end
238   Standard_DEPRECATED("Deprecated method MoreDetected()")
239   Standard_Boolean MoreDetected() { return morePicked(); }
240
241   //! Returns sensitive entity that was detected during the previous run of selection algorithm
242   Standard_DEPRECATED("Deprecated method DetectedEntity() should be replaced by DetectedEntity(int)")
243   Standard_EXPORT const Handle(SelectBasics_SensitiveEntity)& DetectedEntity() const;
244
245 protected:
246
247   Standard_EXPORT SelectMgr_ViewerSelector();
248
249   //! Traverses BVH containing all added selectable objects and
250   //! finds candidates for further search of overlap
251   Standard_EXPORT void TraverseSensitives();
252
253   //! Returns True if the owner provides clipping by depth
254   //! for its sensitives. Override this method to tell the selector
255   //! to use the DepthClipping method for the owner.
256   //! Default implementation returns False for every owner.
257   //! @param theOwner [in] the onwer to check.
258   //! @return True if owner provides depth limits for sensitive clipping.
259   Standard_EXPORT virtual Standard_Boolean HasDepthClipping (const Handle(SelectMgr_EntityOwner)& theOwner) const;
260
261   //! Internal function that checks if there is possible overlap between some entity of selectable object theObject and
262   //! current selecting volume.
263   //! @param theObject [in] the selectable object for traversal.
264   //! @param theMgr [in] the (un)transformed copy of the selecting volume manager representing active selection frustum.
265   //! @param theCamera, theProjectionMat, theWorldViewMat [in] the source camera and matrices for theMgr given.
266   //! @param theViewportWidth, theViewportHeight [in] viewport (window) dimensions for evaluating 
267   //!        object's transformation persistence.
268   Standard_EXPORT void traverseObject (const Handle(SelectMgr_SelectableObject)& theObject,
269                                        const SelectMgr_SelectingVolumeManager& theMgr,
270                                        const Handle(Graphic3d_Camera)& theCamera,
271                                        const Graphic3d_Mat4d& theProjectionMat,
272                                        const Graphic3d_Mat4d& theWorldViewMat,
273                                        const Standard_Integer theViewportWidth,
274                                        const Standard_Integer theViewportHeight);
275
276   //! Internal function that checks if a particular sensitive
277   //! entity theEntity overlaps current selecting volume precisely
278   Standard_EXPORT void checkOverlap (const Handle(SelectBasics_SensitiveEntity)& theEntity,
279                                      const gp_GTrsf& theInversedTrsf,
280                                      SelectMgr_SelectingVolumeManager& theMgr);
281
282 private:
283
284   //! Checks if the entity given requires to scale current selecting frustum
285   Standard_Boolean isToScaleFrustum (const Handle(SelectBasics_SensitiveEntity)& theEntity);
286
287   //! In case if custom tolerance is set, this method will return sum of entity sensitivity and
288   //! custom tolerance. Otherwise, pure entity sensitivity factor will be returned.
289   Standard_Integer sensitivity (const Handle(SelectBasics_SensitiveEntity)& theEntity) const;
290
291   void Activate (const Handle(SelectMgr_Selection)& theSelection);
292
293   void Deactivate (const Handle(SelectMgr_Selection)& theSelection);
294
295   //! removes a Selection from the Selector
296   void Remove (const Handle(SelectMgr_Selection)& aSelection);
297
298   //! Internal function that checks if a current selecting frustum
299   //! needs to be scaled and transformed for the entity and performs
300   //! necessary calculations
301   void computeFrustum (const Handle(SelectBasics_SensitiveEntity)& theEnt,
302                        const SelectMgr_SelectingVolumeManager&     theMgr,
303                        const gp_GTrsf&                             theInvTrsf,
304                        SelectMgr_FrustumCache&                     theCachedMgrs,
305                        SelectMgr_SelectingVolumeManager&           theResMgr);
306
307
308 private: // implementation of deprecated methods
309
310   //! Initializes internal iterator for stored detected sensitive entities
311   void initPicked() { myCurRank = 1; }
312
313   //! Makes a step along the map of detected sensitive entities and their owners
314   void nextPicked() { ++myCurRank; }
315
316   //! Returns true if iterator of map of detected sensitive entities has reached its end
317   Standard_Boolean morePicked() const
318   {
319     if (mystored.Extent() == 0) return Standard_False;
320     if (myCurRank == 0) return Standard_False;
321     return myCurRank <= myIndexes->Length();
322   }
323
324 protected:
325
326   Standard_Boolean                              preferclosest;
327   Standard_Boolean                              myToUpdateTolerance;
328   SelectMgr_IndexedDataMapOfOwnerCriterion      mystored;
329   SelectMgr_SelectingVolumeManager              mySelectingVolumeMgr;
330   mutable SelectMgr_SelectableObjectSet         mySelectableObjects;
331   SelectMgr_ToleranceMap                        myTolerances;
332   NCollection_DataMap<Graphic3d_ZLayerId, Standard_Integer> myZLayerOrderMap;
333   Handle(Select3D_BVHBuilder3d)                 myEntitySetBuilder;
334
335 private:
336
337   Handle(TColStd_HArray1OfInteger)             myIndexes;
338   Standard_Integer                             myCurRank;
339   Standard_Boolean                             myIsLeftChildQueuedFirst;
340   Standard_Integer                             myEntityIdx;
341   SelectMgr_MapOfObjectSensitives              myMapOfObjectSensitives;
342
343 };
344
345 DEFINE_STANDARD_HANDLE(SelectMgr_ViewerSelector, Standard_Transient)
346
347 #endif