Salome HOME
0021791: [CEA 623] Clipping : no difference between a closed shell and a solid.
[modules/gui.git] / src / OCCViewer / OCCViewer_ViewModel.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include "OCCViewer_ViewModel.h"
24 #include "OCCViewer_ViewWindow.h"
25 #include "OCCViewer_ViewFrame.h"
26 #include "OCCViewer_VService.h"
27 #include "OCCViewer_ViewPort3d.h"
28 #include "OCCViewer_ClippingDlg.h"
29 #include "OCCViewer_Utilities.h"
30
31 #include "SUIT_ViewWindow.h"
32 #include "SUIT_ViewManager.h"
33 #include "SUIT_Desktop.h"
34 #include "SUIT_Session.h"
35 #include "SUIT_ResourceMgr.h"
36
37 #include "ViewerData_AISShape.hxx"
38
39 #include "QtxActionToolMgr.h"
40 #include "QtxBackgroundTool.h"
41
42 #include <QPainter>
43 #include <QApplication>
44 #include <QColorDialog>
45 #include <QFileDialog>
46 #include <QPalette>
47 #include <QKeyEvent>
48 #include <QMenu>
49 #include <QMouseEvent>
50 #include <QToolBar>
51 #include <QDesktopWidget>
52
53 #include <AIS_Axis.hxx>
54 #include <AIS_Drawer.hxx>
55 #include <AIS_ListOfInteractive.hxx>
56 #include <AIS_ListIteratorOfListOfInteractive.hxx>
57
58 #include <Graphic3d_Texture2Dmanual.hxx>
59 #include <Graphic3d_TextureParams.hxx>
60
61 #include <Geom_Axis2Placement.hxx>
62 #include <Prs3d_Drawer.hxx>
63 #include <Prs3d_DatumAspect.hxx>
64 #include <Prs3d_LineAspect.hxx>
65 #include <Prs3d_TextAspect.hxx>
66
67 #include <Visual3d_View.hxx>
68
69
70 // VSR: Uncomment below line to allow texture background support in OCC viewer
71 #define OCC_ENABLE_TEXTURED_BACKGROUND
72
73 /*!
74   Get data for supported background modes: gradient types, identifiers and supported image formats
75 */
76 QString OCCViewer_Viewer::backgroundData( QStringList& gradList, QIntList& idList, QIntList& txtList )
77 {
78   gradList << tr("GT_HORIZONTALGRADIENT")    << tr("GT_VERTICALGRADIENT")       <<
79               tr("GT_FIRSTDIAGONALGRADIENT") << tr("GT_SECONDDIAGONALGRADIENT") <<
80               tr("GT_FIRSTCORNERGRADIENT")   << tr("GT_SECONDCORNERGRADIENT")   <<
81               tr("GT_THIRDCORNERGRADIENT")   << tr("GT_FORTHCORNERGRADIENT");
82   idList   << HorizontalGradient             << VerticalGradient  <<
83               Diagonal1Gradient              << Diagonal2Gradient <<
84               Corner1Gradient                << Corner2Gradient   <<
85               Corner3Gradient                << Corner4Gradient;
86 #if OCC_VERSION_LARGE > 0x06050200 // enabled since OCCT 6.5.3, since in previous version this functionality is buggy
87 #ifdef OCC_ENABLE_TEXTURED_BACKGROUND
88   txtList  << Qtx::CenterTexture << Qtx::TileTexture << Qtx::StretchTexture;
89 #endif
90 #endif
91   return tr("BG_IMAGE_FILES");
92 }
93
94 /*!
95   Constructor
96   \param DisplayTrihedron - is trihedron displayed
97 */
98 OCCViewer_Viewer::OCCViewer_Viewer( bool DisplayTrihedron)
99 : SUIT_ViewModel(),
100   myBackgrounds(4, Qtx::BackgroundData( Qt::black )),
101   myIsRelative(true),
102   myTopLayerId( 0 ),
103   myTrihedronSize(100),
104   myClippingDlg (NULL)
105 {
106   // init CasCade viewers
107   myV3dViewer = OCCViewer_VService::CreateViewer( TCollection_ExtendedString("Viewer3d").ToExtString() );
108   //myV3dViewer->Init(); // to avoid creation of the useless perspective view (see OCCT issue 0024267)
109   myV3dViewer->SetDefaultLights();
110
111 #if OCC_VERSION_LARGE <= 0x06060000 // Porting to OCCT higher 6.6.0 version
112   myV3dCollector = OCCViewer_VService::CreateViewer( TCollection_ExtendedString("Collector3d").ToExtString() );
113   //myV3dCollector->Init(); // to avoid creation of the useless perspective view (see OCCT issue 0024267)
114   myV3dCollector->SetDefaultLights();
115 #endif
116
117   // init selector
118 #if OCC_VERSION_LARGE <= 0x06060000 
119   myAISContext = new AIS_InteractiveContext( myV3dViewer, myV3dCollector );
120 #else
121   myAISContext = new AIS_InteractiveContext( myV3dViewer );
122 #endif
123   myAISContext->SelectionColor( Quantity_NOC_WHITE );
124   
125   // display isoline on planar faces (box for ex.)
126   myAISContext->IsoOnPlane( true );
127   
128   /* create trihedron */
129   if ( DisplayTrihedron )
130   {
131     Handle(Geom_Axis2Placement) anAxis = new Geom_Axis2Placement(gp::XOY());
132     myTrihedron = new AIS_Trihedron(anAxis);
133     myTrihedron->SetInfiniteState( Standard_True );
134
135     Quantity_Color Col(193/255., 205/255., 193/255., Quantity_TOC_RGB);
136     //myTrihedron->SetColor( Col );
137     myTrihedron->SetArrowColor( Col.Name() );
138     myTrihedron->SetSize(100);
139     Handle(AIS_Drawer) drawer = myTrihedron->Attributes();
140     if (drawer->HasDatumAspect()) {
141       Handle(Prs3d_DatumAspect) daspect = drawer->DatumAspect();
142       daspect->FirstAxisAspect()->SetColor(Quantity_Color(1.0, 0.0, 0.0, Quantity_TOC_RGB));
143       daspect->SecondAxisAspect()->SetColor(Quantity_Color(0.0, 1.0, 0.0, Quantity_TOC_RGB));
144       daspect->ThirdAxisAspect()->SetColor(Quantity_Color(0.0, 0.0, 1.0, Quantity_TOC_RGB));
145     }
146   }
147
148   // set interaction style to standard
149   myInteractionStyle = 0;
150
151   // set zooming style to standard
152   myZoomingStyle = 0;
153
154   // preselection
155   myPreselectionEnabled = true;
156
157   // selection
158   mySelectionEnabled = true;
159   myMultiSelectionEnabled = true;
160 }
161
162 /*!
163   Destructor
164 */
165 OCCViewer_Viewer::~OCCViewer_Viewer() 
166 {
167   myAISContext.Nullify();
168   myV3dViewer.Nullify();
169 #if OCC_VERSION_LARGE <= 0x06060000
170   myV3dCollector.Nullify();
171 #endif
172 }
173
174 /*!
175   [obsolete]
176   \return background color of viewer
177 */
178 QColor OCCViewer_Viewer::backgroundColor() const
179 {
180   return backgroundColor(0);
181 }
182
183 /*!
184   \return background data of viewer
185 */
186 Qtx::BackgroundData OCCViewer_Viewer::background() const
187 {
188   return background(0);
189 }
190
191 /*!
192   Sets background color [obsolete]
193   \param c - new background color
194 */
195 void OCCViewer_Viewer::setBackgroundColor( const QColor& c )
196 {
197   setBackgroundColor( 0, c );
198 }
199
200 /*!
201   Sets background data
202   \param d - new background data
203 */
204 void OCCViewer_Viewer::setBackground( const Qtx::BackgroundData& theBackground )
205 {
206   setBackground( 0, theBackground );
207 }
208
209 /*!
210   Start initialization of view window
211   \param view - view window to be initialized
212 */
213 void OCCViewer_Viewer::initView( OCCViewer_ViewWindow* view )
214 {
215   if ( view ) {
216     view->initLayout();
217     view->initSketchers();
218     view->setInteractionStyle( interactionStyle() );
219     view->setZoomingStyle( zoomingStyle() );
220     view->enablePreselection( isPreselectionEnabled() );
221     view->enableSelection( isSelectionEnabled() );
222     
223     OCCViewer_ViewPort3d* vp3d = view->getViewPort();
224     if ( vp3d )
225     {
226       vp3d->getView()->SetSurfaceDetail(V3d_TEX_ALL);
227       // connect signal from viewport
228       connect(vp3d, SIGNAL(vpClosed(OCCViewer_ViewPort3d*)), this, SLOT(onViewClosed(OCCViewer_ViewPort3d*)));
229       connect(vp3d, SIGNAL(vpMapped(OCCViewer_ViewPort3d*)), this, SLOT(onViewMapped(OCCViewer_ViewPort3d*)));
230     }
231   }
232 }
233
234 /*!
235   Creates new view window
236   \param theDesktop - main window of application
237 */
238 SUIT_ViewWindow* OCCViewer_Viewer::createView( SUIT_Desktop* theDesktop )
239 {
240   // create view frame
241   OCCViewer_ViewFrame* view = new OCCViewer_ViewFrame(theDesktop, this);
242   // get main view window (created by view frame)
243   OCCViewer_ViewWindow* vw = view->getView(OCCViewer_ViewFrame::MAIN_VIEW);
244   // initialize main view window
245   initView( vw );
246   // set default background for view window
247   vw->setBackground( background(0) ); // 0 means MAIN_VIEW (other views are not yet created here)
248
249   return view;
250 }
251
252 /*!
253   Sets new view manager
254   \param theViewManager - new view manager
255 */
256 void OCCViewer_Viewer::setViewManager(SUIT_ViewManager* theViewManager)
257 {
258   SUIT_ViewModel::setViewManager(theViewManager);
259   if (theViewManager) {
260     connect(theViewManager, SIGNAL(mousePress(SUIT_ViewWindow*, QMouseEvent*)), 
261             this, SLOT(onMousePress(SUIT_ViewWindow*, QMouseEvent*)));
262
263     connect(theViewManager, SIGNAL(mouseMove(SUIT_ViewWindow*, QMouseEvent*)), 
264             this, SLOT(onMouseMove(SUIT_ViewWindow*, QMouseEvent*)));
265
266     connect(theViewManager, SIGNAL(mouseRelease(SUIT_ViewWindow*, QMouseEvent*)), 
267             this, SLOT(onMouseRelease(SUIT_ViewWindow*, QMouseEvent*)));
268
269     connect(theViewManager, SIGNAL(keyPress(SUIT_ViewWindow*, QKeyEvent*)), 
270             this, SLOT(onKeyPress(SUIT_ViewWindow*, QKeyEvent*)));
271   }
272 }
273
274 /*!
275   SLOT: called on mouse button press, stores current mouse position as start point for transformations
276 */
277 void OCCViewer_Viewer::onMousePress(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
278 {
279   myStartPnt.setX(theEvent->x()); myStartPnt.setY(theEvent->y());
280 }
281
282 /*!
283   SLOT: called on mouse move, processes transformation or hilighting
284 */
285 void OCCViewer_Viewer::onMouseMove(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
286 {
287   if (!mySelectionEnabled) return;
288   if (!theWindow->inherits("OCCViewer_ViewWindow")) return;
289
290   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
291
292   myCurPnt.setX(theEvent->x()); myCurPnt.setY(theEvent->y());
293
294   if ( isSelectionEnabled() && isPreselectionEnabled() ) {
295     if (aView->getViewPort()->isBusy()) {
296       QCoreApplication::processEvents();
297       return; // Check that the ViewPort initialization completed
298                                                 // To Prevent call move event if the View port is not initialized
299                                                 // IPAL 20883
300     }
301     Handle(V3d_View) aView3d = aView->getViewPort()->getView();
302     if ( !aView3d.IsNull() ) {
303       myAISContext->MoveTo(theEvent->x(), theEvent->y(), aView3d);
304     }
305   }
306 }
307
308
309 /*!
310   SLOT: called on mouse button release, finishes transformation or selection
311 */
312 void OCCViewer_Viewer::onMouseRelease(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
313 {
314   if (!mySelectionEnabled) return;
315   if (theEvent->button() != Qt::LeftButton) return;
316   if (!theWindow->inherits("OCCViewer_ViewWindow")) return;
317
318   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
319   if (!aView )
320     return;
321
322   myEndPnt.setX(theEvent->x()); myEndPnt.setY(theEvent->y());
323   bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
324   
325   if (!aHasShift) emit deselection();
326
327   if (myStartPnt == myEndPnt)
328   {
329     if ( !isPreselectionEnabled() ) {
330       Handle(V3d_View) aView3d = aView->getViewPort()->getView();
331       if ( !aView3d.IsNull() ) {
332         myAISContext->MoveTo(myEndPnt.x(), myEndPnt.y(), aView3d);
333       }
334     }
335
336     if (aHasShift && myMultiSelectionEnabled)
337       myAISContext->ShiftSelect();
338     else
339       myAISContext->Select();
340   }
341   else
342   {
343     if (aHasShift && myMultiSelectionEnabled)
344       myAISContext->ShiftSelect(myStartPnt.x(), myStartPnt.y(),
345                                 myEndPnt.x(), myEndPnt.y(),
346                                 aView->getViewPort()->getView(), Standard_False );
347     else
348       myAISContext->Select(myStartPnt.x(), myStartPnt.y(),
349                            myEndPnt.x(), myEndPnt.y(),
350                            aView->getViewPort()->getView(), Standard_False );
351
352     int Nb = myAISContext->NbSelected();
353     if( Nb>1 && !myMultiSelectionEnabled )
354     {
355         myAISContext->InitSelected();
356         Handle( SelectMgr_EntityOwner ) anOwner = myAISContext->SelectedOwner();
357         if( !anOwner.IsNull() )
358         {
359             myAISContext->ClearSelected( Standard_False );
360             myAISContext->AddOrRemoveSelected( anOwner, Standard_False );
361         }
362     }
363
364     myAISContext->UpdateCurrentViewer();
365   }
366   emit selectionChanged();
367 }
368
369 /*!
370   SLOT: called on key press, processes selection in "key free" interaction style
371 */
372 void OCCViewer_Viewer::onKeyPress(SUIT_ViewWindow* theWindow, QKeyEvent* theEvent)
373 {
374   if (!mySelectionEnabled) return;
375   if (theEvent->key() != Qt::Key_S) return;
376   if (!theWindow->inherits("OCCViewer_ViewWindow")) return;
377
378   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
379   if (!aView || aView->interactionStyle() != SUIT_ViewModel::KEY_FREE)
380     return;
381
382   emit deselection();
383
384   if ( !isPreselectionEnabled() ) {
385     Handle(V3d_View) aView3d = aView->getViewPort()->getView();
386     if ( !aView3d.IsNull() ) {
387       myAISContext->MoveTo(myCurPnt.x(), myCurPnt.y(), aView3d);
388     }
389   }
390
391   myAISContext->Select();
392
393   emit selectionChanged();
394 }
395
396 void OCCViewer_Viewer::onViewClosed(OCCViewer_ViewPort3d*)
397 {
398   Standard_Integer aViewsNb = 0;
399   for ( myV3dViewer->InitActiveViews(); myV3dViewer->MoreActiveViews(); myV3dViewer->NextActiveViews())
400     ++aViewsNb;
401   if ( aViewsNb < 2 ) {
402     //clean up presentations before last view is closed
403     myAISContext->RemoveAll(Standard_False);
404   }
405 }
406
407 void OCCViewer_Viewer::onViewMapped(OCCViewer_ViewPort3d* viewPort)
408 {
409   setTrihedronShown( true );
410   bool showStaticTrihedron = true;
411   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
412   if ( resMgr ) showStaticTrihedron = resMgr->booleanValue( "3DViewer", "show_static_trihedron", true );
413   viewPort->showStaticTrihedron( showStaticTrihedron );
414 }
415
416 int OCCViewer_Viewer::getTopLayerId()
417 {
418 #if OCC_VERSION_LARGE > 0x06050200
419   if ( myTopLayerId == 0 && !myAISContext->CurrentViewer().IsNull() )    
420     myAISContext->CurrentViewer()->AddZLayer( myTopLayerId );
421 #endif
422
423   return myTopLayerId;
424 }
425
426 /*!
427   \return interaction style
428 */
429 int OCCViewer_Viewer::interactionStyle() const
430 {
431   return myInteractionStyle;
432 }
433
434 /*!
435   Sets interaction style: 0 - standard, 1 - keyboard free interaction
436   \param theStyle - new interaction style
437 */
438 void OCCViewer_Viewer::setInteractionStyle( const int theStyle )
439 {
440   myInteractionStyle = theStyle;
441   //!! To be done for view windows
442   if ( !myViewManager )
443     return;
444
445   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
446   for ( int i = 0; i < (int)wins.count(); i++ )
447   {
448     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
449     if ( win )
450       win->setInteractionStyle( theStyle );
451   }
452 }
453
454 /*!
455   \return zooming style
456 */
457 int OCCViewer_Viewer::zoomingStyle() const
458 {
459   return myZoomingStyle;
460 }
461
462 /*!
463   Sets zooming style: 0 - standard, 1 - advanced (at cursor)
464   \param theStyle - new zooming style
465 */
466 void OCCViewer_Viewer::setZoomingStyle( const int theStyle )
467 {
468   myZoomingStyle = theStyle;
469   //!! To be done for view windows
470   if ( !myViewManager )
471     return;
472
473   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
474   for ( int i = 0; i < (int)wins.count(); i++ )
475   {
476     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
477     if ( win )
478       win->setZoomingStyle( theStyle );
479   }
480 }
481
482 /*!
483   \return true if preselection is enabled
484 */
485 bool OCCViewer_Viewer::isPreselectionEnabled() const 
486
487   return myPreselectionEnabled; 
488 }
489
490 /*!
491   Enables/disables preselection
492   \param isEnabled - new status
493 */
494 void OCCViewer_Viewer::enablePreselection(bool isEnabled)
495 {
496   myPreselectionEnabled = isEnabled;
497
498   if ( !myViewManager )
499     return;
500
501   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
502   for ( int i = 0; i < (int)wins.count(); i++ )
503   {
504     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
505     if ( win ) {
506       win->enablePreselection( isEnabled );
507     }
508   }
509 }
510
511 /*!
512   \return true if selection is enabled
513 */
514 bool OCCViewer_Viewer::isSelectionEnabled() const 
515
516   return mySelectionEnabled; 
517 }
518
519 /*!
520   Enables/disables selection
521   \param isEnabled - new status
522 */
523 void OCCViewer_Viewer::enableSelection(bool isEnabled)
524 {
525   mySelectionEnabled = isEnabled;
526
527   //!! To be done for view windows
528   if ( !myViewManager )
529     return;
530
531   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
532   for ( int i = 0; i < (int)wins.count(); i++ )
533   {
534     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
535     if ( win ) {
536       win->updateEnabledDrawMode();
537       win->enableSelection( isEnabled );
538     }
539   }
540
541   
542   //clear current selection in the viewer
543   if(!isEnabled) {
544     myAISContext->ClearSelected( Standard_True );
545   }
546
547 }
548
549 /*!
550   Sets multiselection enabled status
551   \param isEnabled - new status
552 */
553 void OCCViewer_Viewer::enableMultiselection(bool isEnable)
554 {
555   myMultiSelectionEnabled = isEnable;
556   //!! To be done for view windows
557   if ( !myViewManager )
558     return;
559
560   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
561   for ( int i = 0; i < (int)wins.count(); i++ )
562   {
563     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
564     if ( win )
565       win->updateEnabledDrawMode();
566   }
567 }
568
569 /*!
570   Builds popup for occ viewer
571 */
572 void OCCViewer_Viewer::contextMenuPopup(QMenu* thePopup)
573 {
574   thePopup->addAction( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
575   thePopup->addAction( tr( "MEN_CHANGE_BACKGROUND" ), this, SLOT( onChangeBackground() ) );
576
577   thePopup->addSeparator();
578
579   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
580
581   //Support of several toolbars in the popup menu
582   QList<QToolBar*> lst = qFindChildren<QToolBar*>( aView );
583   QList<QToolBar*>::const_iterator it = lst.begin(), last = lst.end();
584   for ( ; it!=last; it++ ) {
585     if ( (*it)->parentWidget()->isVisible() )
586       thePopup->addAction( (*it)->toggleViewAction() );
587   }
588 }
589
590 /*!
591   SLOT: called on dump view operation is activated, stores scene to raster file
592 */
593 void OCCViewer_Viewer::onDumpView()
594 {
595   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
596   if ( aView )
597     aView->onDumpView();
598 }
599
600 /*!
601   SLOT: called if background color is to be changed changed, passes new color to view port
602 */
603 void OCCViewer_Viewer::onChangeBackground()
604 {
605   OCCViewer_ViewWindow* aView = dynamic_cast<OCCViewer_ViewWindow*>(myViewManager->getActiveView());
606   if ( !aView )
607     return;
608
609   // get supported gradient types
610   QStringList gradList;
611   QIntList    idList, txtList;
612   QString     formats = backgroundData( gradList, idList, txtList );
613
614   // invoke dialog box
615   Qtx::BackgroundData bgData = QtxBackgroundDialog::getBackground( aView->background(),  // initial background
616                                                                    aView,                // parent for dialog box
617                                                                    txtList,              // allowed texture modes
618                                                                    true,                 // enable solid color mode
619                                                                    true,                 // enable gradient mode
620                                                                    false,                // disable custom gradient mode
621                                                                    !txtList.isEmpty(),   // enable/disable texture mode
622                                                                    gradList,             // gradient names
623                                                                    idList,               // gradient identifiers
624                                                                    formats );            // image formats
625
626   // set chosen background data to the viewer
627   if ( bgData.isValid() )
628     aView->setBackground( bgData );
629 }
630
631 /*!
632   Updates OCC 3D viewer
633 */
634 void OCCViewer_Viewer::update()
635 {
636   if (!myV3dViewer.IsNull())
637     myV3dViewer->Update();
638
639   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
640   if ( aView )
641     aView->updateGravityCoords();
642 }
643
644 /*!
645   \return objects selected in 3D viewer
646   \param theList - list to be filled with selected objects
647 */
648 void OCCViewer_Viewer::getSelectedObjects(AIS_ListOfInteractive& theList)
649 {
650   theList.Clear();
651   for (myAISContext->InitSelected(); myAISContext->MoreSelected(); myAISContext->NextSelected())
652     theList.Append(myAISContext->SelectedInteractive());
653 }
654
655 /*!
656   Selects objects in 3D viewer. Other selected objects are left as selected
657   \param theList - list objects to be selected
658 */
659 void OCCViewer_Viewer::setObjectsSelected(const AIS_ListOfInteractive& theList)
660 {
661   AIS_ListIteratorOfListOfInteractive aIt;
662   for (aIt.Initialize(theList); aIt.More(); aIt.Next())
663     myAISContext->AddOrRemoveSelected(aIt.Value(), false);
664   myAISContext->UpdateCurrentViewer();
665 }
666
667 /*!
668   Auxiliary method to emit signal selectionChanged()
669 */
670 void OCCViewer_Viewer::performSelectionChanged()
671 {
672     emit selectionChanged();
673 }
674
675 /*!
676   Hilights/unhilights object in viewer
677   \param obj - object to be updated
678   \param hilight - if it is true, object will be hilighted, otherwise it will be unhilighted
679   \param update - update current viewer
680 */
681 bool OCCViewer_Viewer::highlight( const Handle(AIS_InteractiveObject)& obj,
682                                   bool hilight, bool update )
683 {
684   bool isInLocal = myAISContext->HasOpenedContext();
685   if( !obj.IsNull() )
686     if( !isInLocal )
687     {
688       if ( hilight && !myAISContext->IsSelected( obj ) )
689         myAISContext->AddOrRemoveCurrentObject( obj, false );
690       else if ( !hilight && myAISContext->IsSelected( obj ) )
691         myAISContext->AddOrRemoveCurrentObject( obj, false );
692     }
693
694   if ( update )
695     myV3dViewer->Redraw();
696     
697   return false;
698 }
699
700 /*!
701   Unhilights all objects in viewer
702   \param updateviewer - update current viewer
703 */
704 bool OCCViewer_Viewer::unHighlightAll( bool updateviewer, bool unselect )
705 {
706   if ( myAISContext->HasOpenedContext() ) {
707     if ( unselect ) {
708       myAISContext->ClearSelected( updateviewer );
709     } else {
710       myAISContext->UnhilightSelected( updateviewer );
711     }
712   } else {
713     if ( unselect ) {
714       myAISContext->ClearCurrents( updateviewer );
715     } else {
716       myAISContext->UnhilightCurrents( updateviewer );
717     }
718   }
719
720   return false;
721 }
722
723 /*!
724   \return true if object is in viewer or in collector
725   \param obj - object to be checked
726   \param onlyInViewer - search object only in viewer (so object must be displayed)
727 */
728 bool OCCViewer_Viewer::isInViewer( const Handle(AIS_InteractiveObject)& obj,
729                                    bool onlyInViewer )
730 {
731   AIS_ListOfInteractive List;
732   myAISContext->DisplayedObjects(List);
733
734 #if OCC_VERSION_LARGE <= 0x06060000
735   if( !onlyInViewer )
736   {
737     AIS_ListOfInteractive List1;
738     myAISContext->ObjectsInCollector(List1);
739     List.Append(List1);
740   }
741 #endif
742
743   AIS_ListIteratorOfListOfInteractive ite(List);
744   for ( ; ite.More(); ite.Next() )
745     if( ite.Value()==obj )
746       return true;
747
748   return false;
749 }
750
751 /*!
752   \return true if object is displayed in viewer
753   \param obj - object to be checked
754 */
755 bool OCCViewer_Viewer::isVisible( const Handle(AIS_InteractiveObject)& obj )
756 {
757   return myAISContext->IsDisplayed( obj );
758 }
759
760 /*!
761   Sets color of object
762   \param obj - object to be updated
763   \param color - new color
764   \param update - update current viewer
765 */
766 void OCCViewer_Viewer::setColor( const Handle(AIS_InteractiveObject)& obj,
767                                  const QColor& color,
768                                  bool update )
769 {
770   if( !obj.IsNull() )
771   {
772     Quantity_Color CSFColor = Quantity_Color ( color.red() / 255.,
773                                                color.green() / 255.,
774                                                color.blue() / 255.,
775                                                Quantity_TOC_RGB );
776     obj->SetColor( CSFColor );
777   }
778
779   if( update )
780     myV3dViewer->Update();
781 }
782
783 /*!
784   Changes display mode of object
785   \param obj - object to be processed
786   \param mode - new display mode
787   \param update - update current viewer
788 */
789 void OCCViewer_Viewer::switchRepresentation( const Handle(AIS_InteractiveObject)& obj,
790                                              int mode, bool update )
791 {
792   myAISContext->SetDisplayMode( obj, (Standard_Integer)mode, update );
793   if( update )
794     myV3dViewer->Update();
795 }
796
797 /*!
798   Changes transparency of object
799   \param obj - object to be processed
800   \param trans - new transparency
801   \param update - update current viewer
802 */
803 void OCCViewer_Viewer::setTransparency( const Handle(AIS_InteractiveObject)& obj,
804                                         float trans, bool update )
805 {
806   myAISContext->SetTransparency( obj, trans, false );
807   myAISContext->Redisplay( obj, Standard_False, Standard_True );
808   if( update )
809     myV3dViewer->Update();
810 }
811
812 /*!
813   Changes visibility of trihedron to opposite
814 */
815 void OCCViewer_Viewer::toggleTrihedron()
816 {
817   setTrihedronShown( !isTrihedronVisible() );
818 }
819
820 /*!
821   \return true if trihedron is visible
822 */
823 bool OCCViewer_Viewer::isTrihedronVisible() const
824 {
825   return !myTrihedron.IsNull() && !myAISContext.IsNull() && myAISContext->IsDisplayed( myTrihedron );
826 }
827
828 /*!
829   Sets visibility state of trihedron
830   \param on - new state
831 */
832
833 void OCCViewer_Viewer::setTrihedronShown( const bool on )
834 {
835   if ( myTrihedron.IsNull() )
836     return;
837
838   if ( on ) {
839     myAISContext->Display( myTrihedron );
840     myAISContext->Deactivate(myTrihedron);
841   }
842   else {
843     myAISContext->Erase( myTrihedron );
844   }
845 }
846
847 /*!
848   \return trihedron size
849 */
850 double OCCViewer_Viewer::trihedronSize() const
851 {
852   double sz = 0;
853   if ( !myTrihedron.IsNull() )
854     sz = myTrihedron->Size();
855   return sz;
856 }
857
858 /*!
859   Changes trihedron size
860   \param sz - new size
861 */
862 void OCCViewer_Viewer::setTrihedronSize( const double sz, bool isRelative )
863 {
864   if ( myTrihedronSize != sz || isRelative != myIsRelative) {
865     myTrihedronSize = sz; 
866     myIsRelative = isRelative;
867     updateTrihedron();
868   }
869 }
870
871 /*!
872   Set number of isolines
873   \param u - u-isolines (first parametric co-ordinate)
874   \param v - v-isolines (second parametric co-ordinate)
875 */
876 void OCCViewer_Viewer::setIsos( const int u, const int v )
877 {
878   Handle(AIS_InteractiveContext) ic = getAISContext();
879   if ( ic.IsNull() )
880   return;
881
882   ic->SetIsoNumber( u, AIS_TOI_IsoU );
883   ic->SetIsoNumber( v, AIS_TOI_IsoV );
884 }
885
886 /*!
887   \return number of isolines
888   \param u - to return u-isolines (first parametric co-ordinate)
889   \param v - to return v-isolines (second parametric co-ordinate)
890 */
891 void OCCViewer_Viewer::isos( int& u, int& v ) const
892 {
893   Handle(AIS_InteractiveContext) ic = getAISContext();
894   if ( !ic.IsNull() )
895   {
896     u = ic->IsoNumber( AIS_TOI_IsoU );
897     v = ic->IsoNumber( AIS_TOI_IsoV );
898   }
899 }
900
901 /* 
902  * Returns a new OCCViewer_ViewWindow instance which will be placed as a sub window in ViewFrame
903  */
904 OCCViewer_ViewWindow* OCCViewer_Viewer::createSubWindow()
905 {
906   return new OCCViewer_ViewWindow(0,  this);
907 }
908
909 // obsolete  
910 QColor OCCViewer_Viewer::backgroundColor( int theViewId ) const
911 {
912   return background( theViewId ).color();
913 }
914
915 Qtx::BackgroundData OCCViewer_Viewer::background( int theViewId ) const
916 {
917   return ( theViewId >= 0 && theViewId < myBackgrounds.count() ) ? myBackgrounds[theViewId] : Qtx::BackgroundData();
918 }
919
920 // obsolete
921 void OCCViewer_Viewer::setBackgroundColor( int theViewId, const QColor& theColor )
922 {
923   if ( theColor.isValid() ) {
924     Qtx::BackgroundData bg = background( theViewId );
925     bg.setColor( theColor );
926     setBackground( theViewId, bg );
927   }
928 }
929
930 void OCCViewer_Viewer::setBackground( int theViewId, const Qtx::BackgroundData& theBackground )
931 {
932   if ( theBackground.isValid() && theViewId >= 0 && theViewId < myBackgrounds.count() )
933     myBackgrounds[theViewId] = theBackground;    
934 }
935
936
937 /*!
938   Set the show static trihedron flag
939 */
940 void OCCViewer_Viewer::setStaticTrihedronDisplayed(const bool on)
941 {
942   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
943   if ( aView ) aView->showStaticTrihedron( on );
944 }
945
946 /*!
947   Get new and current trihedron size corresponding to the current model size
948 */
949 bool OCCViewer_Viewer::computeTrihedronSize( double& theNewSize, double& theSize )
950 {
951   theNewSize = 100;
952   theSize = 100;
953
954   //SRN: BUG IPAL8996, a usage of method ActiveView without an initialization
955   Handle(V3d_Viewer) viewer = getViewer3d();
956   viewer->InitActiveViews();
957   if(!viewer->MoreActiveViews()) return false;
958
959   Handle(V3d_View) view3d = viewer->ActiveView();
960   //SRN: END of fix
961
962   if ( view3d.IsNull() )
963     return false;
964
965   double aMaxSide = computeSceneSize( view3d );
966
967   // IPAL21687
968   // The boundary box of the view may be initialized but nullified
969   // (case of infinite objects)
970   if ( aMaxSide < Precision::Confusion() )
971     return false;
972
973   float aSizeInPercents = SUIT_Session::session()->resourceMgr()->doubleValue("3DViewer","trihedron_size", 100.);
974
975   static float EPS = 5.0E-3;
976   theSize = getTrihedron()->Size();
977   theNewSize = aMaxSide*aSizeInPercents / 100.0;
978
979   return fabs( theNewSize - theSize ) > theSize    * EPS ||
980          fabs( theNewSize - theSize ) > theNewSize * EPS;
981 }
982
983 /*!
984  * Compute scene size
985  */
986 double OCCViewer_Viewer::computeSceneSize(const Handle(V3d_View)& view3d) const
987 {
988   double aMaxSide = 0;
989   double Xmin = 0, Ymin = 0, Zmin = 0, Xmax = 0, Ymax = 0, Zmax = 0;
990
991   view3d->View()->MinMaxValues( Xmin, Ymin, Zmin, Xmax, Ymax, Zmax );
992
993   if ( Xmin != RealFirst() && Ymin != RealFirst() && Zmin != RealFirst() &&
994        Xmax != RealLast()  && Ymax != RealLast()  && Zmax != RealLast() )
995   {
996     aMaxSide = Xmax - Xmin;
997     if ( aMaxSide < Ymax -Ymin ) aMaxSide = Ymax -Ymin;
998     if ( aMaxSide < Zmax -Zmin ) aMaxSide = Zmax -Zmin;
999   }
1000
1001   return aMaxSide;
1002 }
1003
1004 /*! 
1005  * Update the size of the trihedron
1006  */
1007 void OCCViewer_Viewer::updateTrihedron() {
1008   if ( myTrihedron.IsNull() )
1009     return;
1010
1011   if(myIsRelative){
1012     double newSz, oldSz;
1013     
1014     if(computeTrihedronSize(newSz, oldSz))
1015       myTrihedron->SetSize(newSz);
1016     
1017   } else if(myTrihedron->Size() != myTrihedronSize) {
1018     myTrihedron->SetSize(myTrihedronSize);
1019   }
1020 }
1021
1022 /*!
1023   Set number of isolines
1024   \param u - u-isolines (first parametric co-ordinate)
1025   \param v - v-isolines (second parametric co-ordinate)
1026 */
1027 void OCCViewer_Viewer::setSelectionOptions( bool isPreselectionEnabled, bool isSelectionEnabled )
1028 {
1029   myPreselectionEnabled = isPreselectionEnabled;
1030   mySelectionEnabled = isSelectionEnabled;
1031   //clear current selection in the viewer
1032   
1033   if(!mySelectionEnabled) {
1034     myAISContext->ClearSelected( Standard_True );
1035   }
1036 }
1037
1038 /*!
1039   Creates clipping plane based on the incoming plane
1040 */
1041 Handle(Graphic3d_ClipPlane) OCCViewer_Viewer::createClipPlane(const gp_Pln& thePlane, const Standard_Boolean theIsOn)
1042 {
1043   Handle(Graphic3d_ClipPlane) aGraphic3dPlane = new Graphic3d_ClipPlane( thePlane );
1044   aGraphic3dPlane->SetOn( theIsOn );
1045   aGraphic3dPlane->SetCapping( Standard_True );
1046
1047   // load capping texture
1048   QPixmap px( ":images/hatch.png" );
1049   if( !px.isNull() ) {
1050     const Handle(Image_PixMap) aPixmap = imageToPixmap( px.toImage() );
1051     Handle(Graphic3d_Texture2Dmanual) aTexture = new Graphic3d_Texture2Dmanual( aPixmap );
1052     if( aTexture->IsDone() ) {
1053       aTexture->EnableModulate();
1054       aTexture->EnableRepeat();
1055       aTexture->GetParams()->SetScale( Graphic3d_Vec2( 0.01, 0.01 ) );
1056       aGraphic3dPlane->SetCappingTexture( aTexture );
1057     }
1058   }
1059   return aGraphic3dPlane;
1060 }
1061 /*!
1062   Applies clipping planes to clippable objects
1063 */
1064 void OCCViewer_Viewer::setClipPlanes(ClipPlanesList theList)
1065 {
1066   // 1. Remove existing clipping planes
1067   myClipPlanes.clear();
1068   myInternalClipPlanes.Clear();
1069
1070   // 2. Create new clipping planes
1071   ClipPlanesList::iterator inIt = theList.begin();
1072   for (;inIt != theList.end(); inIt++ )
1073   {
1074     OCCViewer_ClipPlane aPlane = *inIt;
1075
1076     double aDx = 0.0, aDy = 0.0, aDz = 0.0;
1077     aPlane.OrientationToXYZ( aDx, aDy, aDz );
1078
1079     gp_Pnt anOrigin( aPlane.X, aPlane.Y, aPlane.Z );
1080     gp_Dir aDirection( aDx, aDy, aDz );
1081
1082     myInternalClipPlanes.Append( createClipPlane( gp_Pln( anOrigin, aDirection ), aPlane.IsOn ) );
1083     myClipPlanes.push_back( aPlane );
1084   }
1085
1086   // 3. Apply clipping planes
1087   AIS_ListOfInteractive aList;
1088   myAISContext->DisplayedObjects (aList);
1089   for ( AIS_ListIteratorOfListOfInteractive anIter (aList); anIter.More(); anIter.Next() ) {
1090     Handle(AIS_InteractiveObject) anObj = anIter.Value();
1091     Handle(ViewerData_AISShape) aShape = Handle(ViewerData_AISShape)::DownCast (anObj);
1092     if (!aShape.IsNull() && aShape->IsClippable()) {
1093       aShape->SetClipPlanes(myInternalClipPlanes);
1094     }
1095   }
1096 }
1097
1098 /*!
1099   Returns the clipping planes applied to the displayed objects.
1100 */
1101 ClipPlanesList OCCViewer_Viewer::getClipPlanes() const {
1102   return myClipPlanes;
1103 }
1104 /*!
1105   Applies clipping planes to given object objects
1106 */
1107 void OCCViewer_Viewer::applyExistingClipPlanesToObject (const Handle(AIS_InteractiveObject)& theObject)
1108 {
1109   Handle(ViewerData_AISShape) aShape = Handle(ViewerData_AISShape)::DownCast (theObject);
1110   if (!aShape.IsNull() && aShape->IsClippable())
1111   {
1112     aShape->SetClipPlanes (myInternalClipPlanes);
1113   }
1114 }
1115
1116 /*!
1117   Returns the pointer to the clipping dialog box.
1118 */
1119 OCCViewer_ClippingDlg* OCCViewer_Viewer::getClippingDlg() const{
1120   return myClippingDlg;
1121 }
1122
1123
1124 /*!
1125   Stores pointer to the clipping dialog box.
1126 */
1127 void OCCViewer_Viewer::setClippingDlg(OCCViewer_ClippingDlg* theDlg) {
1128   if(myClippingDlg != theDlg) {
1129     myClippingDlg = theDlg;
1130   }
1131 }