0024307: TKOpenGl - efficient culling of large number of presentations
[occt.git] / src / ViewerTest / ViewerTest_ViewerCommands.cxx
1 // Created on: 1998-09-01
2 // Created by: Robert COUBLANC
3 // Copyright (c) 1998-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 #ifdef HAVE_CONFIG_H
18   #include <config.h>
19 #endif
20
21 #include <OpenGl_GlCore20.hxx>
22 #include <AIS_Shape.hxx>
23 #include <AIS_Drawer.hxx>
24 #include <AIS_InteractiveObject.hxx>
25 #include <AIS_ListOfInteractive.hxx>
26 #include <AIS_ListIteratorOfListOfInteractive.hxx>
27 #include <DBRep.hxx>
28 #include <Graphic3d_AspectMarker3d.hxx>
29 #include <Graphic3d_ExportFormat.hxx>
30 #include <Graphic3d_NameOfTextureEnv.hxx>
31 #include <Graphic3d_TextureEnv.hxx>
32 #include <Graphic3d_TextureParams.hxx>
33 #include <Graphic3d_TypeOfTextureFilter.hxx>
34 #include <Graphic3d_AspectFillArea3d.hxx>
35 #include <ViewerTest.hxx>
36 #include <ViewerTest_EventManager.hxx>
37 #include <ViewerTest_DoubleMapOfInteractiveAndName.hxx>
38 #include <ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName.hxx>
39 #include <Visual3d_View.hxx>
40 #include <Visual3d_ViewManager.hxx>
41 #include <V3d_AmbientLight.hxx>
42 #include <V3d_DirectionalLight.hxx>
43 #include <V3d_LayerMgr.hxx>
44 #include <V3d_LayerMgrPointer.hxx>
45 #include <V3d_PositionalLight.hxx>
46 #include <V3d_SpotLight.hxx>
47 #include <NCollection_DoubleMap.hxx>
48 #include <NCollection_List.hxx>
49 #include <NCollection_Vector.hxx>
50 #include <NIS_View.hxx>
51 #include <NIS_Triangulated.hxx>
52 #include <NIS_InteractiveContext.hxx>
53 #include <AIS_InteractiveContext.hxx>
54 #include <Draw_Interpretor.hxx>
55 #include <Draw.hxx>
56 #include <Draw_Appli.hxx>
57 #include <Aspect_PrintAlgo.hxx>
58 #include <Image_AlienPixMap.hxx>
59 #include <OpenGl_GraphicDriver.hxx>
60 #include <OSD_Timer.hxx>
61 #include <TColStd_HSequenceOfAsciiString.hxx>
62 #include <TColStd_SequenceOfInteger.hxx>
63 #include <TColStd_HSequenceOfReal.hxx>
64 #include <TColgp_Array1OfPnt2d.hxx>
65 #include <TColStd_MapOfAsciiString.hxx>
66 #include <Visual3d_LayerItem.hxx>
67 #include <Aspect_TypeOfLine.hxx>
68 #include <Image_Diff.hxx>
69 #include <Aspect_DisplayConnection.hxx>
70 #include <Graphic3d.hxx>
71 #include <gp_Pnt.hxx>
72 #include <gp_Dir.hxx>
73 #include <gp_Pln.hxx>
74 #include <PrsMgr_PresentableObject.hxx>
75 #include <Graphic3d_ClipPlane.hxx>
76 #include <NCollection_DataMap.hxx>
77 #include <Graphic3d_Texture2Dmanual.hxx>
78 #include <Prs3d_ShadingAspect.hxx>
79
80 #ifdef WNT
81 #undef DrawText
82 #endif
83
84 #include <Visual3d_Layer.hxx>
85 #include <cstdlib>
86
87 #if defined(_WIN32)
88   #include <WNT_WClass.hxx>
89   #include <WNT_Window.hxx>
90
91   #if defined(_MSC_VER)
92     #define _CRT_SECURE_NO_DEPRECATE
93     #pragma warning (disable:4996)
94   #endif
95 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
96   #include <Cocoa_Window.hxx>
97 #else
98   #include <Xw_Window.hxx>
99   #include <X11/Xlib.h> /* contains some dangerous #defines such as Status, True etc. */
100   #include <X11/Xutil.h>
101   #include <tk.h>
102 #endif
103
104 // Auxiliary definitions
105 static const char THE_KEY_DELETE = 127;
106
107 //==============================================================================
108 //  VIEWER GLOBAL VARIABLES
109 //==============================================================================
110
111 Standard_IMPORT Standard_Boolean Draw_VirtualWindows;
112 Standard_IMPORT Standard_Boolean Draw_Interprete (const char* theCommand);
113
114 Standard_EXPORT int ViewerMainLoop(Standard_Integer , const char** argv);
115 extern const Handle(NIS_InteractiveContext)& TheNISContext();
116 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
117
118 extern int VErase (Draw_Interpretor& theDI,
119                    Standard_Integer  theArgNb,
120                    const char**      theArgVec);
121
122 #if defined(_WIN32)
123 static Handle(WNT_Window)& VT_GetWindow() {
124   static Handle(WNT_Window) WNTWin;
125   return WNTWin;
126 }
127 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
128 static Handle(Cocoa_Window)& VT_GetWindow()
129 {
130   static Handle(Cocoa_Window) aWindow;
131   return aWindow;
132 }
133 extern void ViewerTest_SetCocoaEventManagerView (const Handle(Cocoa_Window)& theWindow);
134 extern void SetCocoaWindowTitle (const Handle(Cocoa_Window)& theWindow, Standard_CString theTitle);
135 extern void GetCocoaScreenResolution (Standard_Integer& theWidth, Standard_Integer& theHeight);
136
137 #else
138 static Handle(Xw_Window)& VT_GetWindow(){
139   static Handle(Xw_Window) XWWin;
140   return XWWin;
141 }
142
143 static void VProcessEvents(ClientData,int);
144 #endif
145
146 static Handle(Aspect_DisplayConnection)& GetDisplayConnection()
147 {
148   static Handle(Aspect_DisplayConnection) aDisplayConnection;
149   return aDisplayConnection;
150 }
151
152 static void SetDisplayConnection (const Handle(Aspect_DisplayConnection)& theDisplayConnection)
153 {
154   GetDisplayConnection() = theDisplayConnection;
155 }
156
157 #if defined(_WIN32) || (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
158 Aspect_Handle GetWindowHandle(const Handle(Aspect_Window)& theWindow)
159 {
160   Aspect_Handle aWindowHandle = (Aspect_Handle)NULL;
161 #if defined(_WIN32)
162   const Handle (WNT_Window) aWindow = Handle(WNT_Window)::DownCast (theWindow);
163   if (!aWindow.IsNull())
164     return aWindow->HWindow();
165 #elif (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
166   const Handle (Xw_Window) aWindow = Handle(Xw_Window)::DownCast (theWindow);
167   if (!aWindow.IsNull())
168   return aWindow->XWindow();
169 #endif
170   return aWindowHandle;
171 }
172 #endif
173
174 static Standard_Boolean MyHLRIsOn = Standard_False;
175
176 NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)> ViewerTest_myViews;
177 static NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>  ViewerTest_myContexts;
178 static NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)> ViewerTest_myDrivers;
179 static OpenGl_Caps ViewerTest_myDefaultCaps;
180
181 #define ZCLIPWIDTH 1.
182
183 static void OSWindowSetup();
184
185 //==============================================================================
186 //  EVENT GLOBAL VARIABLES
187 //==============================================================================
188
189 static int Start_Rot = 0;
190 static int ZClipIsOn = 0;
191 int X_Motion = 0; // Current cursor position
192 int Y_Motion = 0;
193 int X_ButtonPress = 0; // Last ButtonPress position
194 int Y_ButtonPress = 0;
195 Standard_Boolean IsDragged = Standard_False;
196 Standard_Boolean DragFirst = Standard_False;
197
198 //==============================================================================
199
200 #ifdef WNT
201 static LRESULT WINAPI ViewerWindowProc(
202                                        HWND hwnd,
203                                        UINT uMsg,
204                                        WPARAM wParam,
205                                        LPARAM lParam );
206 static LRESULT WINAPI AdvViewerWindowProc(
207   HWND hwnd,
208   UINT uMsg,
209   WPARAM wParam,
210   LPARAM lParam );
211 #endif
212
213
214 //==============================================================================
215 //function : WClass
216 //purpose  :
217 //==============================================================================
218
219 const Handle(MMgt_TShared)& ViewerTest::WClass()
220 {
221   static Handle(MMgt_TShared) theWClass;
222 #if defined(_WIN32)
223   if (theWClass.IsNull())
224   {
225     theWClass = new WNT_WClass ("GW3D_Class", AdvViewerWindowProc,
226       CS_VREDRAW | CS_HREDRAW, 0, 0,
227       ::LoadCursor (NULL, IDC_ARROW));
228   }
229 #endif
230   return theWClass;
231 }
232
233 //==============================================================================
234 //function : CreateName
235 //purpose  : Create numerical name for new object in theMap
236 //==============================================================================
237 template <typename ObjectType>
238 TCollection_AsciiString CreateName (const NCollection_DoubleMap <TCollection_AsciiString, ObjectType>& theObjectMap,
239                                     const TCollection_AsciiString& theDefaultString)
240 {
241   if (theObjectMap.IsEmpty())
242     return theDefaultString + TCollection_AsciiString(1);
243
244   Standard_Integer aNextKey = 1;
245   Standard_Boolean isFound = Standard_False;
246   while (!isFound)
247   {
248     TCollection_AsciiString aStringKey = theDefaultString + TCollection_AsciiString(aNextKey);
249     // Look for objects with default names
250     if (theObjectMap.IsBound1(aStringKey))
251     {
252       aNextKey++;
253     }
254     else
255       isFound = Standard_True;
256   }
257
258   return theDefaultString + TCollection_AsciiString(aNextKey);
259 }
260
261 //==============================================================================
262 //structure : ViewerTest_Names
263 //purpose   : Allow to operate with full view name: driverName/viewerName/viewName
264 //==============================================================================
265 struct ViewerTest_Names
266 {
267 private:
268   TCollection_AsciiString myDriverName;
269   TCollection_AsciiString myViewerName;
270   TCollection_AsciiString myViewName;
271
272 public:
273
274   const TCollection_AsciiString& GetDriverName () const
275   {
276     return myDriverName;
277   }
278   void SetDriverName (const TCollection_AsciiString& theDriverName)
279   {
280     myDriverName = theDriverName;
281   }
282   const TCollection_AsciiString& GetViewerName () const
283   {
284     return myViewerName;
285   }
286   void SetViewerName (const TCollection_AsciiString& theViewerName)
287   {
288     myViewerName = theViewerName;
289   }
290   const TCollection_AsciiString& GetViewName () const
291   {
292     return myViewName;
293   }
294   void SetViewName (const TCollection_AsciiString& theViewName)
295   {
296     myViewName = theViewName;
297   }
298
299   //===========================================================================
300   //function : Constructor for ViewerTest_Names
301   //purpose  : Get view, viewer, driver names from custom string
302   //===========================================================================
303
304   ViewerTest_Names (const TCollection_AsciiString& theInputString)
305   {
306     TCollection_AsciiString aName(theInputString);
307     if (theInputString.IsEmpty())
308     {
309       // Get current configuration
310       if (ViewerTest_myDrivers.IsEmpty())
311         myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
312           (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
313       else
314         myDriverName = ViewerTest_myDrivers.Find2
315         (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
316
317       if(ViewerTest_myContexts.IsEmpty())
318       {
319         myViewerName = CreateName <Handle(AIS_InteractiveContext)>
320           (ViewerTest_myContexts, TCollection_AsciiString (myDriverName + "/Viewer"));
321       }
322       else
323         myViewerName = ViewerTest_myContexts.Find2 (ViewerTest::GetAISContext());
324
325         myViewName = CreateName <Handle(V3d_View)>
326           (ViewerTest_myViews, TCollection_AsciiString(myViewerName + "/View"));
327     }
328     else
329     {
330       // There is at least view name
331       Standard_Integer aParserNumber = 0;
332       for (Standard_Integer i = 0; i < 3; ++i)
333       {
334         Standard_Integer aParserPos = aName.SearchFromEnd("/");
335         if(aParserPos != -1)
336         {
337           aParserNumber++;
338           aName.Split(aParserPos-1);
339         }
340         else
341           break;
342       }
343       if (aParserNumber == 0)
344       {
345         // Only view name
346         if (!ViewerTest::GetAISContext().IsNull())
347         {
348           myDriverName = ViewerTest_myDrivers.Find2
349           (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
350           myViewerName = ViewerTest_myContexts.Find2
351           (ViewerTest::GetAISContext());
352         }
353         else
354         {
355           // There is no opened contexts here, need to create names for viewer and driver
356           myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
357             (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
358
359           myViewerName = CreateName <Handle(AIS_InteractiveContext)>
360             (ViewerTest_myContexts, TCollection_AsciiString (myDriverName + "/Viewer"));
361         }
362         myViewName = TCollection_AsciiString(myViewerName + "/" + theInputString);
363       }
364       else if (aParserNumber == 1)
365       {
366         // Here is viewerName/viewName
367         if (!ViewerTest::GetAISContext().IsNull())
368           myDriverName = ViewerTest_myDrivers.Find2
369           (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
370         else
371         {
372           // There is no opened contexts here, need to create name for driver
373           myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
374             (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
375         }
376         myViewerName = TCollection_AsciiString(myDriverName + "/" + aName);
377
378         myViewName = TCollection_AsciiString(myDriverName + "/" + theInputString);
379       }
380       else
381       {
382         //Here is driverName/viewerName/viewName
383         myDriverName = TCollection_AsciiString(aName);
384
385         TCollection_AsciiString aViewerName(theInputString);
386         aViewerName.Split(aViewerName.SearchFromEnd("/") - 1);
387         myViewerName = TCollection_AsciiString(aViewerName);
388
389         myViewName = TCollection_AsciiString(theInputString);
390       }
391     }
392   }
393 };
394
395 //==============================================================================
396 //function : FindContextByView
397 //purpose  : Find AIS_InteractiveContext by View
398 //==============================================================================
399
400 Handle(AIS_InteractiveContext) FindContextByView (const Handle(V3d_View)& theView)
401 {
402   Handle(AIS_InteractiveContext) anAISContext;
403
404   for (NCollection_DoubleMap<TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
405        anIter (ViewerTest_myContexts); anIter.More(); anIter.Next())
406   {
407     if (anIter.Value()->CurrentViewer() == theView->Viewer())
408        return anIter.Key2();
409   }
410   return anAISContext;
411 }
412
413
414 //==============================================================================
415 //function : SetWindowTitle
416 //purpose  : Set window title
417 //==============================================================================
418
419 void SetWindowTitle (const Handle(Aspect_Window)& theWindow,
420                      Standard_CString theTitle)
421 {
422 #if defined(_WIN32)
423   SetWindowText ((HWND)Handle(WNT_Window)::DownCast(theWindow)->HWindow(),
424     theTitle);
425 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
426   SetCocoaWindowTitle (Handle(Cocoa_Window)::DownCast(theWindow), theTitle);
427 #else
428   if(GetDisplayConnection()->GetDisplay())
429   {
430     Window aWindow =
431       Handle(Xw_Window)::DownCast(theWindow)->XWindow();
432     XStoreName (GetDisplayConnection()->GetDisplay(), aWindow , theTitle);
433   }
434 #endif
435 }
436
437 //==============================================================================
438 //function : IsWindowOverlapped
439 //purpose  : Check if theWindow overlapp another view
440 //==============================================================================
441
442 Standard_Boolean IsWindowOverlapped (const Standard_Integer thePxLeft,
443                                      const Standard_Integer thePxTop,
444                                      const Standard_Integer thePxRight,
445                                      const Standard_Integer thePxBottom,
446                                      TCollection_AsciiString& theViewId)
447 {
448   for(NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)>::Iterator
449       anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
450   {
451     Standard_Integer aTop = 0,
452       aLeft = 0,
453       aRight = 0,
454       aBottom = 0;
455     anIter.Value()->Window()->Position(aLeft, aTop, aRight, aBottom);
456     if ((thePxLeft >= aLeft && thePxLeft <= aRight && thePxTop >= aTop && thePxTop <= aBottom) ||
457         (thePxLeft >= aLeft && thePxLeft <= aRight && thePxBottom >= aTop && thePxBottom <= aBottom) ||
458         (thePxRight >= aLeft && thePxRight <= aRight && thePxTop >= aTop && thePxTop <= aBottom) ||
459         (thePxRight >= aLeft && thePxRight <= aRight && thePxBottom >= aTop && thePxBottom <= aBottom))
460     {
461       theViewId = anIter.Key1();
462       return Standard_True;
463     }
464   }
465   return Standard_False;
466 }
467
468 // Workaround: to create and delete non-orthographic views outside ViewerTest
469 void ViewerTest::RemoveViewName (const TCollection_AsciiString& theName)
470 {
471   ViewerTest_myViews.UnBind1 (theName);
472 }
473
474 void ViewerTest::InitViewName (const TCollection_AsciiString& theName,
475                                const Handle(V3d_View)& theView)
476 {
477   ViewerTest_myViews.Bind (theName, theView);
478 }
479
480 TCollection_AsciiString ViewerTest::GetCurrentViewName ()
481 {
482   return ViewerTest_myViews.Find2( ViewerTest::CurrentView());
483 }
484 //==============================================================================
485 //function : ViewerInit
486 //purpose  : Create the window viewer and initialize all the global variable
487 //==============================================================================
488
489 TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft,
490                                                 const Standard_Integer thePxTop,
491                                                 const Standard_Integer thePxWidth,
492                                                 const Standard_Integer thePxHeight,
493                                                 Standard_CString theViewName,
494                                                 Standard_CString theDisplayName)
495 {
496   // Default position and dimension of the viewer window.
497   // Note that left top corner is set to be sufficiently small to have
498   // window fit in the small screens (actual for remote desktops, see #23003).
499   // The position corresponds to the window's client area, thus some
500   // gap is added for window frame to be visible.
501   Standard_Integer aPxLeft   = 20;
502   Standard_Integer aPxTop    = 40;
503   Standard_Integer aPxWidth  = 409;
504   Standard_Integer aPxHeight = 409;
505   Standard_Boolean toCreateViewer = Standard_False;
506
507   Handle(OpenGl_GraphicDriver) aGraphicDriver;
508   ViewerTest_Names aViewNames(theViewName);
509   if (ViewerTest_myViews.IsBound1 (aViewNames.GetViewName ()))
510     aViewNames.SetViewName (aViewNames.GetViewerName() + "/" + CreateName<Handle(V3d_View)>(ViewerTest_myViews, "View"));
511
512   if (thePxLeft != 0)
513     aPxLeft = thePxLeft;
514   if (thePxTop != 0)
515     aPxTop = thePxTop;
516   if (thePxWidth != 0)
517     aPxWidth = thePxWidth;
518   if (thePxHeight != 0)
519     aPxHeight = thePxHeight;
520
521   // Get graphic driver (create it or get from another view)
522   if (!ViewerTest_myDrivers.IsBound1 (aViewNames.GetDriverName()))
523   {
524     // Get connection string
525   #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
526     TCollection_AsciiString aDisplayName(theDisplayName);
527     if (!aDisplayName.IsEmpty())
528       SetDisplayConnection (new Aspect_DisplayConnection ());
529     else
530       SetDisplayConnection (new Aspect_DisplayConnection (aDisplayName));
531   #else
532     (void)theDisplayName; // avoid warning on unused argument
533     SetDisplayConnection (new Aspect_DisplayConnection ());
534   #endif
535     aGraphicDriver = new OpenGl_GraphicDriver (GetDisplayConnection());
536     aGraphicDriver->ChangeOptions() = ViewerTest_myDefaultCaps;
537     ViewerTest_myDrivers.Bind (aViewNames.GetDriverName(), aGraphicDriver);
538     toCreateViewer = Standard_True;
539   }
540   else
541   {
542     aGraphicDriver = Handle(OpenGl_GraphicDriver)::DownCast (ViewerTest_myDrivers.Find1 (aViewNames.GetDriverName()));
543   }
544
545   //Dispose the window if input parameters are default
546   if (!ViewerTest_myViews.IsEmpty() && thePxLeft == 0 && thePxTop == 0)
547   {
548     Standard_Integer aTop = 0,
549                      aLeft = 0,
550                      aRight = 0,
551                      aBottom = 0,
552                      aScreenWidth = 0,
553                      aScreenHeight = 0;
554
555     // Get screen resolution
556 #if defined(_WIN32) || defined(__WIN32__)
557     RECT aWindowSize;
558     GetClientRect(GetDesktopWindow(), &aWindowSize);
559     aScreenHeight = aWindowSize.bottom;
560     aScreenWidth = aWindowSize.right;
561 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
562     GetCocoaScreenResolution (aScreenWidth, aScreenHeight);
563 #else
564     Screen *aScreen = DefaultScreenOfDisplay(GetDisplayConnection()->GetDisplay());
565     aScreenWidth = WidthOfScreen(aScreen);
566     aScreenHeight = HeightOfScreen(aScreen);
567 #endif
568
569     TCollection_AsciiString anOverlappedViewId("");
570
571     while (IsWindowOverlapped (aPxLeft, aPxTop, aPxLeft + aPxWidth, aPxTop + aPxHeight, anOverlappedViewId))
572     {
573       ViewerTest_myViews.Find1(anOverlappedViewId)->Window()->Position (aLeft, aTop, aRight, aBottom);
574
575       if (IsWindowOverlapped (aRight + 20, aPxTop, aRight + 20 + aPxWidth, aPxTop + aPxHeight, anOverlappedViewId)
576         && aRight + 2*aPxWidth + 40 > aScreenWidth)
577       {
578         if (aBottom + aPxHeight + 40 > aScreenHeight)
579         {
580           aPxLeft = 20;
581           aPxTop = 40;
582           break;
583         }
584         aPxLeft = 20;
585         aPxTop = aBottom + 40;
586       }
587       else
588         aPxLeft = aRight + 20;
589     }
590   }
591
592   // Get viewer name
593   TCollection_AsciiString aTitle("3D View - ");
594   aTitle = aTitle + aViewNames.GetViewName() + "(*)";
595
596   // Change name of current active window
597   if (!ViewerTest::CurrentView().IsNull())
598   {
599     TCollection_AsciiString aTitle("3D View - ");
600     aTitle = aTitle
601       + ViewerTest_myViews.Find2 (ViewerTest::CurrentView());
602     SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
603   }
604
605   // Create viewer
606   Handle(V3d_Viewer) a3DViewer;
607   // If it's the single view, we first look for empty context
608   if (ViewerTest_myViews.IsEmpty() && !ViewerTest_myContexts.IsEmpty())
609   {
610     NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
611       anIter(ViewerTest_myContexts);
612     if (anIter.More())
613       ViewerTest::SetAISContext (anIter.Value());
614     a3DViewer = ViewerTest::GetAISContext()->CurrentViewer();
615   }
616   else if (ViewerTest_myContexts.IsBound1(aViewNames.GetViewerName()))
617   {
618     ViewerTest::SetAISContext(ViewerTest_myContexts.Find1(aViewNames.GetViewerName()));
619     a3DViewer = ViewerTest::GetAISContext()->CurrentViewer();
620   }
621   else if (a3DViewer.IsNull())
622   {
623     toCreateViewer = Standard_True;
624     TCollection_ExtendedString NameOfWindow("Viewer3D");
625     a3DViewer = new V3d_Viewer(aGraphicDriver, NameOfWindow.ToExtString());
626
627     NameOfWindow = TCollection_ExtendedString("Collector");
628
629     a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
630   }
631
632   // AIS context setup
633   if (ViewerTest::GetAISContext().IsNull() ||
634       !(ViewerTest_myContexts.IsBound1(aViewNames.GetViewerName())))
635   {
636     Handle(AIS_InteractiveContext) aContext = new AIS_InteractiveContext (a3DViewer);
637     ViewerTest::SetAISContext (aContext);
638     ViewerTest_myContexts.Bind (aViewNames.GetViewerName(), ViewerTest::GetAISContext());
639   }
640   else
641   {
642     ViewerTest::ResetEventManager();
643   }
644
645   // Create window
646 #if defined(_WIN32)
647   VT_GetWindow() = new WNT_Window (aTitle.ToCString(),
648                                     Handle(WNT_WClass)::DownCast (WClass()),
649                                     Draw_VirtualWindows ? WS_POPUPWINDOW : WS_OVERLAPPEDWINDOW,
650                                     aPxLeft, aPxTop,
651                                     aPxWidth, aPxHeight,
652                                     Quantity_NOC_BLACK);
653 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
654   VT_GetWindow() = new Cocoa_Window (aTitle.ToCString(),
655                                      aPxLeft, aPxTop,
656                                      aPxWidth, aPxHeight);
657   ViewerTest_SetCocoaEventManagerView (VT_GetWindow());
658 #else
659   VT_GetWindow() = new Xw_Window (aGraphicDriver->GetDisplayConnection(),
660                                   aTitle.ToCString(),
661                                   aPxLeft, aPxTop,
662                                   aPxWidth, aPxHeight);
663 #endif
664   VT_GetWindow()->SetVirtual (Draw_VirtualWindows);
665
666   // NIS setup
667   Handle(NIS_View) aView = new NIS_View (a3DViewer, VT_GetWindow());
668
669   ViewerTest::CurrentView(aView);
670   ViewerTest_myViews.Bind (aViewNames.GetViewName(), aView);
671   TheNISContext()->AttachView (aView);
672
673   // Setup for X11 or NT
674   OSWindowSetup();
675
676   // Set parameters for V3d_View and V3d_Viewer
677   const Handle (V3d_View) aV3dView = ViewerTest::CurrentView();
678   aV3dView->SetComputedMode(Standard_False);
679   MyHLRIsOn = aV3dView->ComputedMode();
680   aV3dView->SetZClippingDepth(0.5);
681   aV3dView->SetZClippingWidth(ZCLIPWIDTH/2.);
682
683   a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
684   if (toCreateViewer)
685   {
686     a3DViewer->SetDefaultLights();
687     a3DViewer->SetLightOn();
688   }
689
690   #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
691   #if TCL_MAJOR_VERSION  < 8
692   Tk_CreateFileHandler((void*)XConnectionNumber(GetDisplayConnection()->GetDisplay()),
693       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
694   #else
695   Tk_CreateFileHandler(XConnectionNumber(GetDisplayConnection()->GetDisplay()),
696       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
697   #endif
698   #endif
699
700   VT_GetWindow()->Map();
701
702   // Set the handle of created view in the event manager
703   ViewerTest::ResetEventManager();
704
705   ViewerTest::CurrentView()->Redraw();
706
707   aView.Nullify();
708   a3DViewer.Nullify();
709
710   return aViewNames.GetViewName();
711 }
712
713 //==============================================================================
714 //function : RedrawAllViews
715 //purpose  : Redraw all created views
716 //==============================================================================
717 void ViewerTest::RedrawAllViews()
718 {
719   NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator aViewIt(ViewerTest_myViews);
720   for (; aViewIt.More(); aViewIt.Next())
721   {
722     const Handle(V3d_View)& aView = aViewIt.Key2();
723     aView->Redraw();
724   }
725 }
726
727 //==============================================================================
728 //function : Vinit
729 //purpose  : Create the window viewer and initialize all the global variable
730 //    Use Tk_CreateFileHandler on UNIX to catch the X11 Viewer event
731 //==============================================================================
732
733 static int VInit (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
734 {
735   if (theArgsNb > 9)
736   {
737     std::cerr << theArgVec[0] << ": incorrect number of command arguments.\n"
738               << "Type help for more information.\n";
739     return 1;
740   }
741
742   TCollection_AsciiString aViewName, aDisplayName;
743   Standard_Integer aPxLeft = 0, aPxTop = 0, aPxWidth = 0, aPxHeight = 0;
744   TCollection_AsciiString aName, aValue;
745   for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
746   {
747     const TCollection_AsciiString anArg = theArgVec[anArgIt];
748     TCollection_AsciiString anArgCase = anArg;
749     anArgCase.UpperCase();
750     if (ViewerTest::SplitParameter (anArg, aName, aValue))
751     {
752       aName.UpperCase();
753       if (aName.IsEqual ("NAME"))
754       {
755         aViewName = aValue;
756       }
757       else if (aName.IsEqual ("L")
758             || aName.IsEqual ("LEFT"))
759       {
760         aPxLeft = aValue.IntegerValue();
761       }
762       else if (aName.IsEqual ("T")
763             || aName.IsEqual ("TOP"))
764       {
765         aPxTop = aValue.IntegerValue();
766       }
767     #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
768       else if (aName.IsEqual ("DISP")
769             || aName.IsEqual ("DISPLAY"))
770       {
771         aDisplayName = aValue;
772       }
773     #endif
774       else if (aName.IsEqual ("W")
775             || aName.IsEqual ("WIDTH"))
776       {
777         aPxWidth = aValue.IntegerValue();
778       }
779       else if (aName.IsEqual ("H")
780             || aName.IsEqual ("HEIGHT"))
781       {
782         aPxHeight = aValue.IntegerValue();
783       }
784       else
785       {
786         std::cerr << theArgVec[0] << ": Warning: unknown argument " << anArg << ".\n";
787       }
788     }
789     else if (aViewName.IsEmpty())
790     {
791       aViewName = anArg;
792     }
793     else
794     {
795       std::cerr << theArgVec[0] << ": Warning: unknown argument " << anArg << ".\n";
796     }
797   }
798
799   ViewerTest_Names aViewNames (aViewName);
800   if (ViewerTest_myViews.IsBound1 (aViewNames.GetViewName()))
801   {
802     TCollection_AsciiString aCommand = TCollection_AsciiString ("vactivate ") + aViewNames.GetViewName();
803     theDi.Eval (aCommand.ToCString());
804     return 0;
805   }
806
807   TCollection_AsciiString aViewId = ViewerTest::ViewerInit (aPxLeft, aPxTop, aPxWidth, aPxHeight,
808                                                             aViewName.ToCString(),
809                                                             aDisplayName.ToCString());
810   theDi << aViewId;
811   return 0;
812 }
813
814 //==============================================================================
815 //function : VHLR
816 //purpose  : hidden lines removal algorithm
817 //draw args: vhlr is_enabled={on|off} [show_hidden={1|0}]
818 //==============================================================================
819
820 static int VHLR (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
821 {
822   if (ViewerTest::CurrentView().IsNull())
823   {
824     di << argv[0] << ": Call vinit before this command, please.\n";
825     return 1;
826   }
827
828   if (argc < 2)
829   {
830     di << argv[0] << ": Wrong number of command arguments.\n"
831       << "Type help " << argv[0] << " for more information.\n";
832     return 1;
833   }
834
835   // Enable or disable HLR mode.
836   Standard_Boolean isHLROn =
837     (!strcasecmp (argv[1], "on")) ? Standard_True : Standard_False;
838
839   if (isHLROn != MyHLRIsOn)
840   {
841     MyHLRIsOn = isHLROn;
842     ViewerTest::CurrentView()->SetComputedMode (MyHLRIsOn);
843   }
844
845   // Show or hide hidden lines in HLR mode.
846   Standard_Boolean isCurrentShowHidden
847     = ViewerTest::GetAISContext()->DefaultDrawer()->DrawHiddenLine();
848
849   Standard_Boolean isShowHidden =
850     (argc == 3) ? (atoi(argv[2]) == 1 ? Standard_True : Standard_False)
851                 : isCurrentShowHidden;
852
853
854   if (isShowHidden != isCurrentShowHidden)
855   {
856     if (isShowHidden)
857     {
858       ViewerTest::GetAISContext()->DefaultDrawer()->EnableDrawHiddenLine();
859     }
860     else
861     {
862       ViewerTest::GetAISContext()->DefaultDrawer()->DisableDrawHiddenLine();
863     }
864
865     // Redisplay shapes.
866     if (MyHLRIsOn)
867     {
868       AIS_ListOfInteractive aListOfShapes;
869       ViewerTest::GetAISContext()->DisplayedObjects (aListOfShapes);
870
871       for (AIS_ListIteratorOfListOfInteractive anIter(aListOfShapes); anIter.More(); anIter.Next())
872       {
873         Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast (anIter.Value());
874         if (aShape.IsNull())
875         {
876           continue;
877         }
878         aShape->Redisplay();
879       }
880     }
881   }
882
883   ViewerTest::CurrentView()->Update();
884   return 0;
885 }
886
887 //==============================================================================
888 //function : VHLRType
889 //purpose  : change type of using HLR algorithm
890 //==============================================================================
891
892 static int VHLRType (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
893 {
894   if (ViewerTest::CurrentView().IsNull())
895   {
896     di << argv[0] << ": Call vinit before this command, please.\n";
897     return 1;
898   }
899
900   if (argc < 2)
901   {
902     di << argv[0] << ": Wrong number of command arguments.\n"
903       << "Type help " << argv[0] << " for more information.\n";
904     return 1;
905   }
906
907   Prs3d_TypeOfHLR aTypeOfHLR =
908     (!strcasecmp (argv[1], "algo")) ? Prs3d_TOH_Algo : Prs3d_TOH_PolyAlgo;
909
910   if (argc == 2)
911   {
912     AIS_ListOfInteractive aListOfShapes;
913     ViewerTest::GetAISContext()->DisplayedObjects (aListOfShapes);
914     ViewerTest::GetAISContext()->DefaultDrawer()->SetTypeOfHLR(aTypeOfHLR);
915     for (AIS_ListIteratorOfListOfInteractive anIter(aListOfShapes);
916       anIter.More(); anIter.Next())
917     {
918       Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anIter.Value());
919       if (aShape.IsNull())
920         continue;
921       if (aShape->TypeOfHLR() != aTypeOfHLR)
922         aShape->SetTypeOfHLR (aTypeOfHLR);
923       if (MyHLRIsOn)
924         aShape->Redisplay();
925     }
926     ViewerTest::CurrentView()->Update();
927     return 0;
928   }
929   else
930   {
931     for (Standard_Integer i = 2; i < argc; ++i)
932     {
933       ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
934       TCollection_AsciiString aName (argv[i]);
935
936       if (!aMap.IsBound2 (aName))
937       {
938         di << argv[0] << ":" << " Wrong shape name:" << aName.ToCString() << ".\n";
939         continue;
940       }
941       Handle(AIS_Shape) anAISObject =
942         Handle(AIS_Shape)::DownCast (aMap.Find2(aName));
943       if (anAISObject.IsNull())
944         continue;
945       anAISObject->SetTypeOfHLR (aTypeOfHLR);
946       if (MyHLRIsOn)
947         anAISObject->Redisplay();
948     }
949     ViewerTest::CurrentView()->Update();
950   }
951
952   return 0;
953 }
954
955 //==============================================================================
956 //function : FindViewIdByWindowHandle
957 //purpose  : Find theView Id in the map of views by window handle
958 //==============================================================================
959 #if defined(_WIN32) || defined(__WIN32__) || (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
960 TCollection_AsciiString FindViewIdByWindowHandle(const Aspect_Handle theWindowHandle)
961 {
962   for (NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator
963        anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
964   {
965     Aspect_Handle aWindowHandle = GetWindowHandle(anIter.Value()->Window());
966     if (aWindowHandle == theWindowHandle)
967       return anIter.Key1();
968   }
969   return TCollection_AsciiString("");
970 }
971 #endif
972
973 //==============================================================================
974 //function : ActivateView
975 //purpose  : Make the view active
976 //==============================================================================
977
978 void ActivateView (const TCollection_AsciiString& theViewName)
979 {
980   const Handle(V3d_View) aView = ViewerTest_myViews.Find1(theViewName);
981   if (!aView.IsNull())
982   {
983     Handle(AIS_InteractiveContext) anAISContext = FindContextByView(aView);
984     if (!anAISContext.IsNull())
985     {
986       if (!ViewerTest::CurrentView().IsNull())
987       {
988         TCollection_AsciiString aTitle("3D View - ");
989         aTitle = aTitle + ViewerTest_myViews.Find2 (ViewerTest::CurrentView());
990         SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
991       }
992
993       ViewerTest::CurrentView (aView);
994       // Update degenerate mode
995       MyHLRIsOn = ViewerTest::CurrentView()->ComputedMode();
996       ViewerTest::SetAISContext (anAISContext);
997       TCollection_AsciiString aTitle = TCollection_AsciiString("3D View - ");
998       aTitle = aTitle + theViewName + "(*)";
999       SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
1000 #if defined(_WIN32) || defined(__WIN32__)
1001       VT_GetWindow() = Handle(WNT_Window)::DownCast(ViewerTest::CurrentView()->Window());
1002 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1003       VT_GetWindow() = Handle(Cocoa_Window)::DownCast(ViewerTest::CurrentView()->Window());
1004 #else
1005       VT_GetWindow() = Handle(Xw_Window)::DownCast(ViewerTest::CurrentView()->Window());
1006 #endif
1007       SetDisplayConnection(ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
1008       ViewerTest::CurrentView()->Redraw();
1009     }
1010   }
1011 }
1012
1013 //==============================================================================
1014 //function : RemoveView
1015 //purpose  :
1016 //==============================================================================
1017 void ViewerTest::RemoveView (const Handle(V3d_View)& theView,
1018                              const Standard_Boolean  theToRemoveContext)
1019 {
1020   if (!ViewerTest_myViews.IsBound2 (theView))
1021   {
1022     return;
1023   }
1024
1025   const TCollection_AsciiString aViewName = ViewerTest_myViews.Find2 (theView);
1026   RemoveView (aViewName, theToRemoveContext);
1027 }
1028
1029 //==============================================================================
1030 //function : RemoveView
1031 //purpose  : Close and remove view from display, clear maps if neccessary
1032 //==============================================================================
1033 void ViewerTest::RemoveView (const TCollection_AsciiString& theViewName, const Standard_Boolean isContextRemoved)
1034 {
1035   if (!ViewerTest_myViews.IsBound1(theViewName))
1036   {
1037     cout << "Wrong view name\n";
1038     return;
1039   }
1040
1041   // Activate another view if it's active now
1042   if (ViewerTest_myViews.Find1(theViewName) == ViewerTest::CurrentView())
1043   {
1044     if (ViewerTest_myViews.Extent() > 1)
1045     {
1046       TCollection_AsciiString aNewViewName;
1047       for (NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)> :: Iterator
1048            anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
1049         if (anIter.Key1() != theViewName)
1050         {
1051           aNewViewName = anIter.Key1();
1052           break;
1053         }
1054         ActivateView (aNewViewName);
1055     }
1056     else
1057     {
1058       Handle(V3d_View) anEmptyView;
1059 #if defined(_WIN32) || defined(__WIN32__)
1060       Handle(WNT_Window) anEmptyWindow;
1061 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1062       Handle(Cocoa_Window) anEmptyWindow;
1063 #else
1064       Handle(Xw_Window) anEmptyWindow;
1065 #endif
1066       VT_GetWindow() = anEmptyWindow;
1067       ViewerTest::CurrentView (anEmptyView);
1068       if (isContextRemoved)
1069       {
1070         Handle(AIS_InteractiveContext) anEmptyContext;
1071         ViewerTest::SetAISContext(anEmptyContext);
1072       }
1073     }
1074   }
1075
1076   // Delete view
1077   Handle(V3d_View) aView = ViewerTest_myViews.Find1(theViewName);
1078   Handle(AIS_InteractiveContext) aCurrentContext = FindContextByView(aView);
1079
1080   // Remove view resources
1081   TheNISContext()->DetachView(Handle(NIS_View)::DownCast(aView));
1082   ViewerTest_myViews.UnBind1(theViewName);
1083   aView->Remove();
1084
1085 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
1086   XFlush (GetDisplayConnection()->GetDisplay());
1087 #endif
1088
1089   // Keep context opened only if the closed view is last to avoid
1090   // unused empty contexts
1091   if (!aCurrentContext.IsNull())
1092   {
1093     // Check if there are more difined views in the viewer
1094     aCurrentContext->CurrentViewer()->InitDefinedViews();
1095     if ((isContextRemoved || ViewerTest_myContexts.Size() != 1) && !aCurrentContext->CurrentViewer()->MoreDefinedViews())
1096     {
1097       // Remove driver if there is no viewers that use it
1098       Standard_Boolean isRemoveDriver = Standard_True;
1099       for(NCollection_DoubleMap<TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
1100           anIter(ViewerTest_myContexts); anIter.More(); anIter.Next())
1101       {
1102         if (aCurrentContext != anIter.Key2() &&
1103           aCurrentContext->CurrentViewer()->Driver() == anIter.Value()->CurrentViewer()->Driver())
1104         {
1105           isRemoveDriver = Standard_False;
1106           break;
1107         }
1108       }
1109       if(isRemoveDriver)
1110       {
1111         ViewerTest_myDrivers.UnBind2 (aCurrentContext->CurrentViewer()->Driver());
1112       #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
1113         #if TCL_MAJOR_VERSION  < 8
1114         Tk_DeleteFileHandler((void*)XConnectionNumber(aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplay()));
1115         #else
1116         Tk_DeleteFileHandler(XConnectionNumber(aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplay()));
1117         #endif
1118       #endif
1119       }
1120
1121       ViewerTest_myContexts.UnBind2(aCurrentContext);
1122     }
1123   }
1124   cout << "3D View - " << theViewName << " was deleted.\n";
1125
1126 }
1127
1128 //==============================================================================
1129 //function : VClose
1130 //purpose  : Remove the view defined by its name
1131 //==============================================================================
1132
1133 static int VClose (Draw_Interpretor& /*theDi*/,
1134                    Standard_Integer  theArgsNb,
1135                    const char**      theArgVec)
1136 {
1137   NCollection_List<TCollection_AsciiString> aViewList;
1138   if (theArgsNb > 1)
1139   {
1140     TCollection_AsciiString anArg (theArgVec[1]);
1141     anArg.UpperCase();
1142     if (anArg.IsEqual ("ALL")
1143      || anArg.IsEqual ("*"))
1144     {
1145       for (NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator anIter (ViewerTest_myViews);
1146            anIter.More(); anIter.Next())
1147       {
1148         aViewList.Append (anIter.Key1());
1149       }
1150       if (aViewList.IsEmpty())
1151       {
1152         std::cout << "No view to close\n";
1153         return 0;
1154       }
1155     }
1156     else
1157     {
1158       ViewerTest_Names aViewName (theArgVec[1]);
1159       if (!ViewerTest_myViews.IsBound1 (aViewName.GetViewName()))
1160       {
1161         std::cerr << "The view with name '" << theArgVec[1] << "' does not exist\n";
1162         return 1;
1163       }
1164       aViewList.Append (aViewName.GetViewName());
1165     }
1166   }
1167   else
1168   {
1169     // close active view
1170     if (ViewerTest::CurrentView().IsNull())
1171     {
1172       std::cerr << "No active view!\n";
1173       return 1;
1174     }
1175     aViewList.Append (ViewerTest_myViews.Find2 (ViewerTest::CurrentView()));
1176   }
1177
1178   Standard_Boolean toRemoveContext = (theArgsNb != 3 || Draw::Atoi (theArgVec[2]) != 1);
1179   for (NCollection_List<TCollection_AsciiString>::Iterator anIter(aViewList);
1180        anIter.More(); anIter.Next())
1181   {
1182     ViewerTest::RemoveView (anIter.Value(), toRemoveContext);
1183   }
1184
1185   return 0;
1186 }
1187
1188 //==============================================================================
1189 //function : VActivate
1190 //purpose  : Activate the view defined by its ID
1191 //==============================================================================
1192
1193 static int VActivate (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
1194 {
1195   if (theArgsNb > 2)
1196   {
1197     theDi << theArgVec[0] << ": wrong number of command arguments.\n"
1198     << "Usage: " << theArgVec[0] << " ViewID\n";
1199     return 1;
1200   }
1201   if(theArgsNb == 1)
1202   {
1203     theDi.Eval("vviewlist");
1204     return 0;
1205   }
1206
1207   TCollection_AsciiString aNameString(theArgVec[1]);
1208   if ( strcasecmp( aNameString.ToCString(), "NONE" ) == 0 )
1209   {
1210     TCollection_AsciiString aTitle("3D View - ");
1211     aTitle = aTitle + ViewerTest_myViews.Find2(ViewerTest::CurrentView());
1212     SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
1213     Handle(V3d_View) anEmptyView;
1214 #if defined(_WIN32) || defined(__WIN32__)
1215     Handle(WNT_Window) anEmptyWindow;
1216 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1217     Handle(Cocoa_Window) anEmptyWindow;
1218 #else
1219     Handle(Xw_Window) anEmptyWindow;
1220 #endif
1221     VT_GetWindow() = anEmptyWindow;
1222     ViewerTest::CurrentView (anEmptyView);
1223     ViewerTest::ResetEventManager();
1224     theDi << theArgVec[0] << ": all views are inactive\n";
1225     return 0;
1226   }
1227
1228   ViewerTest_Names aViewNames(aNameString);
1229
1230   // Check if this view exists in the viewer with the driver
1231   if (!ViewerTest_myViews.IsBound1(aViewNames.GetViewName()))
1232   {
1233     theDi << "Wrong view name\n";
1234     return 1;
1235   }
1236
1237   // Check if it is active already
1238   if (ViewerTest::CurrentView() == ViewerTest_myViews.Find1(aViewNames.GetViewName()))
1239   {
1240     theDi << theArgVec[0] << ": the view is active already\n";
1241     return 0;
1242   }
1243
1244   ActivateView (aViewNames.GetViewName());
1245   return 0;
1246 }
1247
1248 //==============================================================================
1249 //function : VViewList
1250 //purpose  : Print current list of views per viewer and graphic driver ID
1251 //           shared between viewers
1252 //==============================================================================
1253
1254 static int VViewList (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
1255 {
1256   if (theArgsNb > 2)
1257   {
1258     theDi << theArgVec[0] << ": Wrong number of command arguments\n"
1259           << "Usage: " << theArgVec[0] << " name";
1260     return 1;
1261   }
1262   if (ViewerTest_myContexts.Size() < 1)
1263     return 0;
1264
1265   Standard_Boolean isTreeView =
1266     (( theArgsNb==1 ) || ( strcasecmp( theArgVec[1], "long" ) != 0 ));
1267
1268   if (isTreeView)
1269     theDi << theArgVec[0] <<":\n";
1270
1271     for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
1272       aDriverIter(ViewerTest_myDrivers); aDriverIter.More(); aDriverIter.Next())
1273     {
1274       if (isTreeView)
1275         theDi << aDriverIter.Key1() << ":\n";
1276
1277       for (NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
1278         aContextIter(ViewerTest_myContexts); aContextIter.More(); aContextIter.Next())
1279       {
1280         if (aContextIter.Key1().Search(aDriverIter.Key1()) != -1)
1281         {
1282           if (isTreeView)
1283           {
1284             TCollection_AsciiString aContextName(aContextIter.Key1());
1285             theDi << " " << aContextName.Split(aDriverIter.Key1().Length() + 1) << ":" << "\n";
1286           }
1287
1288           for (NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)>::Iterator
1289             aViewIter(ViewerTest_myViews); aViewIter.More(); aViewIter.Next())
1290           {
1291             if (aViewIter.Key1().Search(aContextIter.Key1()) != -1)
1292             {
1293               TCollection_AsciiString aViewName(aViewIter.Key1());
1294               if (isTreeView)
1295               {
1296                 if (aViewIter.Value() == ViewerTest::CurrentView())
1297                   theDi << "  " << aViewName.Split(aContextIter.Key1().Length() + 1) << "(*)" << "\n";
1298                 else
1299                   theDi << "  " << aViewName.Split(aContextIter.Key1().Length() + 1) << "\n";
1300               }
1301               else
1302               {
1303                 theDi << aViewName << " ";
1304               }
1305             }
1306           }
1307         }
1308       }
1309     }
1310   return 0;
1311 }
1312
1313 //==============================================================================
1314 //function : VT_ProcessKeyPress
1315 //purpose  : Handle KeyPress event from a CString
1316 //==============================================================================
1317 void VT_ProcessKeyPress (const char* buf_ret)
1318 {
1319   //cout << "KeyPress" << endl;
1320   const Handle(V3d_View) aView = ViewerTest::CurrentView();
1321   const Handle(NIS_View) aNisView = Handle(NIS_View)::DownCast (aView);
1322   // Letter in alphabetic order
1323
1324   if (!strcasecmp (buf_ret, "A"))
1325   {
1326     // AXO
1327     aView->SetProj(V3d_XposYnegZpos);
1328   }
1329   else if (!strcasecmp (buf_ret, "D"))
1330   {
1331     // Reset
1332     aView->Reset();
1333   }
1334   else if (!strcasecmp (buf_ret, "F"))
1335   {
1336     // FitAll
1337     if (aNisView.IsNull())
1338       aView->FitAll();
1339     else
1340       aNisView->FitAll3d();
1341   }
1342   else if (!strcasecmp (buf_ret, "H"))
1343   {
1344     // HLR
1345     cout << "HLR" << endl;
1346     aView->SetComputedMode (!aView->ComputedMode());
1347     MyHLRIsOn = aView->ComputedMode();
1348   }
1349   else if (!strcasecmp (buf_ret, "P"))
1350   {
1351     // Type of HLR
1352     Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
1353     if (aContext->DefaultDrawer()->TypeOfHLR() == Prs3d_TOH_Algo)
1354       aContext->DefaultDrawer()->SetTypeOfHLR(Prs3d_TOH_PolyAlgo);
1355     else
1356       aContext->DefaultDrawer()->SetTypeOfHLR(Prs3d_TOH_Algo);
1357     if (aContext->NbCurrents()==0 || aContext->NbSelected() == 0)
1358     {
1359       AIS_ListOfInteractive aListOfShapes;
1360       aContext->DisplayedObjects(aListOfShapes);
1361       for (AIS_ListIteratorOfListOfInteractive anIter(aListOfShapes);
1362         anIter.More(); anIter.Next())
1363       {
1364         Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anIter.Value());
1365         if (aShape.IsNull())
1366           continue;
1367         if (aShape->TypeOfHLR() == Prs3d_TOH_PolyAlgo)
1368           aShape->SetTypeOfHLR (Prs3d_TOH_Algo);
1369         else
1370           aShape->SetTypeOfHLR (Prs3d_TOH_PolyAlgo);
1371         aShape->Redisplay();
1372       }
1373     }
1374     else
1375     {
1376       for (aContext->InitCurrent();aContext->MoreCurrent();aContext->NextCurrent())
1377       {
1378         Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(aContext->Current());
1379         if (aShape.IsNull())
1380           continue;
1381         if(aShape->TypeOfHLR() == Prs3d_TOH_PolyAlgo)
1382           aShape->SetTypeOfHLR (Prs3d_TOH_Algo);
1383         else
1384           aShape->SetTypeOfHLR (Prs3d_TOH_PolyAlgo);
1385         aShape->Redisplay();
1386       }
1387     }
1388
1389     aContext->UpdateCurrentViewer();
1390
1391   }
1392   else if (!strcasecmp (buf_ret, "S"))
1393   {
1394     std::cout << "setup Shaded display mode" << std::endl;
1395
1396     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1397     if(Ctx->NbCurrents()==0 ||
1398       Ctx->NbSelected()==0)
1399       Ctx->SetDisplayMode(AIS_Shaded);
1400     else{
1401       if(Ctx->HasOpenedContext()){
1402         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1403           Ctx->SetDisplayMode(Ctx->Interactive(),1,Standard_False);
1404       }
1405       else{
1406         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1407           Ctx->SetDisplayMode(Ctx->Current(),1,Standard_False);
1408       }
1409       Ctx->UpdateCurrentViewer();
1410     }
1411   }
1412   else if (!strcasecmp (buf_ret, "U"))
1413   {
1414     // Unset display mode
1415     std::cout << "reset display mode to defaults" << std::endl;
1416
1417     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1418     if(Ctx->NbCurrents()==0 ||
1419       Ctx->NbSelected()==0)
1420       Ctx->SetDisplayMode(AIS_WireFrame);
1421     else{
1422       if(Ctx->HasOpenedContext()){
1423         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1424           Ctx->UnsetDisplayMode(Ctx->Interactive(),Standard_False);
1425       }
1426       else{
1427         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1428           Ctx->UnsetDisplayMode(Ctx->Current(),Standard_False);
1429       }
1430       Ctx->UpdateCurrentViewer();
1431     }
1432
1433   }
1434   else if (!strcasecmp (buf_ret, "T"))
1435   {
1436     // Top
1437     aView->SetProj(V3d_Zpos);
1438   }
1439   else if (!strcasecmp (buf_ret, "B"))
1440   {
1441     // Bottom
1442     aView->SetProj(V3d_Zneg);
1443   }
1444   else if (!strcasecmp (buf_ret, "L"))
1445   {
1446     // Left
1447     aView->SetProj(V3d_Xneg);
1448   }
1449   else if (!strcasecmp (buf_ret, "R"))
1450   {
1451     // Right
1452     aView->SetProj(V3d_Xpos);
1453   }
1454   else if (!strcasecmp (buf_ret, "W"))
1455   {
1456     std::cout << "setup WireFrame display mode" << std::endl;
1457     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1458     if(Ctx->NbCurrents()==0 ||
1459       Ctx->NbSelected()==0)
1460       Ctx->SetDisplayMode(AIS_WireFrame);
1461     else{
1462       if(Ctx->HasOpenedContext()){
1463         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1464           Ctx->SetDisplayMode(Ctx->Interactive(),0,Standard_False);
1465       }
1466       else{
1467         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1468           Ctx->SetDisplayMode(Ctx->Current(),0,Standard_False);
1469       }
1470       Ctx->UpdateCurrentViewer();
1471     }
1472   }
1473   else if (!strcasecmp (buf_ret, "Z"))
1474   {
1475     // ZCLIP
1476     if ( ZClipIsOn ) {
1477       cout << "ZClipping OFF" << endl;
1478       ZClipIsOn = 0;
1479
1480       aView->SetZClippingType(V3d_OFF);
1481       aView->Redraw();
1482     }
1483     else {
1484       cout << "ZClipping ON" << endl;
1485       ZClipIsOn = 1;
1486
1487       aView->SetZClippingType(V3d_FRONT);
1488       aView->Redraw();
1489     }
1490   }
1491   else if (!strcasecmp (buf_ret, ","))
1492   {
1493     ViewerTest::GetAISContext()->HilightNextDetected(ViewerTest::CurrentView());
1494   }
1495   else if (!strcasecmp (buf_ret, "."))
1496   {
1497     ViewerTest::GetAISContext()->HilightPreviousDetected(ViewerTest::CurrentView());
1498   }
1499   else if (*buf_ret == THE_KEY_DELETE)
1500   {
1501     Handle(AIS_InteractiveContext) aCtx = ViewerTest::GetAISContext();
1502     if (!aCtx.IsNull()
1503      && aCtx->NbCurrents() > 0
1504      && aCtx->NbSelected() > 0)
1505     {
1506       Draw_Interprete ("verase");
1507     }
1508   }
1509   else
1510   {
1511     // Number
1512     Standard_Integer Num = Draw::Atoi(buf_ret);
1513     if(Num>=0 && Num<=7)
1514       ViewerTest::StandardModeActivation(Num);
1515   }
1516 }
1517
1518 //==============================================================================
1519 //function : VT_ProcessExpose
1520 //purpose  : Redraw the View on an Expose Event
1521 //==============================================================================
1522 void VT_ProcessExpose()
1523 {
1524   Handle(V3d_View) aView3d = ViewerTest::CurrentView();
1525   if (!aView3d.IsNull())
1526   {
1527     aView3d->Redraw();
1528   }
1529 }
1530
1531 //==============================================================================
1532 //function : VT_ProcessConfigure
1533 //purpose  : Resize the View on an Configure Event
1534 //==============================================================================
1535 void VT_ProcessConfigure()
1536 {
1537   Handle(V3d_View) aView3d = ViewerTest::CurrentView();
1538   if (aView3d.IsNull())
1539   {
1540     return;
1541   }
1542
1543   aView3d->MustBeResized();
1544   aView3d->Update();
1545   aView3d->Redraw();
1546 }
1547
1548 //==============================================================================
1549 //function : VT_ProcessButton1Press
1550 //purpose  : Picking
1551 //==============================================================================
1552 Standard_Boolean VT_ProcessButton1Press (Standard_Integer ,
1553                                          const char**     theArgVec,
1554                                          Standard_Boolean theToPick,
1555                                          Standard_Boolean theIsShift)
1556 {
1557   if (theToPick)
1558   {
1559     Standard_Real X, Y, Z;
1560     ViewerTest::CurrentView()->Convert (X_Motion, Y_Motion, X, Y, Z);
1561
1562     Draw::Set (theArgVec[1], X);
1563     Draw::Set (theArgVec[2], Y);
1564     Draw::Set (theArgVec[3], Z);
1565   }
1566
1567   if (theIsShift)
1568   {
1569     ViewerTest::CurrentEventManager()->ShiftSelect();
1570   }
1571   else
1572   {
1573     ViewerTest::CurrentEventManager()->Select();
1574   }
1575
1576   return Standard_False;
1577 }
1578
1579 //==============================================================================
1580 //function : VT_ProcessButton1Release
1581 //purpose  : End selecting
1582 //==============================================================================
1583 void VT_ProcessButton1Release (Standard_Boolean theIsShift)
1584 {
1585   if (IsDragged)
1586   {
1587     IsDragged = Standard_False;
1588     Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
1589     if (theIsShift)
1590     {
1591       EM->ShiftSelect (Min (X_ButtonPress, X_Motion), Max (Y_ButtonPress, Y_Motion),
1592                        Max (X_ButtonPress, X_Motion), Min (Y_ButtonPress, Y_Motion));
1593     }
1594     else
1595     {
1596       EM->Select (Min (X_ButtonPress, X_Motion), Max (Y_ButtonPress, Y_Motion),
1597                   Max (X_ButtonPress, X_Motion), Min (Y_ButtonPress, Y_Motion));
1598     }
1599   }
1600 }
1601
1602 //==============================================================================
1603 //function : VT_ProcessButton3Press
1604 //purpose  : Start Rotation
1605 //==============================================================================
1606 void VT_ProcessButton3Press()
1607 {
1608   Start_Rot = 1;
1609   if (MyHLRIsOn)
1610   {
1611     ViewerTest::CurrentView()->SetComputedMode (Standard_False);
1612   }
1613   ViewerTest::CurrentView()->StartRotation( X_ButtonPress, Y_ButtonPress );
1614 }
1615
1616 //==============================================================================
1617 //function : VT_ProcessButton3Release
1618 //purpose  : End rotation
1619 //==============================================================================
1620 void VT_ProcessButton3Release()
1621 {
1622   if (Start_Rot)
1623   {
1624     Start_Rot = 0;
1625     if (MyHLRIsOn)
1626     {
1627       ViewerTest::CurrentView()->SetComputedMode (Standard_True);
1628     }
1629   }
1630 }
1631
1632 //==============================================================================
1633 //function : ProcessZClipMotion
1634 //purpose  : Zoom
1635 //==============================================================================
1636
1637 void ProcessZClipMotion()
1638 {
1639   Handle(V3d_View)  a3DView = ViewerTest::CurrentView();
1640   if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
1641     static Standard_Real CurZPos = 0.;
1642
1643     //Quantity_Length VDX, VDY;
1644     //a3DView->Size(VDX,VDY);
1645     //Standard_Real VDZ = a3DView->ZSize();
1646     //printf("View size (%lf,%lf,%lf)\n", VDX, VDY, VDZ);
1647
1648     Quantity_Length dx = a3DView->Convert(X_Motion - X_ButtonPress);
1649
1650     // Front = Depth + width/2.
1651     Standard_Real D = 0.5;
1652     Standard_Real W = 0.1;
1653
1654     CurZPos += (dx);
1655
1656     D += CurZPos;
1657
1658     //printf("dx %lf Depth %lf Width %lf\n", dx, D, W);
1659
1660     a3DView->SetZClippingType(V3d_OFF);
1661     a3DView->SetZClippingDepth(D);
1662     a3DView->SetZClippingWidth(W);
1663     a3DView->SetZClippingType(V3d_FRONT);
1664
1665     a3DView->Redraw();
1666
1667     X_ButtonPress = X_Motion;
1668     Y_ButtonPress = Y_Motion;
1669   }
1670 }
1671
1672 //==============================================================================
1673 //function : ProcessControlButton1Motion
1674 //purpose  : Zoom
1675 //==============================================================================
1676
1677 #if defined(_WIN32) || ! defined(__APPLE__) || defined(MACOSX_USE_GLX)
1678 static void ProcessControlButton1Motion()
1679 {
1680   ViewerTest::CurrentView()->Zoom( X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion);
1681
1682   X_ButtonPress = X_Motion;
1683   Y_ButtonPress = Y_Motion;
1684 }
1685 #endif
1686
1687 //==============================================================================
1688 //function : VT_ProcessControlButton2Motion
1689 //purpose  : Panning
1690 //==============================================================================
1691 void VT_ProcessControlButton2Motion()
1692 {
1693   Standard_Integer aDx = X_Motion - X_ButtonPress;
1694   Standard_Integer aDy = Y_Motion - Y_ButtonPress;
1695
1696   aDy = -aDy; // Xwindow Y axis is from top to Bottom
1697
1698   ViewerTest::CurrentView()->Pan (aDx, aDy);
1699
1700   X_ButtonPress = X_Motion;
1701   Y_ButtonPress = Y_Motion;
1702 }
1703
1704 //==============================================================================
1705 //function : VT_ProcessControlButton3Motion
1706 //purpose  : Rotation
1707 //==============================================================================
1708 void VT_ProcessControlButton3Motion()
1709 {
1710   if (Start_Rot)
1711   {
1712     ViewerTest::CurrentView()->Rotation (X_Motion, Y_Motion);
1713   }
1714 }
1715
1716 //==============================================================================
1717 //function : VT_ProcessMotion
1718 //purpose  :
1719 //==============================================================================
1720 void VT_ProcessMotion()
1721 {
1722   //pre-hilights detected objects at mouse position
1723
1724   Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
1725   EM->MoveTo(X_Motion, Y_Motion);
1726 }
1727
1728
1729 void ViewerTest::GetMousePosition(Standard_Integer& Xpix,Standard_Integer& Ypix)
1730 {
1731   Xpix = X_Motion;Ypix=Y_Motion;
1732 }
1733
1734 //==============================================================================
1735 //function : ViewProject: implements VAxo, VTop, VLeft, ...
1736 //purpose  : Switches to an axonometric, top, left and other views
1737 //==============================================================================
1738
1739 static int ViewProject(Draw_Interpretor& di, const V3d_TypeOfOrientation ori)
1740 {
1741   if ( ViewerTest::CurrentView().IsNull() )
1742   {
1743     di<<"Call vinit before this command, please"<<"\n";
1744     return 1;
1745   }
1746
1747   ViewerTest::CurrentView()->SetProj(ori);
1748   return 0;
1749 }
1750
1751 //==============================================================================
1752 //function : VAxo
1753 //purpose  : Switch to an Axonometric view
1754 //Draw arg : No args
1755 //==============================================================================
1756
1757 static int VAxo(Draw_Interpretor& di, Standard_Integer , const char** )
1758 {
1759   return ViewProject(di, V3d_XposYnegZpos);
1760 }
1761
1762 //==============================================================================
1763 //function : VTop
1764 //purpose  : Switch to a Top View
1765 //Draw arg : No args
1766 //==============================================================================
1767
1768 static int VTop(Draw_Interpretor& di, Standard_Integer , const char** )
1769 {
1770   return ViewProject(di, V3d_Zpos);
1771 }
1772
1773 //==============================================================================
1774 //function : VBottom
1775 //purpose  : Switch to a Bottom View
1776 //Draw arg : No args
1777 //==============================================================================
1778
1779 static int VBottom(Draw_Interpretor& di, Standard_Integer , const char** )
1780 {
1781   return ViewProject(di, V3d_Zneg);
1782 }
1783
1784 //==============================================================================
1785 //function : VLeft
1786 //purpose  : Switch to a Left View
1787 //Draw arg : No args
1788 //==============================================================================
1789
1790 static int VLeft(Draw_Interpretor& di, Standard_Integer , const char** )
1791 {
1792   return ViewProject(di, V3d_Ypos);
1793 }
1794
1795 //==============================================================================
1796 //function : VRight
1797 //purpose  : Switch to a Right View
1798 //Draw arg : No args
1799 //==============================================================================
1800
1801 static int VRight(Draw_Interpretor& di, Standard_Integer , const char** )
1802 {
1803   return ViewProject(di, V3d_Yneg);
1804 }
1805
1806 //==============================================================================
1807 //function : VFront
1808 //purpose  : Switch to a Front View
1809 //Draw arg : No args
1810 //==============================================================================
1811
1812 static int VFront(Draw_Interpretor& di, Standard_Integer , const char** )
1813 {
1814   return ViewProject(di, V3d_Xpos);
1815 }
1816
1817 //==============================================================================
1818 //function : VBack
1819 //purpose  : Switch to a Back View
1820 //Draw arg : No args
1821 //==============================================================================
1822
1823 static int VBack(Draw_Interpretor& di, Standard_Integer , const char** )
1824 {
1825   return ViewProject(di, V3d_Xneg);
1826 }
1827
1828 //==============================================================================
1829 //function : VHelp
1830 //purpose  : Dsiplay help on viewer Keyboead and mouse commands
1831 //Draw arg : No args
1832 //==============================================================================
1833
1834 static int VHelp(Draw_Interpretor& di, Standard_Integer , const char** )
1835 {
1836
1837   di << "Q : Quit the application" << "\n";
1838
1839   di << "========================="<<"\n";
1840   di << "F : FitAll" << "\n";
1841   di << "T : TopView" << "\n";
1842   di << "B : BottomView" << "\n";
1843   di << "R : RightView" << "\n";
1844   di << "L : LeftView" << "\n";
1845   di << "A : AxonometricView" << "\n";
1846   di << "D : ResetView" << "\n";
1847
1848   di << "========================="<<"\n";
1849   di << "S : Shading" << "\n";
1850   di << "W : Wireframe" << "\n";
1851   di << "H : HidelLineRemoval" << "\n";
1852   di << "U : Unset display mode" << "\n";
1853   di << "Delete : Remove selection from viewer" << "\n";
1854
1855   di << "========================="<<"\n";
1856   di << "Selection mode "<<"\n";
1857   di << "0 : Shape" <<"\n";
1858   di << "1 : Vertex" <<"\n";
1859   di << "2 : Edge" <<"\n";
1860   di << "3 : Wire" <<"\n";
1861   di << "4 : Face" <<"\n";
1862   di << "5 : Shell" <<"\n";
1863   di << "6 : Solid" <<"\n";
1864   di << "7 : Compound" <<"\n";
1865
1866   di << "========================="<<"\n";
1867   di << "Z : Switch Z clipping On/Off" << "\n";
1868   di << ", : Hilight next detected" << "\n";
1869   di << ". : Hilight previous detected" << "\n";
1870
1871   return 0;
1872 }
1873
1874 #ifdef WNT
1875
1876 static Standard_Boolean Ppick = 0;
1877 static Standard_Integer Pargc = 0;
1878 static const char**           Pargv = NULL;
1879
1880
1881 static LRESULT WINAPI AdvViewerWindowProc( HWND hwnd,
1882                                           UINT Msg,
1883                                           WPARAM wParam,
1884                                           LPARAM lParam )
1885 {
1886   if (!ViewerTest_myViews.IsEmpty()) {
1887
1888     WPARAM fwKeys = wParam;
1889
1890     switch( Msg ) {
1891     case WM_CLOSE:
1892        {
1893          // Delete view from map of views
1894          ViewerTest::RemoveView(FindViewIdByWindowHandle(hwnd));
1895          return 0;
1896        }
1897        break;
1898     case WM_ACTIVATE:
1899       if(LOWORD(wParam) == WA_CLICKACTIVE || LOWORD(wParam) == WA_ACTIVE
1900         || ViewerTest::CurrentView().IsNull())
1901       {
1902         // Activate inactive window
1903         if(GetWindowHandle(VT_GetWindow()) != hwnd)
1904         {
1905           ActivateView (FindViewIdByWindowHandle(hwnd));
1906         }
1907       }
1908       break;
1909     case WM_LBUTTONUP:
1910       if (!DragFirst)
1911       {
1912         HDC hdc = GetDC( hwnd );
1913         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
1914         SetROP2( hdc, R2_NOT );
1915         Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1916         ReleaseDC( hwnd, hdc );
1917         VT_ProcessButton1Release (fwKeys & MK_SHIFT);
1918       }
1919       IsDragged = Standard_False;
1920       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1921
1922     case WM_LBUTTONDOWN:
1923       if( fwKeys == MK_LBUTTON || fwKeys == ( MK_LBUTTON | MK_SHIFT ) )
1924       {
1925         IsDragged = Standard_True;
1926         DragFirst = Standard_True;
1927         X_ButtonPress = LOWORD(lParam);
1928         Y_ButtonPress = HIWORD(lParam);
1929       }
1930       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1931
1932       break;
1933
1934     case WM_MOUSEMOVE:
1935       if( IsDragged )
1936       {
1937         HDC hdc = GetDC( hwnd );
1938
1939         HGDIOBJ anObj = SelectObject( hdc, GetStockObject( WHITE_PEN ) );
1940         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
1941         SetROP2( hdc, R2_NOT );
1942
1943         if( !DragFirst )
1944           Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1945
1946         DragFirst = Standard_False;
1947         X_Motion = LOWORD(lParam);
1948         Y_Motion = HIWORD(lParam);
1949
1950         Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1951
1952         SelectObject( hdc, anObj );
1953
1954         ReleaseDC( hwnd, hdc );
1955       }
1956       else
1957         return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1958       break;
1959
1960     default:
1961       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1962     }
1963     return 0;
1964   }
1965   return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1966 }
1967
1968
1969 static LRESULT WINAPI ViewerWindowProc( HWND hwnd,
1970                                        UINT Msg,
1971                                        WPARAM wParam,
1972                                        LPARAM lParam )
1973 {
1974   static int Up = 1;
1975
1976   if ( !ViewerTest::CurrentView().IsNull() ) {
1977     PAINTSTRUCT    ps;
1978
1979     switch( Msg ) {
1980     case WM_PAINT:
1981       BeginPaint(hwnd, &ps);
1982       EndPaint(hwnd, &ps);
1983       VT_ProcessExpose();
1984       break;
1985
1986     case WM_SIZE:
1987       VT_ProcessConfigure();
1988       break;
1989
1990     case WM_KEYDOWN:
1991       if ((wParam != VK_SHIFT) && (wParam != VK_CONTROL))
1992       {
1993         char c[2];
1994         c[0] = (char) wParam;
1995         c[1] = '\0';
1996         if (wParam == VK_DELETE)
1997         {
1998           c[0] = THE_KEY_DELETE;
1999         }
2000         VT_ProcessKeyPress (c);
2001       }
2002       break;
2003
2004     case WM_LBUTTONUP:
2005     case WM_MBUTTONUP:
2006     case WM_RBUTTONUP:
2007       Up = 1;
2008       VT_ProcessButton3Release();
2009       break;
2010
2011     case WM_LBUTTONDOWN:
2012     case WM_MBUTTONDOWN:
2013     case WM_RBUTTONDOWN:
2014       {
2015         WPARAM fwKeys = wParam;
2016
2017         Up = 0;
2018
2019         X_ButtonPress = LOWORD(lParam);
2020         Y_ButtonPress = HIWORD(lParam);
2021
2022         if (Msg == WM_LBUTTONDOWN)
2023         {
2024           if (fwKeys & MK_CONTROL)
2025           {
2026             Ppick = VT_ProcessButton1Press (Pargc, Pargv, Ppick, (fwKeys & MK_SHIFT));
2027           }
2028           else
2029           {
2030             VT_ProcessButton1Press (Pargc, Pargv, Ppick, (fwKeys & MK_SHIFT));
2031           }
2032         }
2033         else if (Msg == WM_RBUTTONDOWN)
2034         {
2035           // Start rotation
2036           VT_ProcessButton3Press();
2037         }
2038       }
2039       break;
2040
2041     case WM_MOUSEMOVE:
2042       {
2043         //cout << "\t WM_MOUSEMOVE" << endl;
2044         WPARAM fwKeys = wParam;
2045         X_Motion = LOWORD(lParam);
2046         Y_Motion = HIWORD(lParam);
2047
2048         if ( Up &&
2049           fwKeys & ( MK_LBUTTON|MK_MBUTTON|MK_RBUTTON ) ) {
2050             Up = 0;
2051             X_ButtonPress = LOWORD(lParam);
2052             Y_ButtonPress = HIWORD(lParam);
2053
2054             if ( fwKeys & MK_RBUTTON ) {
2055               // Start rotation
2056               VT_ProcessButton3Press();
2057             }
2058           }
2059
2060           if ( fwKeys & MK_CONTROL ) {
2061             if ( fwKeys & MK_LBUTTON ) {
2062               ProcessControlButton1Motion();
2063             }
2064             else if ( fwKeys & MK_MBUTTON ||
2065               ((fwKeys&MK_LBUTTON) &&
2066               (fwKeys&MK_RBUTTON) ) ){
2067                 VT_ProcessControlButton2Motion();
2068               }
2069             else if ( fwKeys & MK_RBUTTON ) {
2070               VT_ProcessControlButton3Motion();
2071             }
2072           }
2073 #ifdef BUG
2074           else if ( fwKeys & MK_SHIFT ) {
2075             if ( fwKeys & MK_MBUTTON ||
2076               ((fwKeys&MK_LBUTTON) &&
2077               (fwKeys&MK_RBUTTON) ) ) {
2078                 cout << "ProcessZClipMotion()" << endl;
2079                 ProcessZClipMotion();
2080               }
2081           }
2082 #endif
2083           else if (GetWindowHandle (VT_GetWindow()) == hwnd)
2084           {
2085             if ((fwKeys & MK_MBUTTON
2086             || ((fwKeys & MK_LBUTTON) && (fwKeys & MK_RBUTTON))))
2087             {
2088               ProcessZClipMotion();
2089             }
2090             else
2091             {
2092               VT_ProcessMotion();
2093             }
2094           }
2095       }
2096       break;
2097
2098     default:
2099       return( DefWindowProc( hwnd, Msg, wParam, lParam ));
2100     }
2101     return 0L;
2102   }
2103
2104   return DefWindowProc( hwnd, Msg, wParam, lParam );
2105 }
2106
2107
2108
2109
2110 //==============================================================================
2111 //function : ViewerMainLoop
2112 //purpose  : Get a Event on the view and dispatch it
2113 //==============================================================================
2114
2115
2116 int ViewerMainLoop(Standard_Integer argc, const char** argv)
2117 {
2118   Ppick = (argc > 0)? 1 : 0;
2119   Pargc = argc;
2120   Pargv = argv;
2121
2122   if ( Ppick ) {
2123     MSG msg;
2124     msg.wParam = 1;
2125
2126     cout << "Start picking" << endl;
2127
2128     while ( Ppick == 1 ) {
2129       // Wait for a VT_ProcessButton1Press() to toggle pick to 1 or 0
2130       if (GetMessage(&msg, NULL, 0, 0) ) {
2131         TranslateMessage(&msg);
2132         DispatchMessage(&msg);
2133       }
2134     }
2135
2136     cout << "Picking done" << endl;
2137   }
2138
2139   return Ppick;
2140 }
2141
2142 #elif !defined(__APPLE__) || defined(MACOSX_USE_GLX)
2143
2144 int min( int a, int b )
2145 {
2146   if( a<b )
2147     return a;
2148   else
2149     return b;
2150 }
2151
2152 int max( int a, int b )
2153 {
2154   if( a>b )
2155     return a;
2156   else
2157     return b;
2158 }
2159
2160 int ViewerMainLoop(Standard_Integer argc, const char** argv)
2161
2162 {
2163   static XEvent aReport;
2164   Standard_Boolean pick = argc > 0;
2165   Display *aDisplay = GetDisplayConnection()->GetDisplay();
2166   XNextEvent (aDisplay, &aReport);
2167
2168   // Handle event for the chosen display connection
2169   switch (aReport.type) {
2170       case ClientMessage:
2171         {
2172           if((Atom)aReport.xclient.data.l[0] == GetDisplayConnection()->GetAtom(Aspect_XA_DELETE_WINDOW))
2173           {
2174             // Close the window
2175             ViewerTest::RemoveView(FindViewIdByWindowHandle (aReport.xclient.window));
2176           }
2177         }
2178         return 0;
2179      case FocusIn:
2180       {
2181          // Activate inactive view
2182          Window aWindow = GetWindowHandle(VT_GetWindow());
2183          if(aWindow != aReport.xfocus.window)
2184          {
2185            ActivateView (FindViewIdByWindowHandle (aReport.xfocus.window));
2186          }
2187       }
2188       break;
2189       case Expose:
2190         {
2191           VT_ProcessExpose();
2192         }
2193         break;
2194       case ConfigureNotify:
2195         {
2196           VT_ProcessConfigure();
2197         }
2198         break;
2199       case KeyPress:
2200         {
2201
2202           KeySym ks_ret ;
2203           char buf_ret[11] ;
2204           int ret_len ;
2205           XComposeStatus status_in_out;
2206
2207           ret_len = XLookupString( ( XKeyEvent *)&aReport ,
2208             (char *) buf_ret , 10 ,
2209             &ks_ret , &status_in_out ) ;
2210
2211
2212           buf_ret[ret_len] = '\0' ;
2213
2214           if (ret_len)
2215           {
2216             VT_ProcessKeyPress (buf_ret);
2217           }
2218         }
2219         break;
2220       case ButtonPress:
2221         {
2222           X_ButtonPress = aReport.xbutton.x;
2223           Y_ButtonPress = aReport.xbutton.y;
2224
2225           if (aReport.xbutton.button == Button1)
2226           {
2227             if (aReport.xbutton.state & ControlMask)
2228             {
2229               pick = VT_ProcessButton1Press (argc, argv, pick, (aReport.xbutton.state & ShiftMask));
2230             }
2231             else
2232             {
2233               IsDragged = Standard_True;
2234               DragFirst = Standard_True;
2235             }
2236           }
2237           else if (aReport.xbutton.button == Button3)
2238           {
2239             // Start rotation
2240             VT_ProcessButton3Press();
2241           }
2242         }
2243         break;
2244       case ButtonRelease:
2245         {
2246           if( IsDragged )
2247           {
2248             if( !DragFirst )
2249             {
2250               Aspect_Handle aWindow = VT_GetWindow()->XWindow();
2251               GC gc = XCreateGC( aDisplay, aWindow, 0, 0 );
2252               XDrawRectangle( aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2253             }
2254
2255             Handle( AIS_InteractiveContext ) aContext = ViewerTest::GetAISContext();
2256             if( aContext.IsNull() )
2257             {
2258               cout << "The context is null. Please use vinit before createmesh" << endl;
2259               return 0;
2260             }
2261
2262             Standard_Boolean ShiftPressed = ( aReport.xbutton.state & ShiftMask );
2263             if( aReport.xbutton.button==1 )
2264               if( DragFirst )
2265                 if( ShiftPressed )
2266                 {
2267                   aContext->ShiftSelect();
2268                 }
2269                 else
2270                 {
2271                   aContext->Select();
2272                 }
2273               else
2274                 if( ShiftPressed )
2275                 {
2276                   aContext->ShiftSelect( min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ),
2277                     max( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
2278                     ViewerTest::CurrentView());
2279                 }
2280                 else
2281                 {
2282                   aContext->Select( min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ),
2283                     max( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
2284                     ViewerTest::CurrentView() );
2285                 }
2286             else
2287               VT_ProcessButton3Release();
2288
2289             IsDragged = Standard_False;
2290           }
2291           else
2292             VT_ProcessButton3Release();
2293         }
2294         break;
2295       case MotionNotify:
2296         {
2297           if (GetWindowHandle (VT_GetWindow()) != aReport.xmotion.window)
2298           {
2299             break;
2300           }
2301           if( IsDragged )
2302           {
2303             Aspect_Handle aWindow = VT_GetWindow()->XWindow();
2304             GC gc = XCreateGC( aDisplay, aWindow, 0, 0 );
2305             XSetFunction( aDisplay, gc, GXinvert );
2306
2307             if( !DragFirst )
2308               XDrawRectangle(aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2309
2310             X_Motion = aReport.xmotion.x;
2311             Y_Motion = aReport.xmotion.y;
2312             DragFirst = Standard_False;
2313
2314             XDrawRectangle( aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2315           }
2316           else
2317           {
2318             X_Motion = aReport.xmotion.x;
2319             Y_Motion = aReport.xmotion.y;
2320
2321             // remove all the ButtonMotionMaskr
2322             while( XCheckMaskEvent( aDisplay, ButtonMotionMask, &aReport) ) ;
2323
2324             if ( ZClipIsOn && aReport.xmotion.state & ShiftMask ) {
2325               if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
2326
2327                 Quantity_Length VDX, VDY;
2328
2329                 ViewerTest::CurrentView()->Size(VDX,VDY);
2330                 Standard_Real VDZ =0 ;
2331                 VDZ = ViewerTest::CurrentView()->ZSize();
2332
2333                 printf("%f,%f,%f\n", VDX, VDY, VDZ);
2334
2335                 Quantity_Length dx = 0 ;
2336                 dx = ViewerTest::CurrentView()->Convert(X_Motion - X_ButtonPress);
2337
2338                 cout << dx << endl;
2339
2340                 dx = dx / VDX * VDZ;
2341
2342                 cout << dx << endl;
2343
2344                 ViewerTest::CurrentView()->Redraw();
2345               }
2346             }
2347
2348             if ( aReport.xmotion.state & ControlMask ) {
2349               if ( aReport.xmotion.state & Button1Mask ) {
2350                 ProcessControlButton1Motion();
2351               }
2352               else if ( aReport.xmotion.state & Button2Mask ) {
2353                 VT_ProcessControlButton2Motion();
2354               }
2355               else if ( aReport.xmotion.state & Button3Mask ) {
2356                 VT_ProcessControlButton3Motion();
2357               }
2358             }
2359             else
2360             {
2361               VT_ProcessMotion();
2362             }
2363           }
2364         }
2365         break;
2366 }
2367 return pick;
2368 }
2369
2370 //==============================================================================
2371 //function : VProcessEvents
2372 //purpose  : call by Tk_CreateFileHandler() to be able to manage the
2373 //       event in the Viewer window
2374 //==============================================================================
2375
2376 static void VProcessEvents(ClientData,int)
2377 {
2378   NCollection_Vector<int> anEventNumbers;
2379   // Get number of messages from every display
2380   for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
2381        anIter (ViewerTest_myDrivers); anIter.More(); anIter.Next())
2382   {
2383     anEventNumbers.Append(XPending (anIter.Key2()->GetDisplayConnection()->GetDisplay()));
2384   }
2385     // Handle events for every display
2386   int anEventIter = 0;
2387   for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
2388        anIter (ViewerTest_myDrivers); anIter.More(); anIter.Next(), anEventIter++)
2389   {
2390     for (int i = 0; i < anEventNumbers.Value(anEventIter) &&
2391          XPending (anIter.Key2()->GetDisplayConnection()->GetDisplay()) > 0; ++i)
2392     {
2393       SetDisplayConnection (anIter.Key2()->GetDisplayConnection());
2394       int anEventResult = ViewerMainLoop( 0, NULL);
2395       // If window is closed or context was not found finish current event processing loop
2396       if (!anEventResult)
2397         return;
2398     }
2399   }
2400
2401   SetDisplayConnection (ViewerTest::GetAISContext()->CurrentViewer()->Driver()->GetDisplayConnection());
2402
2403 }
2404 #endif
2405
2406 //==============================================================================
2407 //function : OSWindowSetup
2408 //purpose  : Setup for the X11 window to be able to cath the event
2409 //==============================================================================
2410
2411
2412 static void OSWindowSetup()
2413 {
2414 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
2415   // X11
2416
2417   Window  window   = VT_GetWindow()->XWindow();
2418   SetDisplayConnection (ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
2419   Display *aDisplay = GetDisplayConnection()->GetDisplay();
2420   XSynchronize(aDisplay, 1);
2421
2422   // X11 : For keyboard on SUN
2423   XWMHints wmhints;
2424   wmhints.flags = InputHint;
2425   wmhints.input = 1;
2426
2427   XSetWMHints( aDisplay, window, &wmhints);
2428
2429   XSelectInput( aDisplay, window,  ExposureMask | KeyPressMask |
2430     ButtonPressMask | ButtonReleaseMask |
2431     StructureNotifyMask |
2432     PointerMotionMask |
2433     Button1MotionMask | Button2MotionMask |
2434     Button3MotionMask | FocusChangeMask
2435     );
2436   Atom aDeleteWindowAtom = GetDisplayConnection()->GetAtom(Aspect_XA_DELETE_WINDOW);
2437   XSetWMProtocols(aDisplay, window, &aDeleteWindowAtom, 1);
2438
2439   XSynchronize(aDisplay, 0);
2440
2441 #else
2442   // WNT
2443 #endif
2444
2445 }
2446
2447
2448 //==============================================================================
2449 //function : VFit
2450
2451 //purpose  : Fitall, no DRAW arguments
2452 //Draw arg : No args
2453 //==============================================================================
2454
2455 static int VFit(Draw_Interpretor& , Standard_Integer , const char** )
2456 {
2457   const Handle(V3d_View) aView = ViewerTest::CurrentView();
2458   Handle(NIS_View) V = Handle(NIS_View)::DownCast(aView);
2459   if (V.IsNull() == Standard_False) {
2460     V->FitAll3d();
2461   } else if (aView.IsNull() == Standard_False) {
2462     aView->FitAll();
2463   }
2464   return 0;
2465 }
2466
2467 //==============================================================================
2468 //function : VZFit
2469 //purpose  : ZFitall, no DRAW arguments
2470 //Draw arg : No args
2471 //==============================================================================
2472 static int VZFit (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb, const char** theArgVec)
2473 {
2474   const Handle(V3d_View)& aCurrentView = ViewerTest::CurrentView();
2475
2476   if (aCurrentView.IsNull())
2477   {
2478     std::cout << theArgVec[0] << ": Call vinit before this command, please.\n";
2479     return 1;
2480   }
2481
2482   if (theArgsNb == 1)
2483   {
2484     aCurrentView->ZFitAll();
2485     aCurrentView->Redraw();
2486     return 0;
2487   }
2488
2489   Standard_Real aScale = 1.0;
2490
2491   if (theArgsNb >= 2)
2492   {
2493     aScale = Draw::Atoi (theArgVec[1]);
2494   }
2495
2496   aCurrentView->ZFitAll (aScale);
2497   aCurrentView->Redraw();
2498
2499   return 0;
2500 }
2501
2502 //==============================================================================
2503 //function : VRepaint
2504 //purpose  :
2505 //==============================================================================
2506 static int VRepaint (Draw_Interpretor& , Standard_Integer , const char** )
2507 {
2508   Handle(V3d_View) V = ViewerTest::CurrentView();
2509   if ( !V.IsNull() ) V->Redraw(); return 0;
2510 }
2511
2512 //==============================================================================
2513 //function : VClear
2514 //purpose  : Remove all the object from the viewer
2515 //Draw arg : No args
2516 //==============================================================================
2517
2518 static int VClear(Draw_Interpretor& , Standard_Integer , const char** )
2519 {
2520   Handle(V3d_View) V = ViewerTest::CurrentView();
2521   if(!V.IsNull())
2522     ViewerTest::Clear();
2523   return 0;
2524 }
2525
2526 //==============================================================================
2527 //function : VPick
2528 //purpose  :
2529 //==============================================================================
2530
2531 static int VPick(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2532 { if (ViewerTest::CurrentView().IsNull() ) return 1;
2533
2534 if ( argc < 4 ) {
2535   di << argv[0] << "Invalid number of arguments" << "\n";
2536   return 1;
2537 }
2538
2539 while (ViewerMainLoop( argc, argv)) {
2540 }
2541
2542 return 0;
2543 }
2544
2545 //==============================================================================
2546 //function : VSetBg
2547 //purpose  : Load image as background
2548 //==============================================================================
2549
2550 static int VSetBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2551 {
2552   if (argc < 2 || argc > 3)
2553   {
2554     di << "Usage : " << argv[0] << " imagefile [filltype] : Load image as background" << "\n";
2555     di << "filltype can be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2556     return 1;
2557   }
2558
2559   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2560   if(AISContext.IsNull())
2561   {
2562     di << "use 'vinit' command before " << argv[0] << "\n";
2563     return 1;
2564   }
2565
2566   Aspect_FillMethod aFillType = Aspect_FM_CENTERED;
2567   if (argc == 3)
2568   {
2569     const char* szType = argv[2];
2570     if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
2571     else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
2572     else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
2573     else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
2574     else
2575     {
2576       di << "Wrong fill type : " << szType << "\n";
2577       di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2578       return 1;
2579     }
2580   }
2581
2582   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2583   V3dView->SetBackgroundImage(argv[1], aFillType, Standard_True);
2584
2585   return 0;
2586 }
2587
2588 //==============================================================================
2589 //function : VSetBgMode
2590 //purpose  : Change background image fill type
2591 //==============================================================================
2592
2593 static int VSetBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2594 {
2595   if (argc != 2)
2596   {
2597     di << "Usage : " << argv[0] << " filltype : Change background image mode" << "\n";
2598     di << "filltype must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2599     return 1;
2600   }
2601
2602   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2603   if(AISContext.IsNull())
2604   {
2605     di << "use 'vinit' command before " << argv[0] << "\n";
2606     return 1;
2607   }
2608   Aspect_FillMethod aFillType = Aspect_FM_NONE;
2609   const char* szType = argv[1];
2610   if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
2611   else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
2612   else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
2613   else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
2614   else
2615   {
2616     di << "Wrong fill type : " << szType << "\n";
2617     di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2618     return 1;
2619   }
2620   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2621   V3dView->SetBgImageStyle(aFillType, Standard_True);
2622   return 0;
2623 }
2624
2625 //==============================================================================
2626 //function : VSetGradientBg
2627 //purpose  : Mount gradient background
2628 //==============================================================================
2629 static int VSetGradientBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2630 {
2631   if (argc != 8 )
2632   {
2633     di << "Usage : " << argv[0] << " R1 G1 B1 R2 G2 B2 Type : Mount gradient background" << "\n";
2634     di << "R1,G1,B1,R2,G2,B2 = [0..255]" << "\n";
2635     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2636     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2637     return 1;
2638   }
2639
2640   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2641   if(AISContext.IsNull())
2642   {
2643     di << "use 'vinit' command before " << argv[0] << "\n";
2644     return 1;
2645   }
2646   if (argc == 8)
2647   {
2648
2649     Standard_Real R1 = Draw::Atof(argv[1])/255.;
2650     Standard_Real G1 = Draw::Atof(argv[2])/255.;
2651     Standard_Real B1 = Draw::Atof(argv[3])/255.;
2652     Quantity_Color aColor1(R1,G1,B1,Quantity_TOC_RGB);
2653
2654     Standard_Real R2 = Draw::Atof(argv[4])/255.;
2655     Standard_Real G2 = Draw::Atof(argv[5])/255.;
2656     Standard_Real B2 = Draw::Atof(argv[6])/255.;
2657
2658     Quantity_Color aColor2(R2,G2,B2,Quantity_TOC_RGB);
2659     int aType = Draw::Atoi(argv[7]);
2660     if( aType < 0 || aType > 8 )
2661     {
2662       di << "Wrong fill type " << "\n";
2663       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2664       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2665       return 1;
2666     }
2667
2668     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
2669
2670     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2671     V3dView->SetBgGradientColors( aColor1, aColor2, aMethod, 1);
2672   }
2673
2674   return 0;
2675 }
2676
2677 //==============================================================================
2678 //function : VSetGradientBgMode
2679 //purpose  : Change gradient background fill style
2680 //==============================================================================
2681 static int VSetGradientBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2682 {
2683   if (argc != 2 )
2684   {
2685     di << "Usage : " << argv[0] << " Type : Change gradient background fill type" << "\n";
2686     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2687     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2688     return 1;
2689   }
2690
2691   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2692   if(AISContext.IsNull())
2693   {
2694     di << "use 'vinit' command before " << argv[0] << "\n";
2695     return 1;
2696   }
2697   if (argc == 2)
2698   {
2699     int aType = Draw::Atoi(argv[1]);
2700     if( aType < 0 || aType > 8 )
2701     {
2702       di << "Wrong fill type " << "\n";
2703       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2704       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2705       return 1;
2706     }
2707
2708     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
2709
2710     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2711     V3dView->SetBgGradientStyle( aMethod, 1 );
2712   }
2713
2714   return 0;
2715 }
2716
2717 //==============================================================================
2718 //function : VSetColorBg
2719 //purpose  : Set color background
2720 //==============================================================================
2721 static int VSetColorBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2722 {
2723   if (argc != 4 )
2724   {
2725     di << "Usage : " << argv[0] << " R G B : Set color background" << "\n";
2726     di << "R,G,B = [0..255]" << "\n";
2727     return 1;
2728   }
2729
2730   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2731   if(AISContext.IsNull())
2732   {
2733     di << "use 'vinit' command before " << argv[0] << "\n";
2734     return 1;
2735   }
2736   if (argc == 4)
2737   {
2738
2739     Standard_Real R = Draw::Atof(argv[1])/255.;
2740     Standard_Real G = Draw::Atof(argv[2])/255.;
2741     Standard_Real B = Draw::Atof(argv[3])/255.;
2742     Quantity_Color aColor(R,G,B,Quantity_TOC_RGB);
2743
2744     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2745     V3dView->SetBackgroundColor( aColor );
2746     V3dView->Update();
2747   }
2748
2749   return 0;
2750 }
2751
2752 //==============================================================================
2753 //function : VScale
2754 //purpose  : View Scaling
2755 //==============================================================================
2756
2757 static int VScale(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2758 {
2759   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2760   if ( V3dView.IsNull() ) return 1;
2761
2762   if ( argc != 4 ) {
2763     di << argv[0] << "Invalid number of arguments" << "\n";
2764     return 1;
2765   }
2766   V3dView->SetAxialScale( Draw::Atof(argv[1]),  Draw::Atof(argv[2]),  Draw::Atof(argv[3]) );
2767   return 0;
2768 }
2769 //==============================================================================
2770 //function : VTestZBuffTrihedron
2771 //purpose  : Displays a V3d_ZBUFFER'ed or V3d_WIREFRAME'd trihedron
2772 //==============================================================================
2773
2774 static int VTestZBuffTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2775 {
2776   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2777   if ( V3dView.IsNull() ) return 1;
2778
2779   V3dView->ZBufferTriedronSetup();
2780
2781   if ( argc == 1 ) {
2782     // Set up default trihedron parameters
2783     V3dView->TriedronDisplay( Aspect_TOTP_LEFT_LOWER, Quantity_NOC_WHITE, 0.1, V3d_ZBUFFER );
2784   } else
2785   if ( argc == 7 )
2786   {
2787     Aspect_TypeOfTriedronPosition aPosition = Aspect_TOTP_LEFT_LOWER;
2788     const char* aPosType = argv[1];
2789
2790     if ( strcmp(aPosType, "center") == 0 )
2791     {
2792       aPosition = Aspect_TOTP_CENTER;
2793     } else
2794     if (strcmp(aPosType, "left_lower") == 0)
2795     {
2796       aPosition = Aspect_TOTP_LEFT_LOWER;
2797     } else
2798     if (strcmp(aPosType, "left_upper") == 0)
2799     {
2800       aPosition = Aspect_TOTP_LEFT_UPPER;
2801     } else
2802     if (strcmp(aPosType, "right_lower") == 0)
2803     {
2804       aPosition = Aspect_TOTP_RIGHT_LOWER;
2805     } else
2806     if (strcmp(aPosType, "right_upper") == 0)
2807     {
2808       aPosition = Aspect_TOTP_RIGHT_UPPER;
2809     } else
2810     {
2811       di << argv[1] << " Invalid type of alignment"  << "\n";
2812       di << "Must be one of [ center, left_lower,"   << "\n";
2813       di << "left_upper, right_lower, right_upper ]" << "\n";
2814       return 1;
2815     }
2816
2817     Standard_Real R = Draw::Atof(argv[2])/255.;
2818     Standard_Real G = Draw::Atof(argv[3])/255.;
2819     Standard_Real B = Draw::Atof(argv[4])/255.;
2820     Quantity_Color aColor(R, G, B, Quantity_TOC_RGB);
2821
2822     Standard_Real aScale = Draw::Atof(argv[5]);
2823
2824     if( aScale <= 0.0 )
2825     {
2826       di << argv[5] << " Invalid value. Must be > 0" << "\n";
2827       return 1;
2828     }
2829
2830     V3d_TypeOfVisualization aPresentation = V3d_ZBUFFER;
2831     const char* aPresType = argv[6];
2832
2833     if ( strcmp(aPresType, "wireframe") == 0 )
2834     {
2835       aPresentation = V3d_WIREFRAME;
2836     } else
2837     if (strcmp(aPresType, "zbuffer") == 0)
2838     {
2839       aPresentation = V3d_ZBUFFER;
2840     } else
2841     {
2842       di << argv[6] << " Invalid type of visualization" << "\n";
2843       di << "Must be one of [ wireframe, zbuffer ]"     << "\n";
2844       return 1;
2845     }
2846
2847     V3dView->TriedronDisplay( aPosition, aColor.Name(), aScale, aPresentation );
2848
2849   } else
2850   {
2851     di << argv[0] << " Invalid number of arguments" << "\n";
2852     return 1;
2853   }
2854
2855   V3dView->ZFitAll();
2856
2857   return 0;
2858 }
2859
2860 //==============================================================================
2861 //function : VRotate
2862 //purpose  : Camera Rotating
2863 //==============================================================================
2864
2865 static int VRotate( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2866   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2867   if ( V3dView.IsNull() ) {
2868     return 1;
2869   }
2870
2871   if ( argc == 4 ) {
2872     V3dView->Rotate( Draw::Atof(argv[1]), Draw::Atof(argv[2]), Draw::Atof(argv[3]) );
2873     return 0;
2874   } else if ( argc == 7 ) {
2875     V3dView->Rotate( Draw::Atof(argv[1]), Draw::Atof(argv[2]), Draw::Atof(argv[3]), Draw::Atof(argv[4]), Draw::Atof(argv[5]), Draw::Atof(argv[6]) );
2876     return 0;
2877   } else {
2878     di << argv[0] << " Invalid number of arguments" << "\n";
2879     return 1;
2880   }
2881 }
2882
2883 //==============================================================================
2884 //function : VZoom
2885 //purpose  : View zoom in / out (relative to current zoom)
2886 //==============================================================================
2887
2888 static int VZoom( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2889   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2890   if ( V3dView.IsNull() ) {
2891     return 1;
2892   }
2893
2894   if ( argc == 2 ) {
2895     Standard_Real coef = Draw::Atof(argv[1]);
2896     if ( coef <= 0.0 ) {
2897       di << argv[1] << "Invalid value" << "\n";
2898       return 1;
2899     }
2900     V3dView->SetZoom( Draw::Atof(argv[1]) );
2901     return 0;
2902   } else {
2903     di << argv[0] << " Invalid number of arguments" << "\n";
2904     return 1;
2905   }
2906 }
2907
2908 //==============================================================================
2909 //function : VPan
2910 //purpose  : View panning (in pixels)
2911 //==============================================================================
2912
2913 static int VPan( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2914   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2915   if ( V3dView.IsNull() ) return 1;
2916
2917   if ( argc == 3 ) {
2918     V3dView->Pan( Draw::Atoi(argv[1]), Draw::Atoi(argv[2]) );
2919     return 0;
2920   } else {
2921     di << argv[0] << " Invalid number of arguments" << "\n";
2922     return 1;
2923   }
2924 }
2925
2926
2927 //==============================================================================
2928 //function : VExport
2929 //purpose  : Export the view to a vector graphic format (PS, EMF, PDF)
2930 //==============================================================================
2931
2932 static int VExport(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2933 {
2934   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2935   if (V3dView.IsNull())
2936     return 1;
2937
2938   if (argc == 1)
2939   {
2940     std::cout << "Usage: " << argv[0] << " Filename [Format]\n";
2941     return 1;
2942   }
2943
2944   Graphic3d_ExportFormat anExpFormat = Graphic3d_EF_PDF;
2945   TCollection_AsciiString aFormatStr;
2946
2947   TCollection_AsciiString aFileName (argv[1]);
2948   Standard_Integer aLen = aFileName.Length();
2949
2950   if (argc > 2)
2951   {
2952     aFormatStr = TCollection_AsciiString (argv[2]);
2953   }
2954   else if (aLen >= 4)
2955   {
2956     if (aFileName.Value (aLen - 2) == '.')
2957     {
2958       aFormatStr = aFileName.SubString (aLen - 1, aLen);
2959     }
2960     else if (aFileName.Value (aLen - 3) == '.')
2961     {
2962       aFormatStr = aFileName.SubString (aLen - 2, aLen);
2963     }
2964     else
2965     {
2966       std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
2967       return 1;
2968     }
2969   }
2970   else
2971   {
2972     std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
2973     return 1;
2974   }
2975
2976   aFormatStr.UpperCase();
2977   if (aFormatStr == "PS")
2978     anExpFormat = Graphic3d_EF_PostScript;
2979   else if (aFormatStr == "EPS")
2980     anExpFormat = Graphic3d_EF_EnhPostScript;
2981   else if (aFormatStr == "TEX")
2982     anExpFormat = Graphic3d_EF_TEX;
2983   else if (aFormatStr == "PDF")
2984     anExpFormat = Graphic3d_EF_PDF;
2985   else if (aFormatStr == "SVG")
2986     anExpFormat = Graphic3d_EF_SVG;
2987   else if (aFormatStr == "PGF")
2988     anExpFormat = Graphic3d_EF_PGF;
2989   else if (aFormatStr == "EMF")
2990     anExpFormat = Graphic3d_EF_EMF;
2991   else
2992   {
2993     std::cout << "Invalid export format '" << aFormatStr << "'\n";
2994     return 1;
2995   }
2996
2997   try {
2998     if (!V3dView->View()->Export (argv[1], anExpFormat))
2999     {
3000       di << "Error: export of image to " << aFormatStr << " failed!\n";
3001     }
3002   }
3003   catch (Standard_Failure)
3004   {
3005     di << "Error: export of image to " << aFormatStr << " failed";
3006     di << " (exception: " << Standard_Failure::Caught()->GetMessageString() << ")";
3007   }
3008   return 0;
3009 }
3010
3011 //==============================================================================
3012 //function : VColorScale
3013 //purpose  : representation color scale
3014 //==============================================================================
3015 #include <V3d_ColorScale.hxx>
3016
3017 static int VColorScale (Draw_Interpretor& di, Standard_Integer argc, const char ** argv)
3018 {
3019   if ( argc != 1 && argc != 4 && argc != 5 && argc != 6 && argc != 8 )
3020   {
3021     di << "Usage : " << argv[0] << " [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = Right X = 0 Y = 0]  " << "\n";
3022     return 1;
3023   }
3024
3025   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
3026   if(aContext.IsNull()) {
3027     di << argv[0] << " ERROR : use 'vinit' command before " << "\n";
3028     return -1;
3029   }
3030
3031   Standard_Real minRange = 0. , maxRange = 100. ;
3032
3033   Standard_Integer numIntervals = 10 ;
3034   Standard_Integer textHeight = 16;
3035   Aspect_TypeOfColorScalePosition position = Aspect_TOCSP_RIGHT;
3036   Standard_Real X = 0., Y = 0. ;
3037
3038   if ( argc < 9 )
3039   {
3040      if( argc > 3 )
3041      {
3042        minRange = Draw::Atof( argv[1] );
3043        maxRange = Draw::Atof( argv[2] );
3044        numIntervals = Draw::Atoi( argv[3] );
3045      }
3046      if ( argc > 4 )
3047        textHeight = Draw::Atoi( argv[4] );
3048      if ( argc > 5 )
3049        position = (Aspect_TypeOfColorScalePosition)Draw::Atoi( argv[5] );
3050      if ( argc > 7 )
3051      {
3052        X = Draw::Atof( argv[6] );
3053        Y = Draw::Atof( argv[7] );
3054      }
3055   }
3056   Handle(V3d_View) curView = ViewerTest::CurrentView( );
3057   if ( curView.IsNull( ) )
3058     return 1;
3059   Handle(Aspect_ColorScale) aCSV = curView->ColorScale( );
3060   Handle(V3d_ColorScale) aCS = ( Handle( V3d_ColorScale )::DownCast( aCSV ) );
3061   if( ! aCS.IsNull( ) )
3062   {
3063     aCS->SetPosition( X , Y );
3064     aCS->SetHeight( 0.95) ;
3065     aCS->SetTextHeight( textHeight );
3066     aCS->SetRange( minRange , maxRange );
3067     aCS->SetNumberOfIntervals( numIntervals );
3068     aCS->SetLabelPosition( position );
3069     if( !curView->ColorScaleIsDisplayed() )
3070       curView->ColorScaleDisplay( );
3071   }
3072   return 0;
3073 }
3074
3075 //==============================================================================
3076 //function : VGraduatedTrihedron
3077 //purpose  : Displays a graduated trihedron
3078 //==============================================================================
3079
3080 static void AddMultibyteString (TCollection_ExtendedString &name, const char *arg)
3081 {
3082   const char *str = arg;
3083   while (*str)
3084   {
3085     unsigned short c1 = *str++;
3086     unsigned short c2 = *str++;
3087     if (!c1 || !c2) break;
3088     name += (Standard_ExtCharacter)((c1 << 8) | c2);
3089   }
3090 }
3091
3092 static int VGraduatedTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3093 {
3094   // Check arguments
3095   if (argc != 2 && argc < 5)
3096   {
3097     di<<"Error: "<<argv[0]<<" - invalid number of arguments\n";
3098     di<<"Usage: type help "<<argv[0]<<"\n";
3099     return 1; //TCL_ERROR
3100   }
3101
3102   Handle(V3d_View) aV3dView = ViewerTest::CurrentView();
3103
3104   // Create 3D view if it doesn't exist
3105   if ( aV3dView.IsNull() )
3106   {
3107     ViewerTest::ViewerInit();
3108     aV3dView = ViewerTest::CurrentView();
3109     if( aV3dView.IsNull() )
3110     {
3111       di << "Error: Cannot create a 3D view\n";
3112       return 1; //TCL_ERROR
3113     }
3114   }
3115
3116   // Erase (==0) or display (!=0)
3117   const int display = Draw::Atoi(argv[1]);
3118
3119   if (display)
3120   {
3121     // Text font
3122     TCollection_AsciiString font;
3123     if (argc < 6)
3124       font.AssignCat("Courier");
3125     else
3126       font.AssignCat(argv[5]);
3127
3128     // Text is multibyte
3129     const Standard_Boolean isMultibyte = (argc < 7)? Standard_False : (Draw::Atoi(argv[6]) != 0);
3130
3131     // Set axis names
3132     TCollection_ExtendedString xname, yname, zname;
3133     if (argc >= 5)
3134     {
3135       if (isMultibyte)
3136       {
3137         AddMultibyteString(xname, argv[2]);
3138         AddMultibyteString(yname, argv[3]);
3139         AddMultibyteString(zname, argv[4]);
3140       }
3141       else
3142       {
3143         xname += argv[2];
3144         yname += argv[3];
3145         zname += argv[4];
3146       }
3147     }
3148     else
3149     {
3150       xname += "X (mm)";
3151       yname += "Y (mm)";
3152       zname += "Z (mm)";
3153     }
3154
3155     aV3dView->GraduatedTrihedronDisplay(xname, yname, zname,
3156                                         Standard_True/*xdrawname*/, Standard_True/*ydrawname*/, Standard_True/*zdrawname*/,
3157                                         Standard_True/*xdrawvalues*/, Standard_True/*ydrawvalues*/, Standard_True/*zdrawvalues*/,
3158                                         Standard_True/*drawgrid*/,
3159                                         Standard_True/*drawaxes*/,
3160                                         5/*nbx*/, 5/*nby*/, 5/*nbz*/,
3161                                         10/*xoffset*/, 10/*yoffset*/, 10/*zoffset*/,
3162                                         30/*xaxisoffset*/, 30/*yaxisoffset*/, 30/*zaxisoffset*/,
3163                                         Standard_True/*xdrawtickmarks*/, Standard_True/*ydrawtickmarks*/, Standard_True/*zdrawtickmarks*/,
3164                                         10/*xtickmarklength*/, 10/*ytickmarklength*/, 10/*ztickmarklength*/,
3165                                         Quantity_NOC_WHITE/*gridcolor*/,
3166                                         Quantity_NOC_RED/*xnamecolor*/,Quantity_NOC_GREEN/*ynamecolor*/,Quantity_NOC_BLUE1/*znamecolor*/,
3167                                         Quantity_NOC_RED/*xcolor*/,Quantity_NOC_GREEN/*ycolor*/,Quantity_NOC_BLUE1/*zcolor*/,font);
3168   }
3169   else
3170     aV3dView->GraduatedTrihedronErase();
3171
3172   ViewerTest::GetAISContext()->UpdateCurrentViewer();
3173   aV3dView->Redraw();
3174
3175   return 0;
3176 }
3177
3178 //==============================================================================
3179 //function : VPrintView
3180 //purpose  : Test printing algorithm, print the view to image file with given
3181 //           width and height. Printing implemented only for WNT.
3182 //==============================================================================
3183 static int VPrintView (Draw_Interpretor& di, Standard_Integer argc,
3184                        const char** argv)
3185 {
3186 #ifndef WNT
3187   di << "Printing implemented only for wnt!\n";
3188   return 0;
3189 #else
3190
3191   Handle(AIS_InteractiveContext) aContextAIS = NULL;
3192   Handle(V3d_View) aView = NULL;
3193   aContextAIS = ViewerTest::GetAISContext();
3194   if (!aContextAIS.IsNull())
3195   {
3196     const Handle(V3d_Viewer)& Vwr = aContextAIS->CurrentViewer();
3197     Vwr->InitActiveViews();
3198     if(Vwr->MoreActiveViews())
3199       aView = Vwr->ActiveView();
3200   }
3201
3202   // check for errors
3203   if (aView.IsNull())
3204   {
3205     di << "Call vinit before!\n";
3206     return 1;
3207   }
3208   else if (argc < 4)
3209   {
3210     di << "Use: " << argv[0];
3211     di << " width height filename [print algo=0] [tile_width tile_height]\n";
3212     di << "width, height of the intermediate buffer for operation\n";
3213     di << "algo : {0|1}\n";
3214     di << "        0 - stretch algorithm\n";
3215     di << "        1 - tile algorithm\n";
3216     di << "test printing algorithms into an intermediate buffer\n";
3217     di << "using specific tile size if provided\n";
3218     di << "with saving output to an image file\n";
3219     return 1;
3220   }
3221
3222   // get the input params
3223   Standard_Integer aWidth  = Draw::Atoi (argv[1]);
3224   Standard_Integer aHeight = Draw::Atoi (argv[2]);
3225   Standard_Integer aMode   = 0;
3226   TCollection_AsciiString aFileName = TCollection_AsciiString (argv[3]);
3227   if (argc >= 5)
3228     aMode = Draw::Atoi (argv[4]);
3229
3230   Standard_Integer aTileWidth  = 0;
3231   Standard_Integer aTileHeight = 0;
3232   Standard_Boolean isTileSizeProvided = Standard_False;
3233   if (argc == 7)
3234   {
3235     isTileSizeProvided = Standard_True;
3236     aTileWidth  = Draw::Atoi (argv[5]);
3237     aTileHeight = Draw::Atoi (argv[6]);
3238   }
3239
3240   // check the input parameters
3241   if (aWidth <= 0 || aHeight <= 0)
3242   {
3243     di << "Width and height must be positive values!\n";
3244     return 1;
3245   }
3246   if (aMode != 0 && aMode != 1)
3247     aMode = 0;
3248
3249   // define compatible bitmap
3250   HDC anDC = CreateCompatibleDC(0);
3251   BITMAPINFO aBitmapData;
3252   memset (&aBitmapData, 0, sizeof (BITMAPINFOHEADER));
3253   aBitmapData.bmiHeader.biSize          = sizeof (BITMAPINFOHEADER);
3254   aBitmapData.bmiHeader.biWidth         = aWidth ;
3255   aBitmapData.bmiHeader.biHeight        = aHeight;
3256   aBitmapData.bmiHeader.biPlanes        = 1;
3257   aBitmapData.bmiHeader.biBitCount      = 24;
3258   aBitmapData.bmiHeader.biXPelsPerMeter = 0;
3259   aBitmapData.bmiHeader.biYPelsPerMeter = 0;
3260   aBitmapData.bmiHeader.biClrUsed       = 0;
3261   aBitmapData.bmiHeader.biClrImportant  = 0;
3262   aBitmapData.bmiHeader.biCompression   = BI_RGB;
3263   aBitmapData.bmiHeader.biSizeImage     = 0;
3264
3265   // Create Device Independent Bitmap
3266   void* aBitsOut = NULL;
3267   HBITMAP aMemoryBitmap = CreateDIBSection (anDC, &aBitmapData, DIB_RGB_COLORS,
3268                                             &aBitsOut, NULL, 0);
3269   HGDIOBJ anOldBitmap   = SelectObject(anDC, aMemoryBitmap);
3270
3271   Standard_Boolean isSaved = Standard_False, isPrinted = Standard_False;
3272   if (aBitsOut != NULL)
3273   {
3274     if (aMode == 0)
3275       isPrinted = aView->Print(anDC,1,1,0,Aspect_PA_STRETCH);
3276     else
3277     {
3278       if (isTileSizeProvided)
3279       {
3280         Graphic3d_CView* aCView = static_cast<Graphic3d_CView*> (ViewerTest::CurrentView()->View()->CView());
3281         Graphic3d_PtrFrameBuffer anOldBuffer = static_cast<Graphic3d_PtrFrameBuffer> (aCView->ptrFBO);
3282         aCView->ptrFBO = aView->View()->FBOCreate (aTileWidth, aTileHeight);
3283
3284         isPrinted = aView->Print (anDC, 1, 1, 0, Aspect_PA_TILE);
3285
3286         Graphic3d_PtrFrameBuffer aNewBuffer = static_cast<Graphic3d_PtrFrameBuffer> (aCView->ptrFBO);
3287         aView->View()->FBORelease (aNewBuffer);
3288         aCView->ptrFBO = anOldBuffer;
3289       }
3290       else
3291       {
3292         isPrinted = aView->Print (anDC, 1, 1, 0, Aspect_PA_TILE);
3293       }
3294     }
3295
3296     // succesfully printed into an intermediate buffer
3297     if (isPrinted)
3298     {
3299       Image_PixMap aWrapper;
3300       aWrapper.InitWrapper (Image_PixMap::ImgBGR, (Standard_Byte* )aBitsOut, aWidth, aHeight, aWidth * 3 + aWidth % 4);
3301       aWrapper.SetTopDown (false);
3302
3303       Image_AlienPixMap anImageBitmap;
3304       anImageBitmap.InitCopy (aWrapper);
3305       isSaved = anImageBitmap.Save (aFileName);
3306     }
3307     else
3308     {
3309       di << "Print operation failed due to printing errors or\n";
3310       di << "insufficient memory available\n";
3311       di << "Please, try to use smaller dimensions for this test\n";
3312       di << "command, as it allocates intermediate buffer for storing\n";
3313       di << "the result\n";
3314     }
3315   }
3316   else
3317   {
3318     di << "Can't allocate memory for intermediate buffer\n";
3319     di << "Please use smaller dimensions\n";
3320   }
3321
3322   if (aMemoryBitmap)
3323   {
3324     SelectObject (anDC, anOldBitmap);
3325     DeleteObject (aMemoryBitmap);
3326     DeleteDC(anDC);
3327   }
3328
3329   if (!isSaved)
3330   {
3331     di << "Save to file operation failed. This operation may fail\n";
3332     di << "if you don't have enough available memory, then you can\n";
3333     di << "use smaller dimensions for the output file\n";
3334     return 1;
3335   }
3336
3337   return 0;
3338
3339 #endif
3340 }
3341
3342 //==============================================================================
3343 //function : VZLayer
3344 //purpose  : Test z layer operations for v3d viewer
3345 //==============================================================================
3346 static int VZLayer (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3347 {
3348   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext ();
3349   if (aContextAIS.IsNull())
3350   {
3351     di << "Call vinit before!\n";
3352     return 1;
3353   }
3354   else if (argc < 2)
3355   {
3356     di << "Use: vzlayer ";
3357     di << " add/del/get/settings/enable/disable [id]\n";
3358     di << " add - add new z layer to viewer and print its id\n";
3359     di << " del - del z layer by its id\n";
3360     di << " get - print sequence of z layers in increasing order of their overlay level\n";
3361     di << " settings - print status of z layer settings\n";
3362     di << " enable ([depth]test/[depth]write/[depth]clear/[depth]offset) \n    enables given setting for the z layer\n";
3363     di << " enable (p[ositive]offset/n[egative]offset) \n    enables given setting for the z layer\n";
3364     di << " disable ([depth]test/[depth]write/[depth]clear/[depth]offset) \n    disables given setting for the z layer\n";
3365     di << "\nWhere id is the layer identificator\n";
3366     di << "\nExamples:\n";
3367     di << "   vzlayer add\n";
3368     di << "   vzlayer enable poffset 1\n";
3369     di << "   vzlayer disable depthtest 1\n";
3370     di << "   vzlayer del 1\n";
3371     return 1;
3372   }
3373
3374   const Handle(V3d_Viewer)& aViewer = aContextAIS->CurrentViewer();
3375   if (aViewer.IsNull())
3376   {
3377     di << "No active viewer!\n";
3378     return 1;
3379   }
3380
3381   // perform operation
3382   TCollection_AsciiString anOp = TCollection_AsciiString (argv[1]);
3383   if (anOp == "add")
3384   {
3385     Standard_Integer aNewId;
3386     if (!aViewer->AddZLayer (aNewId))
3387     {
3388       di << "Impossible to add new z layer!\n";
3389       return 1;
3390     }
3391
3392     di << "New z layer added with index: " << aNewId << "\n";
3393   }
3394   else if (anOp == "del")
3395   {
3396     if (argc < 3)
3397     {
3398       di << "Please also provide as argument id of z layer to remove\n";
3399       return 1;
3400     }
3401
3402     Standard_Integer aDelId = Draw::Atoi (argv[2]);
3403     if (!aViewer->RemoveZLayer (aDelId))
3404     {
3405       di << "Impossible to remove the z layer or invalid id!\n";
3406       return 1;
3407     }
3408
3409     di << "Z layer " << aDelId << " has been removed\n";
3410   }
3411   else if (anOp == "get")
3412   {
3413     TColStd_SequenceOfInteger anIds;
3414     aViewer->GetAllZLayers (anIds);
3415     for (Standard_Integer aSeqIdx = 1; aSeqIdx <= anIds.Length(); aSeqIdx++)
3416     {
3417       di << anIds.Value (aSeqIdx) << " ";
3418     }
3419
3420     di << "\n";
3421   }
3422   else if (anOp == "settings")
3423   {
3424     if (argc < 3)
3425     {
3426       di << "Please also provide an id\n";
3427       return 1;
3428     }
3429
3430     Standard_Integer anId = Draw::Atoi (argv[2]);
3431     Graphic3d_ZLayerSettings aSettings = aViewer->ZLayerSettings (anId);
3432
3433     di << "Depth test - " << (aSettings.IsSettingEnabled (Graphic3d_ZLayerDepthTest) ? "enabled" : "disabled") << "\n";
3434     di << "Depth write - " << (aSettings.IsSettingEnabled (Graphic3d_ZLayerDepthWrite) ? "enabled" : "disabled") << "\n";
3435     di << "Depth buffer clearing - " << (aSettings.IsSettingEnabled (Graphic3d_ZLayerDepthClear) ? "enabled" : "disabled") << "\n";
3436     di << "Depth offset - " << (aSettings.IsSettingEnabled (Graphic3d_ZLayerDepthOffset) ? "enabled" : "disabled") << "\n";
3437
3438   }
3439   else if (anOp == "enable")
3440   {
3441     if (argc < 3)
3442     {
3443       di << "Please also provide an option to enable\n";
3444       return 1;
3445     }
3446
3447     if (argc < 4)
3448     {
3449       di << "Please also provide a layer id\n";
3450       return 1;
3451     }
3452
3453     TCollection_AsciiString aSubOp = TCollection_AsciiString (argv[2]);
3454     Standard_Integer anId = Draw::Atoi (argv[3]);
3455     Graphic3d_ZLayerSettings aSettings = aViewer->ZLayerSettings (anId);
3456
3457     if (aSubOp == "depthtest" || aSubOp == "test")
3458     {
3459       aSettings.EnableSetting (Graphic3d_ZLayerDepthTest);
3460     }
3461     else if (aSubOp == "depthwrite" || aSubOp == "write")
3462     {
3463       aSettings.EnableSetting (Graphic3d_ZLayerDepthWrite);
3464     }
3465     else if (aSubOp == "depthclear" || aSubOp == "clear")
3466     {
3467       aSettings.EnableSetting (Graphic3d_ZLayerDepthClear);
3468     }
3469     else if (aSubOp == "depthoffset" || aSubOp == "offset")
3470     {
3471       if (argc < 6)
3472       {
3473         di << "Please also provide a factor and units values for depth offset\n";
3474         di << "Format is: vzlayer enable offset [factor] [units] [layerId]\n";
3475         return 1;
3476       }
3477
3478       Standard_ShortReal aFactor = static_cast<Standard_ShortReal> (Draw::Atof (argv[3]));
3479       Standard_ShortReal aUnits  = static_cast<Standard_ShortReal> (Draw::Atof (argv[4]));
3480       anId = Draw::Atoi (argv[5]);
3481       aSettings = aViewer->ZLayerSettings (anId);
3482
3483       aSettings.DepthOffsetFactor = aFactor;
3484       aSettings.DepthOffsetUnits  = aUnits;
3485
3486       aSettings.EnableSetting (Graphic3d_ZLayerDepthOffset);
3487     }
3488     else if (aSubOp == "positiveoffset" || aSubOp == "poffset")
3489     {
3490       aSettings.SetDepthOffsetPositive();
3491     }
3492     else if (aSubOp == "negativeoffset" || aSubOp == "noffset")
3493     {
3494       aSettings.SetDepthOffsetNegative();
3495     }
3496
3497     aViewer->SetZLayerSettings (anId, aSettings);
3498   }
3499   else if (anOp == "disable")
3500   {
3501     if (argc < 3)
3502     {
3503       di << "Please also provide an option to disable\n";
3504       return 1;
3505     }
3506
3507     if (argc < 4)
3508     {
3509       di << "Please also provide a layer id\n";
3510       return 1;
3511     }
3512
3513     TCollection_AsciiString aSubOp = TCollection_AsciiString (argv[2]);
3514     Standard_Integer anId = Draw::Atoi (argv[3]);
3515     Graphic3d_ZLayerSettings aSettings = aViewer->ZLayerSettings (anId);
3516
3517     if (aSubOp == "depthtest" || aSubOp == "test")
3518     {
3519       aSettings.DisableSetting (Graphic3d_ZLayerDepthTest);
3520     }
3521     else if (aSubOp == "depthwrite" || aSubOp == "write")
3522     {
3523       aSettings.DisableSetting (Graphic3d_ZLayerDepthWrite);
3524     }
3525     else if (aSubOp == "depthclear" || aSubOp == "clear")
3526     {
3527       aSettings.DisableSetting (Graphic3d_ZLayerDepthClear);
3528     }
3529     else if (aSubOp == "depthoffset" || aSubOp == "offset")
3530     {
3531       aSettings.DisableSetting (Graphic3d_ZLayerDepthOffset);
3532     }
3533
3534     aViewer->SetZLayerSettings (anId, aSettings);
3535   }
3536   else
3537   {
3538     di << "Invalid operation, please use { add / del / get / settings / enable / disable}\n";
3539     return 1;
3540   }
3541
3542   return 0;
3543 }
3544
3545 DEFINE_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
3546
3547 // this class provides a presentation of text item in v3d view under-/overlayer
3548 class V3d_TextItem : public Visual3d_LayerItem
3549 {
3550 public:
3551
3552   // CASCADE RTTI
3553   DEFINE_STANDARD_RTTI(V3d_TextItem)
3554
3555   // constructor
3556   Standard_EXPORT V3d_TextItem(const TCollection_AsciiString& theText,
3557                                const Standard_Real theX1,
3558                                const Standard_Real theY1,
3559                                const Standard_Real theHeight,
3560                                const TCollection_AsciiString& theFontName,
3561                                const Quantity_Color& theColor,
3562                                const Quantity_Color& theSubtitleColor,
3563                                const Aspect_TypeOfDisplayText& theTypeOfDisplay,
3564                                const Handle(Visual3d_Layer)& theLayer);
3565
3566   // redraw method
3567   Standard_EXPORT void RedrawLayerPrs();
3568
3569 private:
3570
3571   Standard_Real            myX1;
3572   Standard_Real            myY1;
3573   TCollection_AsciiString  myText;
3574   Standard_Real            myHeight;
3575   Handle(Visual3d_Layer)   myLayer;
3576   Quantity_Color           myColor;
3577   Quantity_Color           mySubtitleColor;
3578   Aspect_TypeOfDisplayText myType;
3579   TCollection_AsciiString  myFontName;
3580 };
3581
3582 IMPLEMENT_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
3583 IMPLEMENT_STANDARD_RTTIEXT(V3d_TextItem, Visual3d_LayerItem)
3584
3585 // create and add to display the text item
3586 V3d_TextItem::V3d_TextItem (const TCollection_AsciiString& theText,
3587                             const Standard_Real theX1,
3588                             const Standard_Real theY1,
3589                             const Standard_Real theHeight,
3590                             const TCollection_AsciiString& theFontName,
3591                             const Quantity_Color& theColor,
3592                             const Quantity_Color& theSubtitleColor,
3593                             const Aspect_TypeOfDisplayText& theTypeOfDisplay,
3594                             const Handle(Visual3d_Layer)& theLayer)
3595  : myX1 (theX1), myY1 (theY1),
3596    myText (theText),
3597    myHeight (theHeight),
3598    myLayer (theLayer),
3599    myColor (theColor),
3600    mySubtitleColor (theSubtitleColor),
3601    myType (theTypeOfDisplay),
3602    myFontName (theFontName)
3603 {
3604   if (!myLayer.IsNull ())
3605     myLayer->AddLayerItem (this);
3606 }
3607
3608 // render item
3609 void V3d_TextItem::RedrawLayerPrs ()
3610 {
3611   if (myLayer.IsNull ())
3612     return;
3613
3614   myLayer->SetColor (myColor);
3615   myLayer->SetTextAttributes (myFontName.ToCString (), myType, mySubtitleColor);
3616   myLayer->DrawText (myText.ToCString (), myX1, myY1, myHeight);
3617 }
3618
3619 DEFINE_STANDARD_HANDLE(V3d_LineItem, Visual3d_LayerItem)
3620
3621 // The Visual3d_LayerItem line item for "vlayerline" command
3622 // it provides a presentation of line with user-defined
3623 // linewidth, linetype and transparency.
3624 class V3d_LineItem : public Visual3d_LayerItem
3625 {
3626 public:
3627   // CASCADE RTTI
3628   DEFINE_STANDARD_RTTI(V3d_LineItem)
3629
3630   // constructor
3631   Standard_EXPORT V3d_LineItem(Standard_Real X1, Standard_Real Y1,
3632                                Standard_Real X2, Standard_Real Y2,
3633                                V3d_LayerMgrPointer theLayerMgr,
3634                                Aspect_TypeOfLine theType = Aspect_TOL_SOLID,
3635                                Standard_Real theWidth    = 0.5,
3636                                Standard_Real theTransp   = 1.0);
3637
3638   // redraw method
3639   Standard_EXPORT   void RedrawLayerPrs();
3640
3641 private:
3642
3643   Standard_Real       myX1, myY1, myX2, myY2;
3644   V3d_LayerMgrPointer myLayerMgr;
3645   Aspect_TypeOfLine   myType;
3646   Standard_Real       myWidth;
3647   Standard_Real       myTransparency;
3648 };
3649
3650 IMPLEMENT_STANDARD_HANDLE(V3d_LineItem, Visual3d_LayerItem)
3651 IMPLEMENT_STANDARD_RTTIEXT(V3d_LineItem, Visual3d_LayerItem)
3652
3653 // default constructor for line item
3654 V3d_LineItem::V3d_LineItem(Standard_Real X1, Standard_Real Y1,
3655                            Standard_Real X2, Standard_Real Y2,
3656                            V3d_LayerMgrPointer theLayerMgr,
3657                            Aspect_TypeOfLine theType,
3658                            Standard_Real theWidth,
3659                            Standard_Real theTransp) :
3660   myX1(X1), myY1(Y1), myX2(X2), myY2(Y2), myLayerMgr(theLayerMgr),
3661   myType(theType), myWidth(theWidth), myTransparency(theTransp)
3662 {
3663   if (myLayerMgr && !myLayerMgr->Overlay().IsNull())
3664     myLayerMgr->Overlay()->AddLayerItem (this);
3665 }
3666
3667 // render line
3668 void V3d_LineItem::RedrawLayerPrs ()
3669 {
3670   Handle (Visual3d_Layer) aOverlay;
3671
3672   if (myLayerMgr)
3673     aOverlay = myLayerMgr->Overlay();
3674
3675   if (!aOverlay.IsNull())
3676   {
3677     Quantity_Color aColor(1.0, 0, 0, Quantity_TOC_RGB);
3678     aOverlay->SetColor(aColor);
3679     aOverlay->SetTransparency((Standard_ShortReal)myTransparency);
3680     aOverlay->SetLineAttributes((Aspect_TypeOfLine)myType, myWidth);
3681     aOverlay->BeginPolyline();
3682     aOverlay->AddVertex(myX1, myY1);
3683     aOverlay->AddVertex(myX2, myY2);
3684     aOverlay->ClosePrimitive();
3685   }
3686 }
3687
3688 //=============================================================================
3689 //function : VLayerLine
3690 //purpose  : Draws line in the v3d view layer with given attributes: linetype,
3691 //         : linewidth, transparency coefficient
3692 //============================================================================
3693 static int VLayerLine(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3694 {
3695   // get the active view
3696   Handle(V3d_View) aView = ViewerTest::CurrentView();
3697   if (aView.IsNull())
3698   {
3699     di << "Call vinit before!\n";
3700     return 1;
3701   }
3702   else if (argc < 5)
3703   {
3704     di << "Use: " << argv[0];
3705     di << " x1 y1 x2 y2 [linewidth = 0.5] [linetype = 0] [transparency = 1]\n";
3706     di << " linetype : { 0 | 1 | 2 | 3 } \n";
3707     di << "              0 - solid  \n";
3708     di << "              1 - dashed \n";
3709     di << "              2 - dot    \n";
3710     di << "              3 - dashdot\n";
3711     di << " transparency : { 0.0 - 1.0 } \n";
3712     di << "                  0.0 - transparent\n";
3713     di << "                  1.0 - visible    \n";
3714     return 1;
3715   }
3716
3717   // get the input params
3718   Standard_Real X1 = Draw::Atof(argv[1]);
3719   Standard_Real Y1 = Draw::Atof(argv[2]);
3720   Standard_Real X2 = Draw::Atof(argv[3]);
3721   Standard_Real Y2 = Draw::Atof(argv[4]);
3722
3723   Standard_Real    aWidth = 0.5;
3724   Standard_Integer aType  = 0;
3725   Standard_Real    aTransparency = 1.0;
3726
3727   // has width
3728   if (argc > 5)
3729     aWidth = Draw::Atof(argv[5]);
3730
3731   // has type
3732   if (argc > 6)
3733      aType = (Standard_Integer) Draw::Atoi(argv[6]);
3734
3735   // has transparency
3736   if (argc > 7)
3737   {
3738     aTransparency = Draw::Atof(argv[7]);
3739     if (aTransparency < 0 || aTransparency > 1.0)
3740       aTransparency = 1.0;
3741   }
3742
3743   // select appropriate line type
3744   Aspect_TypeOfLine aLineType;
3745   switch (aType)
3746   {
3747     case 1:
3748       aLineType = Aspect_TOL_DASH;
3749     break;
3750
3751     case 2:
3752       aLineType = Aspect_TOL_DOT;
3753     break;
3754
3755     case 3:
3756       aLineType = Aspect_TOL_DOTDASH;
3757     break;
3758
3759     default:
3760       aLineType = Aspect_TOL_SOLID;
3761   }
3762
3763   // replace layer manager
3764   Handle(V3d_LayerMgr) aMgr = new V3d_LayerMgr(aView);
3765   aView->SetLayerMgr(aMgr);
3766
3767   // add line item
3768   Handle (V3d_LineItem) anItem = new V3d_LineItem(X1, Y1, X2, Y2,
3769                                                   aMgr.operator->(),
3770                                                   aLineType, aWidth,
3771                                                   aTransparency);
3772
3773   // update view
3774   aView->MustBeResized();
3775   aView->Redraw();
3776
3777   return 0;
3778 }
3779
3780 //=======================================================================
3781 //function : VOverlayText
3782 //purpose  : Test text displaying in view overlay
3783 //=======================================================================
3784 static int VOverlayText (Draw_Interpretor& di, Standard_Integer argc, const char**argv)
3785 {
3786   // get the active view
3787   Handle(V3d_View) aView = ViewerTest::CurrentView();
3788   if (aView.IsNull())
3789   {
3790     di << "No active view. Please call vinit.\n";
3791     return 1;
3792   }
3793   else if (argc < 4 || argc > 13)
3794   {
3795     di << "Use: " << argv[0];
3796     di << " text x y [height] [font_name] [text_color: R G B] [displayType]\n";
3797     di << "[background_color: R G B]\n";
3798     di << "  height - pixel height of the text (default=10.0)\n";
3799     di << "  font_name - name of font (default=courier)\n";
3800     di << "  text_color - R G B values of text color (default=255.0 255.0 255.0)\n";
3801     di << "  display_type = {normal/subtitle/decal/blend/dimension}, (default=normal)\n";
3802     di << "  background_color- R G B values used for subtitle and decal text\n";
3803     di << "(default=255.0 255.0 255.0)\n";
3804     return 1;
3805   }
3806
3807   TCollection_AsciiString aText (argv[1]);
3808   Standard_Real aPosX = Draw::Atof(argv[2]);
3809   Standard_Real aPosY = Draw::Atof(argv[3]);
3810   Standard_Real aHeight = (argc >= 5) ? Draw::Atof (argv[4]) : 10.0;
3811
3812   // font name
3813   TCollection_AsciiString aFontName = "Courier";
3814   if (argc >= 6)
3815     aFontName = TCollection_AsciiString (argv[5]);
3816
3817   // text colors
3818   Quantity_Parameter aColorRed   = 1.0;
3819   Quantity_Parameter aColorGreen = 1.0;
3820   Quantity_Parameter aColorBlue  = 1.0;
3821   if (argc >= 9)
3822   {
3823     aColorRed   = Draw::Atof (argv[6])/255.;
3824     aColorGreen = Draw::Atof (argv[7])/255.;
3825     aColorBlue  = Draw::Atof (argv[8])/255.;
3826   }
3827
3828   // display type
3829   TCollection_AsciiString aDispStr;
3830   if (argc >= 10)
3831     aDispStr = TCollection_AsciiString (argv[9]);
3832
3833   Aspect_TypeOfDisplayText aTextType = Aspect_TODT_NORMAL;
3834   if (aDispStr.IsEqual ("subtitle"))
3835     aTextType = Aspect_TODT_SUBTITLE;
3836   else if (aDispStr.IsEqual ("decal"))
3837     aTextType = Aspect_TODT_DEKALE;
3838   else if (aDispStr.IsEqual ("blend"))
3839     aTextType = Aspect_TODT_BLEND;
3840   else if (aDispStr.IsEqual ("dimension"))
3841     aTextType = Aspect_TODT_DIMENSION;
3842
3843   // subtitle color
3844   Quantity_Parameter aSubRed   = 1.0;
3845   Quantity_Parameter aSubGreen = 1.0;
3846   Quantity_Parameter aSubBlue  = 1.0;
3847   if (argc == 13)
3848   {
3849     aSubRed   = Draw::Atof (argv[10])/255.;
3850     aSubGreen = Draw::Atof (argv[11])/255.;
3851     aSubBlue  = Draw::Atof (argv[12])/255.;
3852   }
3853
3854   // check fo current overlay
3855   Handle(Visual3d_Layer) anOverlay = aView->Viewer()->Viewer()->OverLayer ();
3856   if (anOverlay.IsNull ())
3857   {
3858     Handle(V3d_LayerMgr) aMgr = new V3d_LayerMgr (aView);
3859     anOverlay = aMgr->Overlay ();
3860     aView->SetLayerMgr (aMgr);
3861   }
3862
3863   Quantity_Color aTextColor (aColorRed, aColorGreen,
3864     aColorBlue, Quantity_TOC_RGB);
3865   Quantity_Color aSubtColor (aSubRed, aSubGreen,
3866     aSubBlue, Quantity_TOC_RGB);
3867
3868   // add text item
3869   Handle(V3d_TextItem) anItem = new V3d_TextItem (aText, aPosX, aPosY,
3870     aHeight, aFontName, aTextColor, aSubtColor, aTextType, anOverlay);
3871
3872   // update view
3873   aView->MustBeResized();
3874   aView->Redraw();
3875
3876   return 0;
3877 }
3878
3879 //==============================================================================
3880 //function : VGrid
3881 //purpose  :
3882 //==============================================================================
3883
3884 static int VGrid (Draw_Interpretor& /*theDI*/,
3885                   Standard_Integer  theArgNb,
3886                   const char**      theArgVec)
3887 {
3888   // get the active view
3889   Handle(V3d_View)   aView   = ViewerTest::CurrentView();
3890   Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext();
3891   if (aView.IsNull() || aViewer.IsNull())
3892   {
3893     std::cerr << "No active view. Please call vinit.\n";
3894     return 1;
3895   }
3896
3897   Aspect_GridType     aType = aViewer->GridType();
3898   Aspect_GridDrawMode aMode = aViewer->GridDrawMode();
3899
3900   Standard_Integer anIter = 1;
3901   for (; anIter < theArgNb; ++anIter)
3902   {
3903     const char* aValue = theArgVec[anIter];
3904     if (*aValue == 'r')
3905     {
3906       aType = Aspect_GT_Rectangular;
3907     }
3908     else if (*aValue == 'c')
3909     {
3910       aType = Aspect_GT_Circular;
3911     }
3912     else if (*aValue == 'l')
3913     {
3914       aMode = Aspect_GDM_Lines;
3915     }
3916     else if (*aValue == 'p')
3917     {
3918       aMode = Aspect_GDM_Points;
3919     }
3920     else if (strcmp (aValue, "off" ) == 0)
3921     {
3922       aViewer->DeactivateGrid();
3923       return 0;
3924     }
3925     else
3926     {
3927       break;
3928     }
3929   }
3930
3931   Standard_Integer aTail = (theArgNb - anIter);
3932   if (aTail == 0)
3933   {
3934     aViewer->ActivateGrid (aType, aMode);
3935     return 0;
3936   }
3937   else if (aTail != 2 && aTail != 5)
3938   {
3939     std::cerr << "Incorrect arguments number! Usage:\n"
3940               << "vgrid [off] [Mode={r|c}] [Type={l|p}] [OriginX OriginY [StepX/StepRadius StepY/DivNb RotAngle]]\n";
3941     return 1;
3942   }
3943
3944   Quantity_Length anOriginX, anOriginY;
3945   Quantity_PlaneAngle aRotAngle;
3946   if (aType == Aspect_GT_Rectangular)
3947   {
3948     Quantity_Length aRStepX, aRStepY;
3949     aViewer->RectangularGridValues (anOriginX, anOriginY, aRStepX, aRStepY, aRotAngle);
3950
3951     anOriginX = Draw::Atof (theArgVec[anIter++]);
3952     anOriginY = Draw::Atof (theArgVec[anIter++]);
3953     if (aTail == 5)
3954     {
3955       aRStepX   = Draw::Atof (theArgVec[anIter++]);
3956       aRStepY   = Draw::Atof (theArgVec[anIter++]);
3957       aRotAngle = Draw::Atof (theArgVec[anIter++]);
3958     }
3959     aViewer->SetRectangularGridValues (anOriginX, anOriginY, aRStepX, aRStepY, aRotAngle);
3960     aViewer->ActivateGrid (aType, aMode);
3961   }
3962   else if (aType == Aspect_GT_Circular)
3963   {
3964     Quantity_Length aRadiusStep;
3965     Standard_Integer aDivisionNumber;
3966     aViewer->CircularGridValues (anOriginX, anOriginY, aRadiusStep, aDivisionNumber, aRotAngle);
3967
3968     anOriginX = Draw::Atof (theArgVec[anIter++]);
3969     anOriginY = Draw::Atof (theArgVec[anIter++]);
3970     if (aTail == 5)
3971     {
3972       aRadiusStep     = Draw::Atof (theArgVec[anIter++]);
3973       aDivisionNumber = Draw::Atoi (theArgVec[anIter++]);
3974       aRotAngle       = Draw::Atof (theArgVec[anIter++]);
3975     }
3976
3977     aViewer->SetCircularGridValues (anOriginX, anOriginY, aRadiusStep, aDivisionNumber, aRotAngle);
3978     aViewer->ActivateGrid (aType, aMode);
3979   }
3980
3981   return 0;
3982 }
3983
3984 //==============================================================================
3985 //function : VFps
3986 //purpose  :
3987 //==============================================================================
3988
3989 static int VFps (Draw_Interpretor& theDI,
3990                  Standard_Integer  theArgNb,
3991                  const char**      theArgVec)
3992 {
3993   // get the active view
3994   Handle(V3d_View) aView = ViewerTest::CurrentView();
3995   if (aView.IsNull())
3996   {
3997     std::cerr << "No active view. Please call vinit.\n";
3998     return 1;
3999   }
4000
4001   Standard_Integer aFramesNb = (theArgNb > 1) ? Draw::Atoi(theArgVec[1]) : 100;
4002   if (aFramesNb <= 0)
4003   {
4004     std::cerr << "Incorrect arguments!\n";
4005     return 1;
4006   }
4007
4008   // the time is meaningless for first call
4009   // due to async OpenGl rendering
4010   aView->Redraw();
4011
4012   // redraw view in loop to estimate average values
4013   OSD_Timer aTimer;
4014   aTimer.Start();
4015   for (Standard_Integer anInter = 0; anInter < aFramesNb; ++anInter)
4016   {
4017     aView->Redraw();
4018   }
4019   aTimer.Stop();
4020   Standard_Real aCpu;
4021   const Standard_Real aTime = aTimer.ElapsedTime();
4022   aTimer.OSD_Chronometer::Show (aCpu);
4023
4024   const Standard_Real aFpsAver = Standard_Real(aFramesNb) / aTime;
4025   const Standard_Real aCpuAver = aCpu / Standard_Real(aFramesNb);
4026
4027   // return statistics
4028   theDI << "FPS: " << aFpsAver << "\n"
4029         << "CPU: " << (1000.0 * aCpuAver) << " msec\n";
4030
4031   return 0;
4032 }
4033
4034 //==============================================================================
4035 //function : VGlDebug
4036 //purpose  :
4037 //==============================================================================
4038
4039 static int VGlDebug (Draw_Interpretor& theDI,
4040                      Standard_Integer  theArgNb,
4041                      const char**      theArgVec)
4042 {
4043   if (theArgNb < 2)
4044   {
4045     Handle(V3d_View) aView = ViewerTest::CurrentView();
4046     if (aView.IsNull())
4047     {
4048       std::cerr << "No active view. Please call vinit.\n";
4049       return 0;
4050     }
4051
4052     Standard_Boolean isActive = OpenGl_Context::CheckExtension ((const char* )glGetString (GL_EXTENSIONS),
4053                                                                 "GL_ARB_debug_output");
4054     std::cout << "Active graphic driver: debug " << (isActive ? "ON" : "OFF") << "\n";
4055     theDI << (isActive ? "1" : "0");
4056     return 0;
4057   }
4058
4059   ViewerTest_myDefaultCaps.contextDebug = Draw::Atoi (theArgVec[1]) != 0;
4060   return 0;
4061 }
4062
4063 //==============================================================================
4064 //function : VVbo
4065 //purpose  :
4066 //==============================================================================
4067
4068 static int VVbo (Draw_Interpretor& theDI,
4069                  Standard_Integer  theArgNb,
4070                  const char**      theArgVec)
4071 {
4072   const Standard_Boolean toSet    = (theArgNb > 1);
4073   const Standard_Boolean toUseVbo = toSet ? (Draw::Atoi (theArgVec[1]) == 0) : 1;
4074   if (toSet)
4075   {
4076     ViewerTest_myDefaultCaps.vboDisable = toUseVbo;
4077   }
4078
4079   // get the context
4080   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
4081   if (aContextAIS.IsNull())
4082   {
4083     if (!toSet)
4084     {
4085       std::cerr << "No active view!\n";
4086     }
4087     return 1;
4088   }
4089   Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast (aContextAIS->CurrentViewer()->Driver());
4090   if (!aDriver.IsNull())
4091   {
4092     if (!toSet)
4093     {
4094       theDI << (aDriver->Options().vboDisable ? "0" : "1") << "\n";
4095     }
4096     else
4097     {
4098       aDriver->ChangeOptions().vboDisable = toUseVbo;
4099     }
4100   }
4101
4102   return 0;
4103 }
4104
4105 //==============================================================================
4106 //function : VCaps
4107 //purpose  :
4108 //==============================================================================
4109
4110 static int VCaps (Draw_Interpretor& theDI,
4111                   Standard_Integer  theArgNb,
4112                   const char**      theArgVec)
4113 {
4114   OpenGl_Caps* aCaps = &ViewerTest_myDefaultCaps;
4115   Handle(OpenGl_GraphicDriver)   aDriver;
4116   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
4117   if (!aContextAIS.IsNull())
4118   {
4119     aDriver = Handle(OpenGl_GraphicDriver)::DownCast (aContextAIS->CurrentViewer()->Driver());
4120     aCaps   = &aDriver->ChangeOptions();
4121   }
4122
4123   if (theArgNb < 2)
4124   {
4125     theDI << "VBO:     " << (aCaps->vboDisable        ? "0" : "1") << "\n";
4126     theDI << "Sprites: " << (aCaps->pntSpritesDisable ? "0" : "1") << "\n";
4127     theDI << "SoftMode:" << (aCaps->contextNoAccel    ? "1" : "0") << "\n";
4128     return 0;
4129   }
4130
4131   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
4132   {
4133     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
4134     if (anArg.Search ("vbo=") > -1)
4135     {
4136       aCaps->vboDisable        = anArg.Token ("=", 2).IntegerValue() == 0;
4137     }
4138     else if (anArg.Search ("sprites=") > -1)
4139     {
4140       aCaps->pntSpritesDisable = anArg.Token ("=", 2).IntegerValue() == 0;
4141     }
4142     else if (anArg.Search ("soft=") > -1)
4143     {
4144       aCaps->contextNoAccel = anArg.Token ("=", 2).IntegerValue() != 0;
4145     }
4146     else
4147     {
4148       std::cerr << "Unknown argument: " << anArg << "\n";
4149     }
4150   }
4151   if (aCaps != &ViewerTest_myDefaultCaps)
4152   {
4153     ViewerTest_myDefaultCaps = *aCaps;
4154   }
4155   return 0;
4156 }
4157
4158 //==============================================================================
4159 //function : VMemGpu
4160 //purpose  :
4161 //==============================================================================
4162
4163 static int VMemGpu (Draw_Interpretor& theDI,
4164                     Standard_Integer  theArgNb,
4165                     const char**      theArgVec)
4166 {
4167   // get the context
4168   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
4169   if (aContextAIS.IsNull())
4170   {
4171     std::cerr << "No active view. Please call vinit.\n";
4172     return 1;
4173   }
4174
4175   Handle(Graphic3d_GraphicDriver) aDriver = aContextAIS->CurrentViewer()->Driver();
4176   if (aDriver.IsNull())
4177   {
4178     std::cerr << "Graphic driver not available.\n";
4179     return 1;
4180   }
4181
4182   Standard_Size aFreeBytes = 0;
4183   TCollection_AsciiString anInfo;
4184   if (!aDriver->MemoryInfo (aFreeBytes, anInfo))
4185   {
4186     std::cerr << "Information not available.\n";
4187     return 1;
4188   }
4189
4190   if (theArgNb > 1 && *theArgVec[1] == 'f')
4191   {
4192     theDI << Standard_Real (aFreeBytes);
4193   }
4194   else
4195   {
4196     theDI << anInfo;
4197   }
4198
4199   return 0;
4200 }
4201
4202 // ==============================================================================
4203 // function : VReadPixel
4204 // purpose  :
4205 // ==============================================================================
4206 static int VReadPixel (Draw_Interpretor& theDI,
4207                        Standard_Integer  theArgNb,
4208                        const char**      theArgVec)
4209 {
4210   // get the active view
4211   Handle(V3d_View) aView = ViewerTest::CurrentView();
4212   if (aView.IsNull())
4213   {
4214     std::cerr << "No active view. Please call vinit.\n";
4215     return 1;
4216   }
4217   else if (theArgNb < 3)
4218   {
4219     std::cerr << "Usage : " << theArgVec[0] << " xPixel yPixel [{rgb|rgba|depth|hls|rgbf|rgbaf}=rgba] [name]\n";
4220     return 1;
4221   }
4222
4223   Image_PixMap::ImgFormat aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGBA : Image_PixMap::ImgBGRA;
4224   Graphic3d_BufferType    aBufferType = Graphic3d_BT_RGBA;
4225
4226   Standard_Integer aWidth, aHeight;
4227   aView->Window()->Size (aWidth, aHeight);
4228   const Standard_Integer anX = Draw::Atoi (theArgVec[1]);
4229   const Standard_Integer anY = Draw::Atoi (theArgVec[2]);
4230   if (anX < 0 || anX >= aWidth || anY < 0 || anY > aHeight)
4231   {
4232     std::cerr << "Pixel coordinates (" << anX << "; " << anY << ") are out of view (" << aWidth << " x " << aHeight << ")\n";
4233     return 1;
4234   }
4235
4236   Standard_Boolean toShowName = Standard_False;
4237   Standard_Boolean toShowHls  = Standard_False;
4238   for (Standard_Integer anIter = 3; anIter < theArgNb; ++anIter)
4239   {
4240     const char* aParam = theArgVec[anIter];
4241     if ( strcasecmp( aParam, "rgb" ) == 0 )
4242     {
4243       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGB : Image_PixMap::ImgBGR;
4244       aBufferType = Graphic3d_BT_RGB;
4245     }
4246     else if ( strcasecmp( aParam, "hls" ) == 0 )
4247     {
4248       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGB : Image_PixMap::ImgBGR;
4249       aBufferType = Graphic3d_BT_RGB;
4250       toShowHls   = Standard_True;
4251     }
4252     else if ( strcasecmp( aParam, "rgbf" ) == 0 )
4253     {
4254       aFormat     = Image_PixMap::ImgRGBF;
4255       aBufferType = Graphic3d_BT_RGB;
4256     }
4257     else if ( strcasecmp( aParam, "rgba" ) == 0 )
4258     {
4259       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGBA : Image_PixMap::ImgBGRA;
4260       aBufferType = Graphic3d_BT_RGBA;
4261     }
4262     else if ( strcasecmp( aParam, "rgbaf" ) == 0 )
4263     {
4264       aFormat     = Image_PixMap::ImgRGBAF;
4265       aBufferType = Graphic3d_BT_RGBA;
4266     }
4267     else if ( strcasecmp( aParam, "depth" ) == 0 )
4268     {
4269       aFormat     = Image_PixMap::ImgGrayF;
4270       aBufferType = Graphic3d_BT_Depth;
4271     }
4272     else if ( strcasecmp( aParam, "name" ) == 0 )
4273     {
4274       toShowName = Standard_True;
4275     }
4276   }
4277
4278   Image_PixMap anImage;
4279   if (!anImage.InitTrash (aFormat, aWidth, aHeight))
4280   {
4281     std::cerr << "Image allocation failed\n";
4282     return 1;
4283   }
4284   else if (!aView->ToPixMap (anImage, aWidth, aHeight, aBufferType))
4285   {
4286     std::cerr << "Image dump failed\n";
4287     return 1;
4288   }
4289
4290   Quantity_Parameter anAlpha;
4291   Quantity_Color aColor = anImage.PixelColor (anX, anY, anAlpha);
4292   if (toShowName)
4293   {
4294     if (aBufferType == Graphic3d_BT_RGBA)
4295     {
4296       theDI << Quantity_Color::StringName (aColor.Name()) << " " << anAlpha;
4297     }
4298     else
4299     {
4300       theDI << Quantity_Color::StringName (aColor.Name());
4301     }
4302   }
4303   else
4304   {
4305     switch (aBufferType)
4306     {
4307       default:
4308       case Graphic3d_BT_RGB:
4309       {
4310         if (toShowHls)
4311         {
4312           theDI << aColor.Hue() << " " << aColor.Light() << " " << aColor.Saturation();
4313         }
4314         else
4315         {
4316           theDI << aColor.Red() << " " << aColor.Green() << " " << aColor.Blue();
4317         }
4318         break;
4319       }
4320       case Graphic3d_BT_RGBA:
4321       {
4322         theDI << aColor.Red() << " " << aColor.Green() << " " << aColor.Blue() << " " << anAlpha;
4323         break;
4324       }
4325       case Graphic3d_BT_Depth:
4326       {
4327         theDI << aColor.Red();
4328         break;
4329       }
4330     }
4331   }
4332
4333   return 0;
4334 }
4335
4336 //==============================================================================
4337 //function : VDiffImage
4338 //purpose  : The draw-command compares two images.
4339 //==============================================================================
4340
4341 static int VDiffImage (Draw_Interpretor& theDI, Standard_Integer theArgNb, const char** theArgVec)
4342 {
4343   if (theArgNb < 6)
4344   {
4345     theDI << "Not enough arguments.\n";
4346     return 1;
4347   }
4348
4349   // image file names
4350   const char* anImgPathRef = theArgVec[1];
4351   const char* anImgPathNew = theArgVec[2];
4352
4353   // get string tolerance and check its validity
4354   Standard_Real aTolColor = Draw::Atof (theArgVec[3]);
4355   if (aTolColor < 0.0)
4356     aTolColor = 0.0;
4357   if (aTolColor > 1.0)
4358     aTolColor = 1.0;
4359
4360   Standard_Boolean toBlackWhite     = (Draw::Atoi (theArgVec[4]) == 1);
4361   Standard_Boolean isBorderFilterOn = (Draw::Atoi (theArgVec[5]) == 1);
4362
4363   // image file of difference
4364   const char* aDiffImagePath = (theArgNb >= 7) ? theArgVec[6] : NULL;
4365
4366   // compare the images
4367   Image_Diff aComparer;
4368   if (!aComparer.Init (anImgPathRef, anImgPathNew, toBlackWhite))
4369   {
4370     return 1;
4371   }
4372
4373   aComparer.SetColorTolerance (aTolColor);
4374   aComparer.SetBorderFilterOn (isBorderFilterOn);
4375   Standard_Integer aDiffColorsNb = aComparer.Compare();
4376   theDI << aDiffColorsNb << "\n";
4377
4378   // save image of difference
4379   if (aDiffImagePath != NULL)
4380   {
4381     aComparer.SaveDiffImage (aDiffImagePath);
4382   }
4383
4384   return 0;
4385 }
4386
4387 //=======================================================================
4388 //function : VSelect
4389 //purpose  : Emulates different types of selection by mouse:
4390 //           1) single click selection
4391 //           2) selection with rectangle having corners at pixel positions (x1,y1) and (x2,y2)
4392 //           3) selection with polygon having corners at
4393 //           pixel positions (x1,y1),...,(xn,yn)
4394 //           4) any of these selections with shift button pressed
4395 //=======================================================================
4396 static Standard_Integer VSelect (Draw_Interpretor& di,
4397                                  Standard_Integer argc,
4398                                  const char ** argv)
4399 {
4400   if(argc < 3)
4401   {
4402     di << "Usage : " << argv[0] << " x1 y1 [x2 y2 [... xn yn]] [shift_selection = 1|0]" << "\n";
4403     return 1;
4404   }
4405
4406   Handle(AIS_InteractiveContext) myAIScontext = ViewerTest::GetAISContext();
4407   if(myAIScontext.IsNull())
4408   {
4409     di << "use 'vinit' command before " << argv[0] << "\n";
4410     return 1;
4411   }
4412   const Standard_Boolean isShiftSelection = (argc>3 && !(argc%2) && (atoi(argv[argc-1])==1));
4413   Handle(ViewerTest_EventManager) aCurrentEventManager = ViewerTest::CurrentEventManager();
4414   aCurrentEventManager->MoveTo(atoi(argv[1]),atoi(argv[2]));
4415   if(argc <= 4)
4416   {
4417     if(isShiftSelection)
4418       aCurrentEventManager->ShiftSelect();
4419     else
4420       aCurrentEventManager->Select();
4421   }
4422   else if(argc <= 6)
4423   {
4424     if(isShiftSelection)
4425       aCurrentEventManager->ShiftSelect(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),atoi(argv[4]));
4426     else
4427       aCurrentEventManager->Select(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),atoi(argv[4]));
4428   }
4429   else
4430   {
4431     Standard_Integer anUpper = 0;
4432
4433     if(isShiftSelection)
4434       anUpper = (argc-1)/2;
4435     else
4436       anUpper = argc/2;
4437     TColgp_Array1OfPnt2d aPolyline(1,anUpper);
4438
4439     for(Standard_Integer i=1;i<=anUpper;++i)
4440       aPolyline.SetValue(i,gp_Pnt2d(atoi(argv[2*i-1]),atoi(argv[2*i])));
4441
4442     if(isShiftSelection)
4443       aCurrentEventManager->ShiftSelect(aPolyline);
4444     else
4445       aCurrentEventManager->Select(aPolyline);
4446   }
4447   return 0;
4448 }
4449
4450 //=======================================================================
4451 //function : VMoveTo
4452 //purpose  : Emulates cursor movement to defined pixel position
4453 //=======================================================================
4454 static Standard_Integer VMoveTo (Draw_Interpretor& di,
4455                                 Standard_Integer argc,
4456                                 const char ** argv)
4457 {
4458   if(argc != 3)
4459   {
4460     di << "Usage : " << argv[0] << " x y" << "\n";
4461     return 1;
4462   }
4463
4464   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4465   if(aContext.IsNull())
4466   {
4467     di << "use 'vinit' command before " << argv[0] << "\n";
4468     return 1;
4469   }
4470   ViewerTest::CurrentEventManager()->MoveTo(atoi(argv[1]),atoi(argv[2]));
4471   return 0;
4472 }
4473
4474 //=================================================================================================
4475 //function : VViewParams
4476 //purpose  : Gets or sets AIS View characteristics
4477 //=================================================================================================
4478 static int VViewParams (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
4479 {
4480   Handle(V3d_View) anAISView = ViewerTest::CurrentView();
4481   if (anAISView.IsNull())
4482   {
4483     std::cout << theArgVec[0] << ": please initialize or activate view.\n";
4484     return 1;
4485   }
4486
4487   if (theArgsNb == 1)
4488   {
4489     // print all of the available view parameters
4490     Quantity_Factor anAISViewScale = anAISView->Scale();
4491
4492     Standard_Real anAISViewProjX = 0.0;
4493     Standard_Real anAISViewProjY = 0.0;
4494     Standard_Real anAISViewProjZ = 0.0;
4495     anAISView->Proj (anAISViewProjX, anAISViewProjY, anAISViewProjZ);
4496
4497     Standard_Real anAISViewUpX = 0.0;
4498     Standard_Real anAISViewUpY = 0.0;
4499     Standard_Real anAISViewUpZ = 0.0;
4500     anAISView->Up (anAISViewUpX, anAISViewUpY, anAISViewUpZ);
4501
4502     Standard_Real anAISViewAtX = 0.0;
4503     Standard_Real anAISViewAtY = 0.0;
4504     Standard_Real anAISViewAtZ = 0.0;
4505     anAISView->At (anAISViewAtX, anAISViewAtY, anAISViewAtZ);
4506
4507     Standard_Real anAISViewEyeX = 0.0;
4508     Standard_Real anAISViewEyeY = 0.0;
4509     Standard_Real anAISViewEyeZ = 0.0;
4510     anAISView->Eye (anAISViewEyeX, anAISViewEyeY, anAISViewEyeZ);
4511
4512     theDi << "Scale of current view: " << anAISViewScale << "\n";
4513     theDi << "Proj on X : " << anAISViewProjX << "; on Y: " << anAISViewProjY << "; on Z: " << anAISViewProjZ << "\n";
4514     theDi << "Up on X : " << anAISViewUpX << "; on Y: " << anAISViewUpY << "; on Z: " << anAISViewUpZ << "\n";
4515     theDi << "At on X : " << anAISViewAtX << "; on Y: " << anAISViewAtY << "; on Z: " << anAISViewAtZ << "\n";
4516     theDi << "Eye on X : " << anAISViewEyeX << "; on Y: " << anAISViewEyeY << "; on Z: " << anAISViewEyeZ << "\n";
4517     return 0;
4518   }
4519
4520   // -------------------------
4521   //  Parse options and values
4522   // -------------------------
4523
4524   NCollection_DataMap<TCollection_AsciiString, Handle(TColStd_HSequenceOfAsciiString)> aMapOfKeysByValues;
4525   TCollection_AsciiString aParseKey;
4526   for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
4527   {
4528     TCollection_AsciiString anArg (theArgVec [anArgIt]);
4529
4530     if (anArg.Value (1) == '-' && !anArg.IsRealValue())
4531     {
4532       aParseKey = anArg;
4533       aParseKey.Remove (1);
4534       aParseKey.UpperCase();
4535       aMapOfKeysByValues.Bind (aParseKey, new TColStd_HSequenceOfAsciiString);
4536       continue;
4537     }
4538
4539     if (aParseKey.IsEmpty())
4540     {
4541       std::cout << theArgVec[0] << ": values should be passed with key.\n";
4542       std::cout << "Type help for more information.\n";
4543       return 1;
4544     }
4545
4546     aMapOfKeysByValues(aParseKey)->Append (anArg);
4547   }
4548
4549   // ---------------------------------------------
4550   //  Change or print parameters, order plays role
4551   // ---------------------------------------------
4552
4553   // Check arguments for validity
4554   NCollection_DataMap<TCollection_AsciiString, Handle(TColStd_HSequenceOfAsciiString)>::Iterator aMapIt (aMapOfKeysByValues);
4555   for (; aMapIt.More(); aMapIt.Next())
4556   {
4557     const TCollection_AsciiString& aKey = aMapIt.Key();
4558     const Handle(TColStd_HSequenceOfAsciiString)& aValues = aMapIt.Value();
4559
4560     if (!(aKey.IsEqual ("SCALE")  && (aValues->Length() == 1 || aValues->IsEmpty()))
4561      && !(aKey.IsEqual ("SIZE")   && (aValues->Length() == 1 || aValues->IsEmpty()))
4562      && !(aKey.IsEqual ("EYE")    && (aValues->Length() == 3 || aValues->IsEmpty()))
4563      && !(aKey.IsEqual ("AT")     && (aValues->Length() == 3 || aValues->IsEmpty()))
4564      && !(aKey.IsEqual ("UP")     && (aValues->Length() == 3 || aValues->IsEmpty()))
4565      && !(aKey.IsEqual ("PROJ")   && (aValues->Length() == 3 || aValues->IsEmpty()))
4566      && !(aKey.IsEqual ("CENTER") &&  aValues->Length() == 2))
4567     {
4568       TCollection_AsciiString aLowerKey;
4569       aLowerKey  = "-";
4570       aLowerKey += aKey;
4571       aLowerKey.LowerCase();
4572       std::cout << theArgVec[0] << ": " << aLowerKey << " is unknown option, or number of arguments is invalid.\n";
4573       std::cout << "Type help for more information.\n";
4574       return 1;
4575     }
4576   }
4577
4578   Handle(TColStd_HSequenceOfAsciiString) aValues;
4579
4580   // Change view parameters in proper order
4581   if (aMapOfKeysByValues.Find ("SCALE", aValues))
4582   {
4583     if (aValues->IsEmpty())
4584     {
4585       theDi << "Scale: " << anAISView->Scale() << "\n";
4586     }
4587     else
4588     {
4589       anAISView->SetScale (aValues->Value(1).RealValue());
4590     }
4591   }
4592   if (aMapOfKeysByValues.Find ("SIZE", aValues))
4593   {
4594     if (aValues->IsEmpty())
4595     {
4596       Standard_Real aSizeX = 0.0;
4597       Standard_Real aSizeY = 0.0;
4598       anAISView->Size (aSizeX, aSizeY);
4599       theDi << "Size X: " << aSizeX << " Y: " << aSizeY << "\n";
4600     }
4601     else
4602     {
4603       anAISView->SetSize (aValues->Value(1).RealValue());
4604     }
4605   }
4606   if (aMapOfKeysByValues.Find ("EYE", aValues))
4607   {
4608     if (aValues->IsEmpty())
4609     {
4610       Standard_Real anEyeX = 0.0;
4611       Standard_Real anEyeY = 0.0;
4612       Standard_Real anEyeZ = 0.0;
4613       anAISView->Eye (anEyeX, anEyeY, anEyeZ);
4614       theDi << "Eye X: " << anEyeX << " Y: " << anEyeY << " Z: " << anEyeZ << "\n";
4615     }
4616     else
4617     {
4618       anAISView->SetEye (aValues->Value(1).RealValue(), aValues->Value(2).RealValue(), aValues->Value(3).RealValue());
4619     }
4620   }
4621   if (aMapOfKeysByValues.Find ("AT", aValues))
4622   {
4623     if (aValues->IsEmpty())
4624     {
4625       Standard_Real anAtX = 0.0;
4626       Standard_Real anAtY = 0.0;
4627       Standard_Real anAtZ = 0.0;
4628       anAISView->At (anAtX, anAtY, anAtZ);
4629       theDi << "At X: " << anAtX << " Y: " << anAtY << " Z: " << anAtZ << "\n";
4630     }
4631     else
4632     {
4633       anAISView->SetAt (aValues->Value(1).RealValue(), aValues->Value(2).RealValue(), aValues->Value(3).RealValue());
4634     }
4635   }
4636   if (aMapOfKeysByValues.Find ("PROJ", aValues))
4637   {
4638     if (aValues->IsEmpty())
4639     {
4640       Standard_Real aProjX = 0.0;
4641       Standard_Real aProjY = 0.0;
4642       Standard_Real aProjZ = 0.0;
4643       anAISView->Proj (aProjX, aProjY, aProjZ);
4644       theDi << "Proj X: " << aProjX << " Y: " << aProjY << " Z: " << aProjZ << "\n";
4645     }
4646     else
4647     {
4648       anAISView->SetProj (aValues->Value(1).RealValue(), aValues->Value(2).RealValue(), aValues->Value(3).RealValue());
4649     }
4650   }
4651   if (aMapOfKeysByValues.Find ("UP", aValues))
4652   {
4653     if (aValues->IsEmpty())
4654     {
4655       Standard_Real anUpX = 0.0;
4656       Standard_Real anUpY = 0.0;
4657       Standard_Real anUpZ = 0.0;
4658       anAISView->Up (anUpX, anUpY, anUpZ);
4659       theDi << "Up X: " << anUpX << " Y: " << anUpY << " Z: " << anUpZ << "\n";
4660     }
4661     else
4662     {
4663       anAISView->SetUp (aValues->Value(1).RealValue(), aValues->Value(2).RealValue(), aValues->Value(3).RealValue());
4664     }
4665   }
4666   if (aMapOfKeysByValues.Find ("CENTER", aValues))
4667   {
4668     anAISView->SetCenter (aValues->Value(1).IntegerValue(), aValues->Value(2).IntegerValue());
4669   }
4670
4671   return 0;
4672 }
4673
4674 //=======================================================================
4675 //function : VChangeSelected
4676 //purpose  : Adds the shape to selection or remove one from it
4677 //=======================================================================
4678 static Standard_Integer VChangeSelected (Draw_Interpretor& di,
4679                                 Standard_Integer argc,
4680                                 const char ** argv)
4681 {
4682   if(argc != 2)
4683   {
4684     di<<"Usage : " << argv[0] << " shape \n";
4685     return 1;
4686   }
4687   //get AIS_Shape:
4688   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4689   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4690   TCollection_AsciiString aName(argv[1]);
4691   Handle(AIS_InteractiveObject) anAISObject;
4692
4693   if(!aMap.IsBound2(aName))
4694   {
4695     di<<"Use 'vdisplay' before";
4696     return 1;
4697   }
4698   else
4699   {
4700     anAISObject = Handle(AIS_InteractiveObject)::DownCast(aMap.Find2(aName));
4701     if(anAISObject.IsNull()){
4702       di<<"No interactive object \n";
4703       return 1;
4704     }
4705
4706     if(aContext->HasOpenedContext())
4707     {
4708       aContext->AddOrRemoveSelected(anAISObject);
4709     }
4710     else
4711     {
4712       aContext->AddOrRemoveCurrentObject(anAISObject);
4713     }
4714   }
4715   return 0;
4716 }
4717
4718 //=======================================================================
4719 //function : VZClipping
4720 //purpose  : Gets or sets ZClipping mode, width and depth
4721 //=======================================================================
4722 static Standard_Integer VZClipping (Draw_Interpretor& di,
4723                                 Standard_Integer argc,
4724                                 const char ** argv)
4725 {
4726   if(argc>4)
4727   {
4728     di << "Usage : " << argv[0] << " [mode] [depth  width]" << "\n"
4729       <<"mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4730     return -1;
4731   }
4732   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4733   if(aContext.IsNull())
4734   {
4735     di << "use 'vinit' command before " << argv[0] << "\n";
4736     return 1;
4737   }
4738   Handle(V3d_View) aView = ViewerTest::CurrentView();
4739   V3d_TypeOfZclipping aZClippingMode = V3d_OFF;
4740   if(argc==1)
4741   {
4742     TCollection_AsciiString aZClippingModeString;
4743     Quantity_Length aDepth, aWidth;
4744     aZClippingMode = aView->ZClipping(aDepth, aWidth);
4745     switch (aZClippingMode)
4746     {
4747     case V3d_OFF:
4748       aZClippingModeString.Copy("OFF");
4749       break;
4750     case V3d_BACK:
4751       aZClippingModeString.Copy("BACK");
4752       break;
4753     case V3d_FRONT:
4754       aZClippingModeString.Copy("FRONT");
4755       break;
4756     case V3d_SLICE:
4757       aZClippingModeString.Copy("SLICE");
4758       break;
4759     default:
4760       aZClippingModeString.Copy(TCollection_AsciiString(aZClippingMode));
4761       break;
4762     }
4763     di << "ZClippingMode = " << aZClippingModeString.ToCString() << "\n"
4764       << "ZClipping depth = " << aDepth << "\n"
4765       << "ZClipping width = " << aWidth << "\n";
4766   }
4767   else
4768   {
4769     if(argc !=3)
4770     {
4771       Standard_Integer aStatus = 0;
4772       if ( strcmp (argv [1], "OFF") == 0 ) {
4773         aStatus = 1;
4774         aZClippingMode = V3d_OFF;
4775       }
4776       if ( strcmp (argv [1], "BACK") == 0 ) {
4777         aStatus = 1;
4778         aZClippingMode = V3d_BACK;
4779       }
4780       if ( strcmp (argv [1], "FRONT") == 0 ) {
4781         aStatus = 1;
4782         aZClippingMode = V3d_FRONT;
4783       }
4784       if ( strcmp (argv [1], "SLICE") == 0 ) {
4785         aStatus = 1;
4786         aZClippingMode = V3d_SLICE;
4787       }
4788       if (aStatus != 1)
4789       {
4790         di << "Bad mode; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4791           << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4792         return 1;
4793       }
4794       aView->SetZClippingType(aZClippingMode);
4795     }
4796     if(argc >2)
4797     {
4798       Quantity_Length aDepth = 0., aWidth = 1.;
4799       if(argc == 3)
4800       {
4801         aDepth = atof(argv[1]);
4802         aWidth = atof(argv[2]);
4803       }
4804       else if(argc == 4)
4805       {
4806         aDepth = atof(argv[2]);
4807         aWidth = atof(argv[3]);
4808       }
4809
4810       if(aDepth<0. || aDepth>1.)
4811       {
4812         di << "Bad depth; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4813         << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4814         return 1;
4815       }
4816       if(aWidth<0. || aWidth>1.)
4817       {
4818         di << "Bad width; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4819         << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4820         return 1;
4821       }
4822
4823       aView->SetZClippingDepth(aDepth);
4824       aView->SetZClippingWidth(aWidth);
4825     }
4826     aView->Redraw();
4827   }
4828   return 0;
4829 }
4830
4831 //=======================================================================
4832 //function : VNbSelected
4833 //purpose  : Returns number of selected objects
4834 //=======================================================================
4835 static Standard_Integer VNbSelected (Draw_Interpretor& di,
4836                                 Standard_Integer argc,
4837                                 const char ** argv)
4838 {
4839   if(argc != 1)
4840   {
4841     di << "Usage : " << argv[0] << "\n";
4842     return 1;
4843   }
4844   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4845   if(aContext.IsNull())
4846   {
4847     di << "use 'vinit' command before " << argv[0] << "\n";
4848     return 1;
4849   }
4850   di << aContext->NbSelected() << "\n";
4851   return 0;
4852 }
4853
4854 //=======================================================================
4855 //function : VAntialiasing
4856 //purpose  : Switches altialiasing on or off
4857 //=======================================================================
4858 static Standard_Integer VAntialiasing (Draw_Interpretor& di,
4859                                 Standard_Integer argc,
4860                                 const char ** argv)
4861 {
4862   if(argc > 2)
4863   {
4864     di << "Usage : " << argv[0] << " [1|0]" << "\n";
4865     return 1;
4866   }
4867
4868   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4869   if(aContext.IsNull())
4870   {
4871     di << "use 'vinit' command before " << argv[0] << "\n";
4872     return 1;
4873   }
4874
4875   Handle(V3d_View) aView = ViewerTest::CurrentView();
4876
4877   if((argc == 2) && (atof(argv[1]) == 0))
4878     aView->SetAntialiasingOff();
4879   else
4880     aView->SetAntialiasingOn();
4881   aView->Update();
4882   return 0;
4883 }
4884
4885 //=======================================================================
4886 //function : VPurgeDisplay
4887 //purpose  : Switches altialiasing on or off
4888 //=======================================================================
4889 static Standard_Integer VPurgeDisplay (Draw_Interpretor& di,
4890                                 Standard_Integer argc,
4891                                 const char ** argv)
4892 {
4893   if (argc > 1)
4894   {
4895     di << "Usage : " << argv[0] << "\n";
4896     return 1;
4897   }
4898   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4899   if (aContext.IsNull())
4900   {
4901     di << "use 'vinit' command before " << argv[0] << "\n";
4902     return 1;
4903   }
4904   aContext->CloseAllContexts(Standard_False);
4905   di << aContext->PurgeDisplay() << "\n";
4906   return 0;
4907 }
4908
4909 //=======================================================================
4910 //function : VSetViewSize
4911 //purpose  :
4912 //=======================================================================
4913 static Standard_Integer VSetViewSize (Draw_Interpretor& di,
4914                                 Standard_Integer argc,
4915                                 const char ** argv)
4916 {
4917   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4918   if(aContext.IsNull())
4919   {
4920     di << "use 'vinit' command before " << argv[0] << "\n";
4921     return 1;
4922   }
4923   if(argc != 2)
4924   {
4925     di<<"Usage : " << argv[0] << " Size\n";
4926     return 1;
4927   }
4928   Standard_Real aSize = atof(argv[1]);
4929   if (aSize <= 0.)
4930   {
4931     di<<"Bad Size value  : " << aSize << "\n";
4932     return 1;
4933   }
4934
4935   Handle(V3d_View) aView = ViewerTest::CurrentView();
4936   aView->SetSize(aSize);
4937   return 0;
4938 }
4939
4940 //=======================================================================
4941 //function : VMoveView
4942 //purpose  :
4943 //=======================================================================
4944 static Standard_Integer VMoveView (Draw_Interpretor& di,
4945                                 Standard_Integer argc,
4946                                 const char ** argv)
4947 {
4948   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4949   if(aContext.IsNull())
4950   {
4951     di << "use 'vinit' command before " << argv[0] << "\n";
4952     return 1;
4953   }
4954   if(argc < 4 || argc > 5)
4955   {
4956     di<<"Usage : " << argv[0] << " Dx Dy Dz [Start = 1|0]\n";
4957     return 1;
4958   }
4959   Standard_Real Dx = atof(argv[1]);
4960   Standard_Real Dy = atof(argv[2]);
4961   Standard_Real Dz = atof(argv[3]);
4962   Standard_Boolean aStart = Standard_True;
4963   if (argc == 5)
4964   {
4965       aStart = (atoi(argv[4]) > 0);
4966   }
4967
4968   Handle(V3d_View) aView = ViewerTest::CurrentView();
4969   aView->Move(Dx,Dy,Dz,aStart);
4970   return 0;
4971 }
4972
4973 //=======================================================================
4974 //function : VTranslateView
4975 //purpose  :
4976 //=======================================================================
4977 static Standard_Integer VTranslateView (Draw_Interpretor& di,
4978                                 Standard_Integer argc,
4979                                 const char ** argv)
4980 {
4981   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4982   if(aContext.IsNull())
4983   {
4984     di << "use 'vinit' command before " << argv[0] << "\n";
4985     return 1;
4986   }
4987   if(argc < 4 || argc > 5)
4988   {
4989     di<<"Usage : " << argv[0] << " Dx Dy Dz [Start = 1|0]\n";
4990     return 1;
4991   }
4992   Standard_Real Dx = atof(argv[1]);
4993   Standard_Real Dy = atof(argv[2]);
4994   Standard_Real Dz = atof(argv[3]);
4995   Standard_Boolean aStart = Standard_True;
4996   if (argc == 5)
4997   {
4998       aStart = (atoi(argv[4]) > 0);
4999   }
5000
5001   Handle(V3d_View) aView = ViewerTest::CurrentView();
5002   aView->Translate(Dx,Dy,Dz,aStart);
5003   return 0;
5004 }
5005
5006 //=======================================================================
5007 //function : VTurnView
5008 //purpose  :
5009 //=======================================================================
5010 static Standard_Integer VTurnView (Draw_Interpretor& di,
5011                                 Standard_Integer argc,
5012                                 const char ** argv)
5013 {
5014   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
5015   if(aContext.IsNull()) {
5016     di << "use 'vinit' command before " << argv[0] << "\n";
5017     return 1;
5018   }
5019   if(argc < 4 || argc > 5){
5020     di<<"Usage : " << argv[0] << " Ax Ay Az [Start = 1|0]\n";
5021     return 1;
5022   }
5023   Standard_Real Ax = atof(argv[1]);
5024   Standard_Real Ay = atof(argv[2]);
5025   Standard_Real Az = atof(argv[3]);
5026   Standard_Boolean aStart = Standard_True;
5027   if (argc == 5)
5028   {
5029       aStart = (atoi(argv[4]) > 0);
5030   }
5031
5032   Handle(V3d_View) aView = ViewerTest::CurrentView();
5033   aView->Turn(Ax,Ay,Az,aStart);
5034   return 0;
5035 }
5036
5037 //==============================================================================
5038 //function : VTextureEnv
5039 //purpose  : ENables or disables environment mapping
5040 //==============================================================================
5041 class OCC_TextureEnv : public Graphic3d_TextureEnv
5042 {
5043 public:
5044   OCC_TextureEnv(const Standard_CString FileName);
5045   OCC_TextureEnv(const Graphic3d_NameOfTextureEnv aName);
5046   void SetTextureParameters(const Standard_Boolean theRepeatFlag,
5047                             const Standard_Boolean theModulateFlag,
5048                             const Graphic3d_TypeOfTextureFilter theFilter,
5049                             const Standard_ShortReal theXScale,
5050                             const Standard_ShortReal theYScale,
5051                             const Standard_ShortReal theXShift,
5052                             const Standard_ShortReal theYShift,
5053                             const Standard_ShortReal theAngle);
5054   DEFINE_STANDARD_RTTI(OCC_TextureEnv);
5055 };
5056 DEFINE_STANDARD_HANDLE(OCC_TextureEnv, Graphic3d_TextureEnv);
5057 IMPLEMENT_STANDARD_HANDLE(OCC_TextureEnv, Graphic3d_TextureEnv);
5058 IMPLEMENT_STANDARD_RTTIEXT(OCC_TextureEnv, Graphic3d_TextureEnv);
5059
5060 OCC_TextureEnv::OCC_TextureEnv(const Standard_CString theFileName)
5061   : Graphic3d_TextureEnv(theFileName)
5062 {
5063 }
5064
5065 OCC_TextureEnv::OCC_TextureEnv(const Graphic3d_NameOfTextureEnv theTexId)
5066   : Graphic3d_TextureEnv(theTexId)
5067 {
5068 }
5069
5070 void OCC_TextureEnv::SetTextureParameters(const Standard_Boolean theRepeatFlag,
5071                                           const Standard_Boolean theModulateFlag,
5072                                           const Graphic3d_TypeOfTextureFilter theFilter,
5073                                           const Standard_ShortReal theXScale,
5074                                           const Standard_ShortReal theYScale,
5075                                           const Standard_ShortReal theXShift,
5076                                           const Standard_ShortReal theYShift,
5077                                           const Standard_ShortReal theAngle)
5078 {
5079   myParams->SetRepeat     (theRepeatFlag);
5080   myParams->SetModulate   (theModulateFlag);
5081   myParams->SetFilter     (theFilter);
5082   myParams->SetScale      (Graphic3d_Vec2(theXScale, theYScale));
5083   myParams->SetTranslation(Graphic3d_Vec2(theXShift, theYShift));
5084   myParams->SetRotation   (theAngle);
5085 }
5086
5087 static int VTextureEnv (Draw_Interpretor& /*theDI*/, Standard_Integer theArgNb, const char** theArgVec)
5088 {
5089   // get the active view
5090   Handle(V3d_View) aView = ViewerTest::CurrentView();
5091   if (aView.IsNull())
5092   {
5093     std::cerr << "No active view. Please call vinit.\n";
5094     return 1;
5095   }
5096
5097   // Checking the input arguments
5098   Standard_Boolean anEnableFlag = Standard_False;
5099   Standard_Boolean isOk         = theArgNb >= 2;
5100   if (isOk)
5101   {
5102     TCollection_AsciiString anEnableOpt(theArgVec[1]);
5103     anEnableFlag = anEnableOpt.IsEqual("on");
5104     isOk         = anEnableFlag || anEnableOpt.IsEqual("off");
5105   }
5106   if (anEnableFlag)
5107   {
5108     isOk = (theArgNb == 3 || theArgNb == 11);
5109     if (isOk)
5110     {
5111       TCollection_AsciiString aTextureOpt(theArgVec[2]);
5112       isOk = (!aTextureOpt.IsIntegerValue() ||
5113              (aTextureOpt.IntegerValue() >= 0 && aTextureOpt.IntegerValue() < Graphic3d_NOT_ENV_UNKNOWN));
5114
5115       if (isOk && theArgNb == 11)
5116       {
5117         TCollection_AsciiString aRepeatOpt  (theArgVec[3]),
5118                                 aModulateOpt(theArgVec[4]),
5119                                 aFilterOpt  (theArgVec[5]),
5120                                 aSScaleOpt  (theArgVec[6]),
5121                                 aTScaleOpt  (theArgVec[7]),
5122                                 aSTransOpt  (theArgVec[8]),
5123                                 aTTransOpt  (theArgVec[9]),
5124                                 anAngleOpt  (theArgVec[10]);
5125         isOk = ((aRepeatOpt.  IsEqual("repeat")   || aRepeatOpt.  IsEqual("clamp")) &&
5126                 (aModulateOpt.IsEqual("modulate") || aModulateOpt.IsEqual("decal")) &&
5127                 (aFilterOpt.  IsEqual("nearest")  || aFilterOpt.  IsEqual("bilinear") || aFilterOpt.IsEqual("trilinear")) &&
5128                 aSScaleOpt.IsRealValue() && aTScaleOpt.IsRealValue() &&
5129                 aSTransOpt.IsRealValue() && aTTransOpt.IsRealValue() &&
5130                 anAngleOpt.IsRealValue());
5131       }
5132     }
5133   }
5134
5135   if (!isOk)
5136   {
5137     std::cerr << "Usage :" << std::endl;
5138     std::cerr << theArgVec[0] << " off" << std::endl;
5139     std::cerr << theArgVec[0] << " on {index_of_std_texture(0..7)|texture_file_name} [{clamp|repeat} {decal|modulate} {nearest|bilinear|trilinear} scale_s scale_t translation_s translation_t rotation_degrees]" << std::endl;
5140     return 1;
5141   }
5142
5143   if (anEnableFlag)
5144   {
5145     TCollection_AsciiString aTextureOpt(theArgVec[2]);
5146     Handle(OCC_TextureEnv) aTexEnv = aTextureOpt.IsIntegerValue() ?
5147                                      new OCC_TextureEnv((Graphic3d_NameOfTextureEnv)aTextureOpt.IntegerValue()) :
5148                                      new OCC_TextureEnv(theArgVec[2]);
5149
5150     if (theArgNb == 11)
5151     {
5152       TCollection_AsciiString aRepeatOpt(theArgVec[3]), aModulateOpt(theArgVec[4]), aFilterOpt(theArgVec[5]);
5153       aTexEnv->SetTextureParameters(
5154         aRepeatOpt.  IsEqual("repeat"),
5155         aModulateOpt.IsEqual("modulate"),
5156         aFilterOpt.  IsEqual("nearest") ? Graphic3d_TOTF_NEAREST :
5157                                           aFilterOpt.IsEqual("bilinear") ? Graphic3d_TOTF_BILINEAR :
5158                                                                            Graphic3d_TOTF_TRILINEAR,
5159         (Standard_ShortReal)Draw::Atof(theArgVec[6]),
5160         (Standard_ShortReal)Draw::Atof(theArgVec[7]),
5161         (Standard_ShortReal)Draw::Atof(theArgVec[8]),
5162         (Standard_ShortReal)Draw::Atof(theArgVec[9]),
5163         (Standard_ShortReal)Draw::Atof(theArgVec[10])
5164         );
5165     }
5166     aView->SetTextureEnv(aTexEnv);
5167     aView->SetSurfaceDetail(V3d_TEX_ENVIRONMENT);
5168   }
5169   else // Disabling environment mapping
5170   {
5171     aView->SetSurfaceDetail(V3d_TEX_NONE);
5172     Handle(Graphic3d_TextureEnv) aTexture;
5173     aView->SetTextureEnv(aTexture); // Passing null handle to clear the texture data
5174   }
5175
5176   aView->Redraw();
5177   return 0;
5178 }
5179
5180 //===============================================================================================
5181 //function : VClipPlane
5182 //purpose  :
5183 //===============================================================================================
5184 static int VClipPlane (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5185 {
5186   // use short-cut for created clip planes map of created (or "registered by name") clip planes
5187   typedef NCollection_DataMap<TCollection_AsciiString, Handle(Graphic3d_ClipPlane)> MapOfPlanes;
5188   static MapOfPlanes aRegPlanes;
5189
5190   if (theArgsNb < 2)
5191   {
5192     theDi << theArgVec[0] << ": command argument is required. Type help for more information.\n";
5193     return 1;
5194   }
5195
5196   TCollection_AsciiString aCommand (theArgVec[1]);
5197
5198   // print maximum number of planes for current viewer
5199   if (aCommand == "maxplanes")
5200   {
5201     if (theArgsNb < 3)
5202     {
5203       theDi << theArgVec[0] << ": view name is required. Type help for more information.\n";
5204       return 1;
5205     }
5206
5207     TCollection_AsciiString aViewName (theArgVec[2]);
5208
5209     if (!ViewerTest_myViews.IsBound1 (aViewName))
5210     {
5211       theDi << theArgVec[0] << ": view is not found.\n";
5212       return 1;
5213     }
5214
5215     const Handle(V3d_View)& aView = ViewerTest_myViews.Find1 (aViewName);
5216
5217     theDi << theArgVec[0] << ": "
5218                           << aView->Viewer()->Driver()->InquirePlaneLimit()
5219                           << " plane slots provided by driver."
5220                           << " Note that 2 more planes might be used (reserved for z-clipping).\n";
5221
5222     return 0;
5223   }
5224
5225   // create / delete plane instance
5226   if (aCommand == "create" || aCommand == "delete" || aCommand == "clone")
5227   {
5228     if (theArgsNb < 3)
5229     {
5230       theDi << theArgVec[0] << ": plane name is required. Type help for more information.\n";
5231       return 1;
5232     }
5233
5234     Standard_Boolean toCreate = (aCommand == "create");
5235     Standard_Boolean toClone  = (aCommand == "clone");
5236     TCollection_AsciiString aPlane (theArgVec[2]);
5237
5238     if (toCreate)
5239     {
5240       if (aRegPlanes.IsBound (aPlane))
5241       {
5242         theDi << theArgVec[0] << ": plane name is in use.\n";
5243         return 1;
5244       }
5245
5246       aRegPlanes.Bind (aPlane, new Graphic3d_ClipPlane());
5247     }
5248     else if (toClone) // toClone
5249     {
5250       if (!aRegPlanes.IsBound (aPlane))
5251       {
5252         theDi << theArgVec[0] << ": no such plane.\n";
5253         return 1;
5254       }
5255
5256       if (theArgsNb < 4)
5257       {
5258         theDi << theArgVec[0] << ": enter name for new plane. Type help for more information.\n";
5259         return 1;
5260       }
5261
5262       TCollection_AsciiString aClone (theArgVec[3]);
5263       if (aRegPlanes.IsBound (aClone))
5264       {
5265         theDi << theArgVec[0] << ": plane name is in use.\n";
5266         return 1;
5267       }
5268
5269       const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
5270
5271       aRegPlanes.Bind (aClone, aClipPlane->Clone());
5272     }
5273     else// toDelete
5274     {
5275       if (!aRegPlanes.IsBound (aPlane))
5276       {
5277         theDi << theArgVec[0] << ": no such plane.\n";
5278         return 1;
5279       }
5280
5281       Handle(Graphic3d_ClipPlane) aClipPlane = aRegPlanes.Find (aPlane);
5282       aRegPlanes.UnBind (aPlane);
5283
5284       ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName anIObjIt (GetMapOfAIS());
5285       for (; anIObjIt.More(); anIObjIt.Next())
5286       {
5287         Handle(PrsMgr_PresentableObject) aPrs = Handle(PrsMgr_PresentableObject)::DownCast (anIObjIt.Key1());
5288         aPrs->RemoveClipPlane(aClipPlane);
5289       }
5290
5291       NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator aViewIt(ViewerTest_myViews);
5292       for (; aViewIt.More(); aViewIt.Next())
5293       {
5294         const Handle(V3d_View)& aView = aViewIt.Key2();
5295         aView->RemoveClipPlane(aClipPlane);
5296       }
5297
5298       ViewerTest::RedrawAllViews();
5299     }
5300
5301     return 0;
5302   }
5303
5304   // set / unset plane command
5305   if (aCommand == "set" || aCommand == "unset")
5306   {
5307     if (theArgsNb < 4)
5308     {
5309       theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5310       return 1;
5311     }
5312
5313     Standard_Boolean toSet = (aCommand == "set");
5314     TCollection_AsciiString aPlane (theArgVec [2]);
5315     if (!aRegPlanes.IsBound (aPlane))
5316     {
5317       theDi << theArgVec[0] << ": no such plane.\n";
5318       return 1;
5319     }
5320
5321     const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
5322
5323     TCollection_AsciiString aTarget (theArgVec [3]);
5324     if (aTarget != "object" && aTarget != "view")
5325     {
5326       theDi << theArgVec[0] << ": invalid target.\n";
5327       return 1;
5328     }
5329
5330     if (aTarget == "object" || aTarget == "view")
5331     {
5332       if (theArgsNb < 5)
5333       {
5334         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5335         return 1;
5336       }
5337
5338       Standard_Boolean isObject = (aTarget == "object");
5339
5340       for (Standard_Integer anIt = 4; anIt < theArgsNb; ++anIt)
5341       {
5342         TCollection_AsciiString anEntityName (theArgVec[anIt]);
5343         if (isObject) // to object
5344         {
5345           if (!GetMapOfAIS().IsBound2 (anEntityName))
5346           {
5347             theDi << theArgVec[0] << ": can not find IO with name " << anEntityName << ".\n";
5348             continue;
5349           }
5350
5351           Handle(AIS_InteractiveObject) aIObj =
5352             Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (anEntityName));
5353
5354           if (toSet)
5355             aIObj->AddClipPlane (aClipPlane);
5356           else
5357             aIObj->RemoveClipPlane (aClipPlane);
5358         }
5359         else // to view
5360         {
5361           if (!ViewerTest_myViews.IsBound1 (anEntityName))
5362           {
5363             theDi << theArgVec[0] << ": can not find View with name " << anEntityName << ".\n";
5364             continue;
5365           }
5366
5367           Handle(V3d_View) aView = ViewerTest_myViews.Find1(anEntityName);
5368           if (toSet)
5369             aView->AddClipPlane (aClipPlane);
5370           else
5371             aView->RemoveClipPlane (aClipPlane);
5372         }
5373       }
5374
5375       ViewerTest::RedrawAllViews();
5376     }
5377
5378     return 0;
5379   }
5380
5381   // change plane command
5382   if (aCommand == "change")
5383   {
5384     if (theArgsNb < 4)
5385     {
5386       theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5387       return 1;
5388     }
5389
5390     TCollection_AsciiString aPlane (theArgVec [2]);
5391     if (!aRegPlanes.IsBound (aPlane))
5392     {
5393       theDi << theArgVec[0] << ": no such plane.\n";
5394       return 1;
5395     }
5396
5397     const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
5398
5399     TCollection_AsciiString aChangeArg (theArgVec [3]);
5400     if (aChangeArg != "on" && aChangeArg != "off" && aChangeArg != "capping" && aChangeArg != "equation")
5401     {
5402       theDi << theArgVec[0] << ": invalid arguments. Type help for more information.\n";
5403       return 1;
5404     }
5405
5406     if (aChangeArg == "on" || aChangeArg == "off") // on / off
5407     {
5408       aClipPlane->SetOn (aChangeArg == "on");
5409     }
5410     else if (aChangeArg == "equation") // change equation
5411     {
5412       if (theArgsNb < 8)
5413       {
5414         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5415         return 1;
5416       }
5417
5418       Standard_Real aCoeffA = atof (theArgVec [4]);
5419       Standard_Real aCoeffB = atof (theArgVec [5]);
5420       Standard_Real aCoeffC = atof (theArgVec [6]);
5421       Standard_Real aCoeffD = atof (theArgVec [7]);
5422       aClipPlane->SetEquation (gp_Pln (aCoeffA, aCoeffB, aCoeffC, aCoeffD));
5423     }
5424     else if (aChangeArg == "capping") // change capping aspects
5425     {
5426       if (theArgsNb < 5)
5427       {
5428         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5429         return 1;
5430       }
5431
5432       TCollection_AsciiString aCappingArg (theArgVec [4]);
5433       if (aCappingArg != "on" && aCappingArg != "off" &&
5434           aCappingArg != "color" && aCappingArg != "texname" &&
5435           aCappingArg != "texscale" && aCappingArg != "texorigin" &&
5436           aCappingArg != "texrotate" && aCappingArg != "hatch")
5437       {
5438         theDi << theArgVec[0] << ": invalid arguments. Type help for more information.\n";
5439         return 1;
5440       }
5441
5442       if (aCappingArg == "on" || aCappingArg == "off") // on / off capping
5443       {
5444         aClipPlane->SetCapping (aCappingArg == "on");
5445       }
5446       else if (aCappingArg == "color") // color aspect for capping
5447       {
5448         if (theArgsNb < 8)
5449         {
5450           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5451           return 1;
5452         }
5453
5454         Standard_Real aRed = atof (theArgVec [5]);
5455         Standard_Real aGrn = atof (theArgVec [6]);
5456         Standard_Real aBlu = atof (theArgVec [7]);
5457
5458         Graphic3d_MaterialAspect aMat = aClipPlane->CappingMaterial();
5459         aMat.SetColor (Quantity_Color (aRed, aGrn, aBlu, Quantity_TOC_RGB));
5460         aClipPlane->SetCappingMaterial (aMat);
5461       }
5462       else if (aCappingArg == "texname") // texture name
5463       {
5464         if (theArgsNb < 6)
5465         {
5466           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5467           return 1;
5468         }
5469
5470         TCollection_AsciiString aTextureName (theArgVec [5]);
5471
5472         Handle(Graphic3d_Texture2Dmanual) aTexture = new Graphic3d_Texture2Dmanual(aTextureName);
5473         if (!aTexture->IsDone ())
5474         {
5475           aClipPlane->SetCappingTexture (NULL);
5476         }
5477         else
5478         {
5479           aTexture->EnableModulate();
5480           aTexture->EnableRepeat();
5481           aClipPlane->SetCappingTexture (aTexture);
5482         }
5483       }
5484       else if (aCappingArg == "texscale") // texture scale
5485       {
5486         if (aClipPlane->CappingTexture().IsNull())
5487         {
5488           theDi << theArgVec[0] << ": no texture is set.\n";
5489           return 1;
5490         }
5491
5492         if (theArgsNb < 7)
5493         {
5494           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5495           return 1;
5496         }
5497
5498         Standard_ShortReal aSx = (Standard_ShortReal)atof (theArgVec [5]);
5499         Standard_ShortReal aSy = (Standard_ShortReal)atof (theArgVec [6]);
5500
5501         aClipPlane->CappingTexture()->GetParams()->SetScale (Graphic3d_Vec2 (aSx, aSy));
5502       }
5503       else if (aCappingArg == "texorigin") // texture origin
5504       {
5505         if (aClipPlane->CappingTexture().IsNull())
5506         {
5507           theDi << theArgVec[0] << ": no texture is set.\n";
5508           return 1;
5509         }
5510
5511         if (theArgsNb < 7)
5512         {
5513           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5514           return 1;
5515         }
5516
5517         Standard_ShortReal aTx = (Standard_ShortReal)atof (theArgVec [5]);
5518         Standard_ShortReal aTy = (Standard_ShortReal)atof (theArgVec [6]);
5519
5520         aClipPlane->CappingTexture()->GetParams()->SetTranslation (Graphic3d_Vec2 (aTx, aTy));
5521       }
5522       else if (aCappingArg == "texrotate") // texture rotation
5523       {
5524         if (aClipPlane->CappingTexture().IsNull())
5525         {
5526           theDi << theArgVec[0] << ": no texture is set.\n";
5527           return 1;
5528         }
5529
5530         if (theArgsNb < 6)
5531         {
5532           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5533           return 1;
5534         }
5535
5536         Standard_ShortReal aRot = (Standard_ShortReal)atof (theArgVec[5]);
5537
5538         aClipPlane->CappingTexture()->GetParams()->SetRotation (aRot);
5539       }
5540       else if (aCappingArg == "hatch") // hatch style
5541       {
5542         if (theArgsNb < 6)
5543         {
5544           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5545           return 1;
5546         }
5547
5548         TCollection_AsciiString aHatchStr (theArgVec [5]);
5549         if (aHatchStr == "on")
5550         {
5551           aClipPlane->SetCappingHatchOn();
5552         }
5553         else if (aHatchStr == "off")
5554         {
5555           aClipPlane->SetCappingHatchOff();
5556         }
5557         else
5558         {
5559           aClipPlane->SetCappingHatch ((Aspect_HatchStyle)atoi (theArgVec[5]));
5560         }
5561       }
5562     }
5563
5564     ViewerTest::RedrawAllViews();
5565
5566     return 0;
5567   }
5568
5569   theDi << theArgVec[0] << ": invalid command. Type help for more information.\n";
5570   return 1;
5571 }
5572
5573 //===============================================================================================
5574 //function : VSetTextureMode
5575 //purpose  :
5576 //===============================================================================================
5577 static int VSetTextureMode (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5578 {
5579   if (theArgsNb < 3)
5580   {
5581     theDi << theArgVec[0] << ": insufficient command arguments. Type help for more information.\n";
5582     return 1;
5583   }
5584
5585   TCollection_AsciiString aViewName (theArgVec[1]);
5586   if (!ViewerTest_myViews.IsBound1 (aViewName))
5587   {
5588     theDi << theArgVec[0] << ": view is not found.\n";
5589     return 1;
5590   }
5591
5592   const Handle(V3d_View)& aView = ViewerTest_myViews.Find1 (aViewName);
5593   switch (atoi (theArgVec[2]))
5594   {
5595     case 0: aView->SetSurfaceDetail (V3d_TEX_NONE); break;
5596     case 1: aView->SetSurfaceDetail (V3d_TEX_ENVIRONMENT); break;
5597     case 2: aView->SetSurfaceDetail (V3d_TEX_ALL); break;
5598     default:
5599       theDi << theArgVec[0] << ": invalid mode.\n";
5600       return 1;
5601   }
5602
5603   aView->Redraw();
5604   return 0;
5605 }
5606
5607 //===============================================================================================
5608 //function : VZRange
5609 //purpose  :
5610 //===============================================================================================
5611 static int VZRange (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5612 {
5613   const Handle(V3d_View)& aCurrentView = ViewerTest::CurrentView();
5614
5615   if (aCurrentView.IsNull())
5616   {
5617     std::cout << theArgVec[0] << ": Call vinit before this command, please.\n";
5618     return 1;
5619   }
5620
5621   Handle(Graphic3d_Camera) aCamera = aCurrentView->Camera();
5622
5623   if (theArgsNb < 2)
5624   {
5625     theDi << "ZNear: " << aCamera->ZNear() << "\n";
5626     theDi << "ZFar: " << aCamera->ZFar() << "\n";
5627     return 0;
5628   }
5629
5630   if (theArgsNb == 3)
5631   {
5632     Standard_Real aNewZNear = atof (theArgVec[1]);
5633     Standard_Real aNewZFar = atof (theArgVec[2]);
5634
5635     if (aNewZNear >= aNewZFar)
5636     {
5637       std::cout << theArgVec[0] << ": invalid arguments: znear should be less than zfar.\n";
5638       return 1;
5639     }
5640
5641     if (!aCamera->IsOrthographic() && (aNewZNear <= 0.0 || aNewZFar <= 0.0))
5642     {
5643       std::cout << theArgVec[0] << ": invalid arguments: ";
5644       std::cout << "znear, zfar should be positive for perspective camera.\n";
5645       return 1;
5646     }
5647
5648     aCamera->SetZRange (aNewZNear, aNewZFar);
5649   }
5650   else
5651   {
5652     std::cout << theArgVec[0] << ": wrong command arguments. Type help for more information.\n";
5653     return 1;
5654   }
5655
5656   aCurrentView->Redraw();
5657
5658   return 0;
5659 }
5660
5661 //===============================================================================================
5662 //function : VAutoZFit
5663 //purpose  :
5664 //===============================================================================================
5665 static int VAutoZFit (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5666 {
5667   const Handle(V3d_View)& aCurrentView = ViewerTest::CurrentView();
5668
5669   if (aCurrentView.IsNull())
5670   {
5671     std::cout << theArgVec[0] << ": Call vinit before this command, please.\n";
5672     return 1;
5673   }
5674
5675   Standard_Real aScale = aCurrentView->AutoZFitScaleFactor();
5676
5677   if (theArgsNb > 3)
5678   {
5679     std::cout << theArgVec[0] << ": wrong command arguments. Type help for more information.\n";
5680     return 1;
5681   }
5682
5683   if (theArgsNb < 2)
5684   {
5685     theDi << "Auto z-fit mode: " << "\n"
5686           << "On: " << (aCurrentView->AutoZFitMode() ? "enabled" : "disabled") << "\n"
5687           << "Scale: " << aScale << "\n";
5688     return 0;
5689   }
5690
5691   Standard_Boolean isOn = Draw::Atoi (theArgVec[1]) == 1;
5692
5693   if (theArgsNb >= 3)
5694   {
5695     aScale = Draw::Atoi (theArgVec[2]);
5696   }
5697
5698   aCurrentView->SetAutoZFitMode (isOn, aScale);
5699   aCurrentView->AutoZFit();
5700   aCurrentView->Redraw();
5701
5702   return 0;
5703 }
5704
5705 //===============================================================================================
5706 //function : VChangeCamera
5707 //purpose  :
5708 //===============================================================================================
5709 static int VChangeCamera (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5710 {
5711   if (ViewerTest::CurrentView().IsNull())
5712   {
5713     theDi << theArgVec[0] << ": Call vinit before this command, please.\n";
5714     return 1;
5715   }
5716
5717   const char anErrorMessage[] = ": wrong command arguments. Type help for more information.\n";
5718   if (theArgsNb < 3)
5719   {
5720     theDi << theArgVec[0] << anErrorMessage;
5721     return 1;
5722   }
5723
5724   Handle(Graphic3d_Camera) aCamera = ViewerTest::CurrentView()->Camera();
5725
5726   TCollection_AsciiString aCommand (theArgVec[1]);
5727   TCollection_AsciiString aValue (theArgVec[2]);
5728
5729   aCommand.LowerCase();
5730   aValue.LowerCase();
5731
5732   if (aCommand == "proj")
5733   {
5734     if (aValue == "ortho")
5735     {
5736       aCamera->SetProjectionType (Graphic3d_Camera::Projection_Orthographic);
5737     } 
5738     else if (aValue == "persp")
5739     {
5740       aCamera->SetProjectionType (Graphic3d_Camera::Projection_Perspective);
5741     }
5742     else if (aValue == "left")
5743     {
5744       aCamera->SetProjectionType (Graphic3d_Camera::Projection_MonoLeftEye);
5745     }
5746     else if (aValue == "right")
5747     {
5748       aCamera->SetProjectionType (Graphic3d_Camera::Projection_MonoRightEye);
5749     }
5750     else if (aValue == "stereo")
5751     {
5752       aCamera->SetProjectionType (Graphic3d_Camera::Projection_Stereo);
5753     }
5754     else
5755     {
5756       theDi << theArgVec[0] << anErrorMessage;
5757       return 1;
5758     }
5759   }
5760   else if (aCommand == "dist")
5761   {
5762     aCamera->SetDistance (aValue.RealValue());
5763   }
5764   else if (aCommand == "iod")
5765   {
5766     aCamera->SetIOD (aCamera->GetIODType(), aValue.RealValue());
5767   }
5768   else if (aCommand == "zfocus")
5769   {
5770     aCamera->SetZFocus (aCamera->ZFocusType(), aValue.RealValue());
5771   }
5772   else if (aCommand == "fov")
5773   {
5774     aCamera->SetFOVy (aValue.RealValue());
5775   }
5776   else if (aCommand == "zfocustype")
5777   {
5778     if (aValue == "absolute")
5779     {
5780       aCamera->SetZFocus (Graphic3d_Camera::FocusType_Absolute, aCamera->ZFocus());
5781     } 
5782     else if (aValue == "relative")
5783     {
5784       aCamera->SetZFocus (Graphic3d_Camera::FocusType_Relative, aCamera->ZFocus());
5785     }
5786     else
5787     {
5788       theDi << theArgVec[0] << anErrorMessage;
5789       return 1;
5790     }
5791   }
5792   else if (aCommand == "iodtype")
5793   {
5794     if (aValue == "absolute")
5795     {
5796       aCamera->SetIOD (Graphic3d_Camera::IODType_Absolute, aCamera->IOD());
5797     } 
5798     else if (aValue == "relative")
5799     {
5800       aCamera->SetIOD (Graphic3d_Camera::IODType_Relative, aCamera->IOD());
5801     }
5802     else
5803     {
5804       theDi << theArgVec[0] << anErrorMessage;
5805       return 1;
5806     }
5807   }
5808   else
5809   {
5810     theDi << theArgVec[0] << anErrorMessage;
5811     return 1;
5812   }
5813
5814   ViewerTest::CurrentView()->AutoZFit();
5815   ViewerTest::CurrentView()->Redraw();
5816
5817   return 0;
5818 }
5819
5820 //==============================================================================
5821 //function : VStereo
5822 //purpose  :
5823 //==============================================================================
5824
5825 static int VStereo (Draw_Interpretor& theDI,
5826                     Standard_Integer  theArgNb,
5827                     const char**      theArgVec)
5828 {
5829   if (theArgNb < 2)
5830   {
5831     Handle(V3d_View) aView = ViewerTest::CurrentView();
5832     if (aView.IsNull())
5833     {
5834       std::cerr << "No active view. Please call vinit.\n";
5835       return 0;
5836     }
5837
5838     Standard_Boolean isActive = ViewerTest_myDefaultCaps.contextStereo;
5839     theDI << "Stereo " << (isActive ? "ON" : "OFF") << "\n";
5840     return 0;
5841   }
5842
5843   ViewerTest_myDefaultCaps.contextStereo = Draw::Atoi (theArgVec[1]) != 0;
5844   return 0;
5845 }
5846
5847 //===============================================================================================
5848 //function : VDefaults
5849 //purpose  :
5850 //===============================================================================================
5851 static int VDefaults (Draw_Interpretor& theDi,
5852                       Standard_Integer  theArgsNb,
5853                       const char**      theArgVec)
5854 {
5855   const Handle(AIS_InteractiveContext)& aCtx = ViewerTest::GetAISContext();
5856   if (aCtx.IsNull())
5857   {
5858     std::cerr << "No active viewer!\n";
5859     return 1;
5860   }
5861
5862   Handle(Prs3d_Drawer) aDefParams = aCtx->DefaultDrawer();
5863   if (theArgsNb < 2)
5864   {
5865     if (aDefParams->TypeOfDeflection() == Aspect_TOD_RELATIVE)
5866     {
5867       theDi << "DeflType:           relative\n"
5868             << "DeviationCoeff:     " << aDefParams->DeviationCoefficient() << "\n";
5869     }
5870     else
5871     {
5872       theDi << "DeflType:           absolute\n"
5873             << "AbsoluteDeflection: " << aDefParams->MaximalChordialDeviation() << "\n";
5874     }
5875     theDi << "AngularDeflection:  " << (180.0 * aDefParams->HLRAngle() / M_PI) << "\n";
5876     return 0;
5877   }
5878
5879   for (Standard_Integer anArgIter = 1; anArgIter < theArgsNb; ++anArgIter)
5880   {
5881     TCollection_AsciiString anArg (theArgVec[anArgIter]);
5882     TCollection_AsciiString aKey, aValue;
5883     if (!ViewerTest::SplitParameter (anArg, aKey, aValue)
5884      || aValue.IsEmpty())
5885     {
5886       std::cerr << "Error, wrong syntax at: '" << anArg.ToCString() << "'!\n";
5887       return 1;
5888     }
5889
5890     aKey.UpperCase();
5891     if (aKey == "ABSDEFL"
5892      || aKey == "ABSOLUTEDEFLECTION"
5893      || aKey == "DEFL"
5894      || aKey == "DEFLECTION")
5895     {
5896       aDefParams->SetTypeOfDeflection         (Aspect_TOD_ABSOLUTE);
5897       aDefParams->SetMaximalChordialDeviation (aValue.RealValue());
5898     }
5899     else if (aKey == "RELDEFL"
5900           || aKey == "RELATIVEDEFLECTION"
5901           || aKey == "DEVCOEFF"
5902           || aKey == "DEVIATIONCOEFF"
5903           || aKey == "DEVIATIONCOEFFICIENT")
5904     {
5905       aDefParams->SetTypeOfDeflection     (Aspect_TOD_RELATIVE);
5906       aDefParams->SetDeviationCoefficient (aValue.RealValue());
5907     }
5908     else if (aKey == "ANGDEFL"
5909           || aKey == "ANGULARDEFL"
5910           || aKey == "ANGULARDEFLECTION")
5911     {
5912       // currently HLRDeviationAngle is used instead of DeviationAngle in most places
5913       aDefParams->SetHLRAngle (M_PI * aValue.RealValue() / 180.0);
5914     }
5915     else
5916     {
5917       std::cerr << "Warning, unknown argument '" << anArg.ToCString() << "'\n";
5918     }
5919   }
5920
5921   return 0;
5922 }
5923
5924 //! Auxiliary method
5925 inline void addLight (const Handle(V3d_Light)& theLightNew,
5926                       const Standard_Boolean   theIsGlobal)
5927 {
5928   if (theLightNew.IsNull())
5929   {
5930     return;
5931   }
5932
5933   if (theIsGlobal)
5934   {
5935     ViewerTest::GetViewerFromContext()->SetLightOn (theLightNew);
5936   }
5937   else
5938   {
5939     ViewerTest::CurrentView()->SetLightOn (theLightNew);
5940   }
5941 }
5942
5943 //! Auxiliary method
5944 inline Standard_Integer getLightId (const TCollection_AsciiString& theArgNext)
5945 {
5946   TCollection_AsciiString anArgNextCase (theArgNext);
5947   anArgNextCase.UpperCase();
5948   if (anArgNextCase.Length() > 5
5949    && anArgNextCase.SubString (1, 5).IsEqual ("LIGHT"))
5950   {
5951     return theArgNext.SubString (6, theArgNext.Length()).IntegerValue();
5952   }
5953   else
5954   {
5955     return theArgNext.IntegerValue();
5956   }
5957 }
5958
5959 //===============================================================================================
5960 //function : VLight
5961 //purpose  :
5962 //===============================================================================================
5963 static int VLight (Draw_Interpretor& theDi,
5964                    Standard_Integer  theArgsNb,
5965                    const char**      theArgVec)
5966 {
5967   Handle(V3d_View)   aView   = ViewerTest::CurrentView();
5968   Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext();
5969   if (aView.IsNull()
5970    || aViewer.IsNull())
5971   {
5972     std::cerr << "No active viewer!\n";
5973     return 1;
5974   }
5975
5976   Standard_Real        anXYZ[3];
5977   Quantity_Coefficient anAtten[2];
5978   if (theArgsNb < 2)
5979   {
5980     // print lights info
5981     Standard_Integer aLightId = 0;
5982     for (aView->InitActiveLights(); aView->MoreActiveLights(); aView->NextActiveLights(), ++aLightId)
5983     {
5984       Handle(V3d_Light) aLight = aView->ActiveLight();
5985       const Quantity_Color aColor = aLight->Color();
5986       theDi << "Light" << aLightId << "\n";
5987       switch (aLight->Type())
5988       {
5989         case V3d_AMBIENT:
5990         {
5991           theDi << "  Type:      Ambient\n";
5992           break;
5993         }
5994         case V3d_DIRECTIONAL:
5995         {
5996           Handle(V3d_DirectionalLight) aLightDir = Handle(V3d_DirectionalLight)::DownCast (aLight);
5997           theDi << "  Type:      Directional\n";
5998           theDi << "  Headlight: " << (aLight->Headlight() ? "TRUE" : "FALSE") << "\n";
5999           if (!aLightDir.IsNull())
6000           {
6001             aLightDir->Position  (anXYZ[0], anXYZ[1], anXYZ[2]);
6002             theDi << "  Position:  " << anXYZ[0] << ", " << anXYZ[1] << ", " << anXYZ[2] << "\n";
6003             aLightDir->Direction (anXYZ[0], anXYZ[1], anXYZ[2]);
6004             theDi << "  Direction: " << anXYZ[0] << ", " << anXYZ[1] << ", " << anXYZ[2] << "\n";
6005           }
6006           break;
6007         }
6008         case V3d_POSITIONAL:
6009         {
6010           Handle(V3d_PositionalLight) aLightPos = Handle(V3d_PositionalLight)::DownCast (aLight);
6011           theDi << "  Type:      Positional\n";
6012           theDi << "  Headlight: " << (aLight->Headlight() ? "TRUE" : "FALSE") << "\n";
6013           if (!aLightPos.IsNull())
6014           {
6015             aLightPos->Position  (anXYZ[0], anXYZ[1], anXYZ[2]);
6016             theDi << "  Position:  " << anXYZ[0] << ", " << anXYZ[1] << ", " << anXYZ[2] << "\n";
6017             aLightPos->Attenuation (anAtten[0], anAtten[1]);
6018             theDi << "  Atten.:    " << anAtten[0] << " " << anAtten[1] << "\n";
6019           }
6020           break;
6021         }
6022         case V3d_SPOT:
6023         {
6024           Handle(V3d_SpotLight) aLightSpot = Handle(V3d_SpotLight)::DownCast (aLight);
6025           theDi << "  Type:      Spot\n";
6026           theDi << "  Headlight: " << (aLight->Headlight() ? "TRUE" : "FALSE") << "\n";
6027           if (!aLightSpot.IsNull())
6028           {
6029             aLightSpot->Position  (anXYZ[0], anXYZ[1], anXYZ[2]);
6030             theDi << "  Position:  " << anXYZ[0] << ", " << anXYZ[1] << ", " << anXYZ[2] << "\n";
6031             aLightSpot->Direction (anXYZ[0], anXYZ[1], anXYZ[2]);
6032             theDi << "  Direction: " << anXYZ[0] << ", " << anXYZ[1] << ", " << anXYZ[2] << "\n";
6033             aLightSpot->Attenuation (anAtten[0], anAtten[1]);
6034             theDi << "  Atten.:    " << anAtten[0] << " " << anAtten[1] << "\n";
6035             theDi << "  Angle:     " << (aLightSpot->Angle() * 180.0 / M_PI) << "\n";
6036             theDi << "  Exponent:  " << aLightSpot->Concentration() << "\n";
6037           }
6038           break;
6039         }
6040         default:
6041         {
6042           theDi << "  Type:      UNKNOWN\n";
6043           break;
6044         }
6045       }
6046       theDi << "  Color:     " << aColor.Red() << ", " << aColor.Green() << ", " << aColor.Blue() << "\n";
6047     }
6048   }
6049
6050   Handle(V3d_Light) aLightNew;
6051   Handle(V3d_Light) aLightOld;
6052   Standard_Boolean  isGlobal = Standard_True;
6053   Standard_Boolean  toCreate = Standard_False;
6054   for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
6055   {
6056     Handle(V3d_Light)            aLightCurr = aLightNew.IsNull() ? aLightOld : aLightNew;
6057     Handle(V3d_AmbientLight)     aLightAmb  = Handle(V3d_AmbientLight)    ::DownCast (aLightCurr);
6058     Handle(V3d_DirectionalLight) aLightDir  = Handle(V3d_DirectionalLight)::DownCast (aLightCurr);
6059     Handle(V3d_PositionalLight)  aLightPos  = Handle(V3d_PositionalLight) ::DownCast (aLightCurr);
6060     Handle(V3d_SpotLight)        aLightSpot = Handle(V3d_SpotLight)       ::DownCast (aLightCurr);
6061
6062     TCollection_AsciiString aName, aValue;
6063     const TCollection_AsciiString anArg (theArgVec[anArgIt]);
6064     TCollection_AsciiString anArgCase (anArg);
6065     anArgCase.UpperCase();
6066     if (anArgCase.IsEqual ("NEW")
6067      || anArgCase.IsEqual ("ADD")
6068      || anArgCase.IsEqual ("CREATE"))
6069     {
6070       toCreate = Standard_True;
6071     }
6072     else if (anArgCase.IsEqual ("GLOB")
6073           || anArgCase.IsEqual ("GLOBAL"))
6074     {
6075       isGlobal = Standard_True;
6076     }
6077     else if (anArgCase.IsEqual ("LOC")
6078           || anArgCase.IsEqual ("LOCAL"))
6079     {
6080       isGlobal = Standard_False;
6081     }
6082     else if (anArgCase.IsEqual ("DEF")
6083           || anArgCase.IsEqual ("DEFAULTS"))
6084     {
6085       toCreate = Standard_False;
6086       aViewer->SetDefaultLights();
6087     }
6088     else if (anArgCase.IsEqual ("CLR")
6089           || anArgCase.IsEqual ("CLEAR"))
6090     {
6091       toCreate = Standard_False;
6092       aView->InitActiveLights();
6093       while (aView->MoreActiveLights())
6094       {
6095         aViewer->DelLight (aView->ActiveLight());
6096         aView->InitActiveLights();
6097       }
6098     }
6099     else if (anArgCase.IsEqual ("AMB")
6100           || anArgCase.IsEqual ("AMBIENT")
6101           || anArgCase.IsEqual ("AMBLIGHT"))
6102     {
6103       addLight (aLightNew, isGlobal);
6104       if (!toCreate)
6105       {
6106         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6107         return 1;
6108       }
6109       toCreate  = Standard_False;
6110       aLightNew = new V3d_AmbientLight (aViewer);
6111     }
6112     else if (anArgCase.IsEqual ("DIRECTIONAL")
6113           || anArgCase.IsEqual ("DIRLIGHT"))
6114     {
6115       addLight (aLightNew, isGlobal);
6116       if (!toCreate)
6117       {
6118         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6119         return 1;
6120       }
6121       toCreate  = Standard_False;
6122       aLightNew = new V3d_DirectionalLight (aViewer);
6123     }
6124     else if (anArgCase.IsEqual ("SPOT")
6125           || anArgCase.IsEqual ("SPOTLIGHT"))
6126     {
6127       addLight (aLightNew, isGlobal);
6128       if (!toCreate)
6129       {
6130         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6131         return 1;
6132       }
6133       toCreate  = Standard_False;
6134       aLightNew = new V3d_SpotLight (aViewer, 0.0, 0.0, 0.0);
6135     }
6136     else if (anArgCase.IsEqual ("POSLIGHT")
6137           || anArgCase.IsEqual ("POSITIONAL"))
6138     {
6139       addLight (aLightNew, isGlobal);
6140       if (!toCreate)
6141       {
6142         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6143         return 1;
6144       }
6145       toCreate  = Standard_False;
6146       aLightNew = new V3d_PositionalLight (aViewer, 0.0, 0.0, 0.0);
6147     }
6148     else if (anArgCase.IsEqual ("CHANGE"))
6149     {
6150       addLight (aLightNew, isGlobal);
6151       aLightNew.Nullify();
6152       if (++anArgIt >= theArgsNb)
6153       {
6154         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6155         return 1;
6156       }
6157
6158       const Standard_Integer aLightId = getLightId (theArgVec[anArgIt]);
6159       Standard_Integer aLightIt = 0;
6160       for (aView->InitActiveLights(); aView->MoreActiveLights(); aView->NextActiveLights(), ++aLightIt)
6161       {
6162         if (aLightIt == aLightId)
6163         {
6164           aLightOld = aView->ActiveLight();
6165           break;
6166         }
6167       }
6168
6169       if (aLightOld.IsNull())
6170       {
6171         std::cerr << "Light " << theArgVec[anArgIt] << " is undefined!\n";
6172         return 1;
6173       }
6174     }
6175     else if (anArgCase.IsEqual ("DEL")
6176           || anArgCase.IsEqual ("DELETE"))
6177     {
6178       Handle(V3d_Light) aLightDel;
6179       if (++anArgIt >= theArgsNb)
6180       {
6181         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6182         return 1;
6183       }
6184
6185       const TCollection_AsciiString anArgNext (theArgVec[anArgIt]);
6186       const Standard_Integer aLightDelId = getLightId (theArgVec[anArgIt]);
6187       Standard_Integer aLightIt = 0;
6188       for (aView->InitActiveLights(); aView->MoreActiveLights(); aView->NextActiveLights(), ++aLightIt)
6189       {
6190         aLightDel = aView->ActiveLight();
6191         if (aLightIt == aLightDelId)
6192         {
6193           break;
6194         }
6195       }
6196       if (!aLightDel.IsNull())
6197       {
6198         aViewer->DelLight (aLightDel);
6199       }
6200     }
6201     else if (anArgCase.IsEqual ("COLOR")
6202           || anArgCase.IsEqual ("COLOUR"))
6203     {
6204       if (++anArgIt >= theArgsNb)
6205       {
6206         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6207         return 1;
6208       }
6209
6210       TCollection_AsciiString anArgNext (theArgVec[anArgIt]);
6211       anArgNext.UpperCase();
6212       const Quantity_Color aColor = ViewerTest::GetColorFromName (anArgNext.ToCString());
6213       if (!aLightCurr.IsNull())
6214       {
6215         aLightCurr->SetColor (aColor);
6216       }
6217     }
6218     else if (anArgCase.IsEqual ("POS")
6219           || anArgCase.IsEqual ("POSITION"))
6220     {
6221       if ((anArgIt + 3) >= theArgsNb)
6222       {
6223         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6224         return 1;
6225       }
6226
6227       anXYZ[0] = Atof (theArgVec[++anArgIt]);
6228       anXYZ[1] = Atof (theArgVec[++anArgIt]);
6229       anXYZ[2] = Atof (theArgVec[++anArgIt]);
6230       if (!aLightDir.IsNull())
6231       {
6232         aLightDir->SetPosition (anXYZ[0], anXYZ[1], anXYZ[2]);
6233       }
6234       else if (!aLightPos.IsNull())
6235       {
6236         aLightPos->SetPosition (anXYZ[0], anXYZ[1], anXYZ[2]);
6237       }
6238       else if (!aLightSpot.IsNull())
6239       {
6240         aLightSpot->SetPosition (anXYZ[0], anXYZ[1], anXYZ[2]);
6241       }
6242       else
6243       {
6244         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6245         return 1;
6246       }
6247     }
6248     else if (anArgCase.IsEqual ("DIR")
6249           || anArgCase.IsEqual ("DIRECTION"))
6250     {
6251       if ((anArgIt + 3) >= theArgsNb)
6252       {
6253         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6254         return 1;
6255       }
6256
6257       anXYZ[0] = Atof (theArgVec[++anArgIt]);
6258       anXYZ[1] = Atof (theArgVec[++anArgIt]);
6259       anXYZ[2] = Atof (theArgVec[++anArgIt]);
6260       if (!aLightDir.IsNull())
6261       {
6262         aLightDir->SetDirection (anXYZ[0], anXYZ[1], anXYZ[2]);
6263       }
6264       else if (!aLightSpot.IsNull())
6265       {
6266         aLightSpot->SetDirection (anXYZ[0], anXYZ[1], anXYZ[2]);
6267       }
6268       else
6269       {
6270         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6271         return 1;
6272       }
6273     }
6274     else if (anArgCase.IsEqual ("ANG")
6275           || anArgCase.IsEqual ("ANGLE"))
6276     {
6277       if (++anArgIt >= theArgsNb)
6278       {
6279         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6280         return 1;
6281       }
6282
6283       Standard_Real anAngle = Atof (theArgVec[anArgIt]);
6284
6285       if (!aLightSpot.IsNull())
6286       {
6287         aLightSpot->SetAngle (anAngle / 180.0 * M_PI);
6288       }
6289     }
6290     else if (anArgCase.IsEqual ("CONSTATTEN")
6291           || anArgCase.IsEqual ("CONSTATTENUATION"))
6292     {
6293       if (++anArgIt >= theArgsNb)
6294       {
6295         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6296         return 1;
6297       }
6298
6299       if (!aLightPos.IsNull())
6300       {
6301         aLightPos->Attenuation (anAtten[0], anAtten[1]);
6302         anAtten[0] = Atof (theArgVec[anArgIt]);
6303         aLightPos->SetAttenuation (anAtten[0], anAtten[1]);
6304       }
6305       else if (!aLightSpot.IsNull())
6306       {
6307         aLightSpot->Attenuation (anAtten[0], anAtten[1]);
6308         anAtten[0] = Atof (theArgVec[anArgIt]);
6309         aLightSpot->SetAttenuation (anAtten[0], anAtten[1]);
6310       }
6311       else
6312       {
6313         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6314         return 1;
6315       }
6316     }
6317     else if (anArgCase.IsEqual ("LINATTEN")
6318           || anArgCase.IsEqual ("LINEARATTEN")
6319           || anArgCase.IsEqual ("LINEARATTENUATION"))
6320     {
6321       if (++anArgIt >= theArgsNb)
6322       {
6323         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6324         return 1;
6325       }
6326
6327       if (!aLightPos.IsNull())
6328       {
6329         aLightPos->Attenuation (anAtten[0], anAtten[1]);
6330         anAtten[1] = Atof (theArgVec[anArgIt]);
6331         aLightPos->SetAttenuation (anAtten[0], anAtten[1]);
6332       }
6333       else if (!aLightSpot.IsNull())
6334       {
6335         aLightSpot->Attenuation (anAtten[0], anAtten[1]);
6336         anAtten[1] = Atof (theArgVec[anArgIt]);
6337         aLightSpot->SetAttenuation (anAtten[0], anAtten[1]);
6338       }
6339       else
6340       {
6341         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6342         return 1;
6343       }
6344     }
6345     else if (anArgCase.IsEqual ("EXP")
6346           || anArgCase.IsEqual ("EXPONENT")
6347           || anArgCase.IsEqual ("SPOTEXP")
6348           || anArgCase.IsEqual ("SPOTEXPONENT"))
6349     {
6350       if (++anArgIt >= theArgsNb)
6351       {
6352         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6353         return 1;
6354       }
6355
6356       if (!aLightSpot.IsNull())
6357       {
6358         aLightSpot->SetConcentration (Atof (theArgVec[anArgIt]));
6359       }
6360       else
6361       {
6362         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6363         return 1;
6364       }
6365     }
6366     else if (anArgCase.IsEqual ("HEAD")
6367           || anArgCase.IsEqual ("HEADLIGHT"))
6368     {
6369       if (++anArgIt >= theArgsNb)
6370       {
6371         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6372         return 1;
6373       }
6374
6375       if (aLightAmb.IsNull()
6376        && !aLightCurr.IsNull())
6377       {
6378         aLightCurr->SetHeadlight (Draw::Atoi (theArgVec[anArgIt]) != 0);
6379       }
6380       else
6381       {
6382         std::cerr << "Wrong syntax at argument '" << anArg << "'!\n";
6383         return 1;
6384       }
6385     }
6386     else
6387     {
6388       std::cerr << "Warning: unknown argument '" << anArg << "'\n";
6389     }
6390   }
6391
6392   addLight (aLightNew, isGlobal);
6393   aViewer->UpdateLights();
6394
6395   return 0;
6396 }
6397
6398 inline Standard_Boolean parseOnOff (Standard_CString  theArg,
6399                                     Standard_Boolean& theIsOn)
6400 {
6401   TCollection_AsciiString aFlag (theArg);
6402   aFlag.LowerCase();
6403   if (aFlag == "on")
6404   {
6405     theIsOn = Standard_True;
6406     return Standard_True;
6407   }
6408   else if (aFlag == "off")
6409   {
6410     theIsOn = Standard_False;
6411     return Standard_True;
6412   }
6413   return Standard_False;
6414 }
6415
6416 //=======================================================================
6417 //function : VRenderParams
6418 //purpose  : Enables/disables rendering features
6419 //=======================================================================
6420
6421 static Standard_Integer VRenderParams (Draw_Interpretor& theDI,
6422                                        Standard_Integer  theArgNb,
6423                                        const char**      theArgVec)
6424 {
6425   Handle(V3d_View) aView = ViewerTest::CurrentView();
6426   if (aView.IsNull())
6427   {
6428     std::cerr << "Error: no active viewer!\n";
6429     return 1;
6430   }
6431
6432   Graphic3d_RenderingParams& aParams = aView->ChangeRenderingParams();
6433
6434   if (theArgNb < 2)
6435   {
6436     theDI << "renderMode:  ";
6437     switch (aParams.Method)
6438     {
6439       case Graphic3d_RM_RASTERIZATION: theDI << "rasterization "; break;
6440       case Graphic3d_RM_RAYTRACING:    theDI << "raytrace ";      break;
6441     }
6442     theDI << "\n";
6443     theDI << "fsaa:        " << (aParams.IsAntialiasingEnabled      ? "on" : "off") << "\n";
6444     theDI << "shadows:     " << (aParams.IsShadowEnabled            ? "on" : "off") << "\n";
6445     theDI << "reflections: " << (aParams.IsReflectionEnabled        ? "on" : "off") << "\n";
6446     theDI << "rayDepth:    " <<  aParams.RaytracingDepth                            << "\n";
6447     theDI << "gleam:       " << (aParams.IsTransparentShadowEnabled ? "on" : "off") << "\n";
6448     return 0;
6449   }
6450
6451   Standard_Boolean toPrint = Standard_False;
6452   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
6453   {
6454     Standard_CString        anArg (theArgVec[anArgIter]);
6455     TCollection_AsciiString aFlag (anArg);
6456     aFlag.LowerCase();
6457     if (aFlag == "-echo"
6458      || aFlag == "-print")
6459     {
6460       toPrint = Standard_True;
6461     }
6462     else if (aFlag == "-mode"
6463           || aFlag == "-rendermode"
6464           || aFlag == "-render_mode")
6465     {
6466       if (toPrint)
6467       {
6468         switch (aParams.Method)
6469         {
6470           case Graphic3d_RM_RASTERIZATION: theDI << "rasterization "; break;
6471           case Graphic3d_RM_RAYTRACING:    theDI << "ray-tracing ";   break;
6472         }
6473         continue;
6474       }
6475       else
6476       {
6477         std::cerr << "Error: wrong syntax at argument '" << anArg << "'\n";
6478         return 1;
6479       }
6480     }
6481     else if (aFlag == "-ray"
6482           || aFlag == "-raytrace")
6483     {
6484       if (toPrint)
6485       {
6486         theDI << (aParams.Method == Graphic3d_RM_RAYTRACING ? "true" : "false") << " ";
6487         continue;
6488       }
6489
6490       aParams.Method = Graphic3d_RM_RAYTRACING;
6491     }
6492     else if (aFlag == "-rast"
6493           || aFlag == "-raster"
6494           || aFlag == "-rasterization")
6495     {
6496       if (toPrint)
6497       {
6498         theDI << (aParams.Method == Graphic3d_RM_RASTERIZATION ? "true" : "false") << " ";
6499         continue;
6500       }
6501
6502       aParams.Method = Graphic3d_RM_RASTERIZATION;
6503     }
6504     else if (aFlag == "-raydepth"
6505           || aFlag == "-ray_depth")
6506     {
6507       if (toPrint)
6508       {
6509         theDI << aParams.RaytracingDepth << " ";
6510         continue;
6511       }
6512       else if (++anArgIter >= theArgNb)
6513       {
6514         std::cerr << "Error: wrong syntax at argument '" << anArg << "'\n";
6515         return 1;
6516       }
6517
6518       const Standard_Integer aDepth = Draw::Atoi (theArgVec[anArgIter]);
6519       if (aDepth < 1 || aDepth > 10)
6520       {
6521         std::cerr << "Error: invalid ray-tracing depth " << aDepth << ". Should be within range [1; 10]\n";
6522         return 1;
6523       }
6524       else
6525       {
6526         aParams.RaytracingDepth = aDepth;
6527       }
6528     }
6529     else if (aFlag == "-shad"
6530           || aFlag == "-shadows")
6531     {
6532       if (toPrint)
6533       {
6534         theDI << (aParams.IsShadowEnabled ? "on" : "off") << " ";
6535         continue;
6536       }
6537
6538       Standard_Boolean toEnable = Standard_True;
6539       if (++anArgIter < theArgNb
6540       && !parseOnOff (theArgVec[anArgIter], toEnable))
6541       {
6542         --anArgIter;
6543       }
6544       aParams.IsShadowEnabled = toEnable;
6545     }
6546     else if (aFlag == "-refl"
6547           || aFlag == "-reflections")
6548     {
6549       if (toPrint)
6550       {
6551         theDI << (aParams.IsReflectionEnabled ? "on" : "off") << " ";
6552         continue;
6553       }
6554
6555       Standard_Boolean toEnable = Standard_True;
6556       if (++anArgIter < theArgNb
6557       && !parseOnOff (theArgVec[anArgIter], toEnable))
6558       {
6559         --anArgIter;
6560       }
6561       aParams.IsReflectionEnabled = toEnable;
6562     }
6563     else if (aFlag == "-fsaa")
6564     {
6565       if (toPrint)
6566       {
6567         theDI << (aParams.IsAntialiasingEnabled ? "on" : "off") << " ";
6568         continue;
6569       }
6570
6571       Standard_Boolean toEnable = Standard_True;
6572       if (++anArgIter < theArgNb
6573       && !parseOnOff (theArgVec[anArgIter], toEnable))
6574       {
6575         --anArgIter;
6576       }
6577       aParams.IsAntialiasingEnabled = toEnable;
6578     }
6579     else if (aFlag == "-gleam")
6580     {
6581       if (toPrint)
6582       {
6583         theDI << (aParams.IsTransparentShadowEnabled ? "on" : "off") << " ";
6584         continue;
6585       }
6586
6587       Standard_Boolean toEnable = Standard_True;
6588       if (++anArgIter < theArgNb
6589       && !parseOnOff (theArgVec[anArgIter], toEnable))
6590       {
6591         --anArgIter;
6592       }
6593       aParams.IsTransparentShadowEnabled = toEnable;
6594     }
6595     else
6596     {
6597       std::cout << "Error: wrong syntax, unknown flag '" << anArg << "'\n";
6598       return 1;
6599     }
6600   }
6601
6602   aView->Redraw();
6603   return 0;
6604 }
6605
6606 //=======================================================================
6607 //function : VFrustumCulling
6608 //purpose  : enables/disables view volume's culling.
6609 //=======================================================================
6610 static int VFrustumCulling (Draw_Interpretor& theDI,
6611                             Standard_Integer  theArgNb,
6612                             const char**      theArgVec)
6613 {
6614   Handle(V3d_View) aView = ViewerTest::CurrentView();
6615   if (aView.IsNull())
6616   {
6617     std::cout << theArgVec[0] << " Error: Use 'vinit' command before\n";
6618     return 1;
6619   }
6620
6621   if (theArgNb < 2)
6622   {
6623     theDI << (aView->IsCullingEnabled() ? "on" : "off");
6624     return 0;
6625   }
6626   else if (theArgNb != 2)
6627   {
6628     std::cout << theArgVec[0] << " Syntax error: Specify the mode\n";
6629     return 1;
6630   }
6631
6632   TCollection_AsciiString aModeStr (theArgVec[1]);
6633   aModeStr.LowerCase();
6634   Standard_Boolean toEnable = 0;
6635   if (aModeStr == "on")
6636   {
6637     toEnable = 1;
6638   }
6639   else if (aModeStr == "off")
6640   {
6641     toEnable = 0;
6642   }
6643   else
6644   {
6645     toEnable = Draw::Atoi (theArgVec[1]) != 0;
6646   }
6647
6648   aView->SetFrustumCulling (toEnable);
6649   aView->Redraw();
6650   return 0;
6651 }
6652
6653 //=======================================================================
6654 //function : ViewerCommands
6655 //purpose  :
6656 //=======================================================================
6657
6658 void ViewerTest::ViewerCommands(Draw_Interpretor& theCommands)
6659 {
6660
6661   const char *group = "ZeViewer";
6662   theCommands.Add("vinit",
6663 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
6664     "[name=view_name] [display=display_name] [l=leftPx t=topPx] [w=widthPx h=heightPx]\n"
6665 #else
6666     "[name=view_name] [l=leftPx t=topPx] [w=widthPx h=heightPx]\n"
6667 #endif
6668     " - Creates new View window with specified name view_name.\n"
6669     "By default the new view is created in the viewer and in"
6670     " graphic driver shared with active view.\n"
6671     " - name = {driverName/viewerName/viewName | viewerName/viewName | viewName}.\n"
6672     "If driverName isn't specified the driver will be shared with active view.\n"
6673     "If viewerName isn't specified the viewer will be shared with active view.\n"
6674 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
6675     " - display = HostName.DisplayNumber[:ScreenNumber] : if specified"
6676     "is used in creation of graphic driver\n"
6677 #endif
6678     " - l, t: pixel position of left top corner of the window\n"
6679     " - w,h: width and heigth of window respectively.\n"
6680     "Additional commands for operations with views: vclose, vactivate, vviewlist.\n",
6681     __FILE__,VInit,group);
6682   theCommands.Add("vclose" ,
6683     "[view_id [keep_context=0|1]]\n"
6684     "or vclose ALL - to remove all created views\n"
6685     " - removes view(viewer window) defined by its view_id.\n"
6686     " - keep_context: by default 0; if 1 and the last view is deleted"
6687     " the current context is not removed.",
6688     __FILE__,VClose,group);
6689   theCommands.Add("vactivate" ,
6690     "view_id"
6691     " - activates view(viewer window) defined by its view_id",
6692     __FILE__,VActivate,group);
6693   theCommands.Add("vviewlist",
6694     "vviewlist [format={tree, long}]"
6695     " - prints current list of views per viewer and graphic_driver ID shared between viewers"
6696     " - format: format of result output, if tree the output is a tree view;"
6697     "otherwise it's a list of full view names. By default format = tree",
6698     __FILE__,VViewList,group);
6699   theCommands.Add("vhelp" ,
6700     "vhelp            : display help on the viewer commands",
6701     __FILE__,VHelp,group);
6702   theCommands.Add("vtop" ,
6703     "vtop or <T>      : Top view" ,
6704     __FILE__,VTop,group);
6705   theCommands.Add("vbottom" ,
6706     "vbottom          : Bottom view" ,
6707     __FILE__,VBottom,group);
6708   theCommands.Add("vleft" ,
6709     "vleft            : Left view" ,
6710     __FILE__,VLeft,group);
6711   theCommands.Add("vright" ,
6712     "vright           : Right view" ,
6713     __FILE__,VRight,group);
6714   theCommands.Add("vaxo" ,
6715     " vaxo or <A>     : Axonometric view ",
6716     __FILE__,VAxo,group);
6717   theCommands.Add("vfront" ,
6718     "vfront           : Front view" ,
6719     __FILE__,VFront,group);
6720   theCommands.Add("vback" ,
6721     "vback            : Back view" ,
6722     __FILE__,VBack,group);
6723   theCommands.Add("vpick" ,
6724     "vpick           : vpick X Y Z [shape subshape] ( all variables as string )",
6725     VPick,group);
6726   theCommands.Add("vfit"    ,
6727     "vfit or <F>         : vfit",
6728     __FILE__,VFit,group);
6729   theCommands.Add ("vzfit", "vzfit [scale]\n"
6730     "   Matches Z near, Z far view volume planes to the displayed objects.\n"
6731     "   \"scale\" - specifies factor to scale computed z range.\n",
6732     __FILE__, VZFit, group);
6733   theCommands.Add("vrepaint",
6734     "vrepaint        : vrepaint, force redraw",
6735     __FILE__,VRepaint,group);
6736   theCommands.Add("vclear",
6737     "vclear          : vclear",
6738     __FILE__,VClear,group);
6739   theCommands.Add("vsetbg",
6740     "vsetbg          : vsetbg imagefile [filltype] : Load image as background",
6741     __FILE__,VSetBg,group);
6742   theCommands.Add("vsetbgmode",
6743     "vsetbgmode      : vsetbgmode filltype : Change background image fill type",
6744     __FILE__,VSetBgMode,group);
6745   theCommands.Add("vsetgradientbg",
6746     "vsetgradientbg  : vsetgradientbg r1 g1 b1 r2 g2 b2 filltype : Mount gradient background",
6747     __FILE__,VSetGradientBg,group);
6748   theCommands.Add("vsetgrbgmode",
6749     "vsetgrbgmode    : vsetgrbgmode filltype : Change gradient background fill type",
6750     __FILE__,VSetGradientBgMode,group);
6751   theCommands.Add("vsetcolorbg",
6752     "vsetcolorbg     : vsetcolorbg r g b : Set background color",
6753     __FILE__,VSetColorBg,group);
6754   theCommands.Add("vscale",
6755     "vscale          : vscale X Y Z",
6756     __FILE__,VScale,group);
6757   theCommands.Add("vzbufftrihedron",
6758     "vzbufftrihedron [center|left_lower|left_upper|right_lower|right_upper"
6759     " textR=255 textG=255 textB=255 scale=0.1 wireframe|zbuffer]"
6760     " : Displays a V3d_ZBUFFER'ed or V3d_WIREFRAME'd trihedron",
6761     __FILE__,VTestZBuffTrihedron,group);
6762   theCommands.Add("vrotate",
6763     "vrotate         : vrotate AX AY AZ [X Y Z]",
6764     __FILE__,VRotate,group);
6765   theCommands.Add("vzoom",
6766     "vzoom           : vzoom coef",
6767     __FILE__,VZoom,group);
6768   theCommands.Add("vpan",
6769     "vpan            : vpan dx dy",
6770     __FILE__,VPan,group);
6771   theCommands.Add("vexport",
6772     "vexport         : vexport full_file_path {PS | EPS | TEX | PDF | SVG | PGF | EMF }"
6773     " : exports the view to a vector file of a given format"
6774     " : notice that EMF format requires patched gl2ps",
6775     __FILE__,VExport,group);
6776   theCommands.Add("vcolorscale",
6777     "vcolorscale     : vcolorscale [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = 2 X = 0 Y = 0]: draw color scale",
6778     __FILE__,VColorScale,group);
6779   theCommands.Add("vgraduatedtrihedron",
6780     "vgraduatedtrihedron : 1/0 (display/erase) [Xname Yname Zname [Font [isMultibyte]]]",
6781     __FILE__,VGraduatedTrihedron,group);
6782   theCommands.Add("vprintview" ,
6783     "vprintview : width height filename [algo=0] [tile_width tile_height] : Test print algorithm: algo = 0 - stretch, algo = 1 - tile",
6784     __FILE__,VPrintView,group);
6785   theCommands.Add("vzlayer",
6786     "vzlayer add/del/get/settings/enable/disable [id]\n"
6787     " add - add new z layer to viewer and print its id\n"
6788     " del - del z layer by its id\n"
6789     " get - print sequence of z layers in increasing order of their overlay level\n"
6790     " settings - print status of z layer settings\n"
6791     " enable ([depth]test/[depth]write/[depth]clear/[depth]offset) \n    enables given setting for the z layer\n"
6792     " enable (p[ositive]offset/n[egative]offset) \n    enables given setting for the z layer\n"
6793     " disable ([depth]test/[depth]write/[depth]clear/[depth]offset) \n    disables given setting for the z layer\n"
6794     "\nWhere id is the layer identificator\n"
6795     "\nExamples:\n"
6796     "   vzlayer add\n"
6797     "   vzlayer enable poffset 1\n"
6798     "   vzlayer disable depthtest 1\n"
6799     "   vzlayer del 1\n",
6800     __FILE__,VZLayer,group);
6801   theCommands.Add("voverlaytext",
6802     "voverlaytext : text x y [height] [font_name] [text_color: R G B] [display_type] [background_color: R G B]"
6803     " : height - pixel height of the text (default=10.0)"
6804     " : font_name - name of font (default=courier)"
6805     " : text_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0) "
6806     " : display_type = {normal/subtitle/decal/blend}, (default=normal) "
6807     " : background_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0), the parameter is defined for subtitle and decal display types ",
6808     __FILE__,VOverlayText,group);
6809   theCommands.Add("vlayerline",
6810     "vlayerline : vlayerline x1 y1 x2 y2 [linewidth=0.5] [linetype=0] [transparency=1.0]",
6811     __FILE__,VLayerLine,group);
6812   theCommands.Add ("vgrid",
6813     "vgrid [off] [Mode={r|c}] [Type={l|p}] [OriginX OriginY [StepX/StepRadius StepY/DivNb RotAngle]]"
6814     " : Mode - rectangular or circular"
6815     " : Type - lines or points",
6816     __FILE__, VGrid, group);
6817   theCommands.Add ("vfps",
6818     "vfps [framesNb=100] : estimate average frame rate for active view",
6819     __FILE__, VFps, group);
6820   theCommands.Add ("vgldebug",
6821     "vgldebug [{0|1}] : request debug GL context, should be called before vinit\n"
6822     "                : this function is implemented only for Windows\n"
6823     "                : GL_ARB_debug_output extension should be exported by OpenGL driver!",
6824     __FILE__, VGlDebug, group);
6825   theCommands.Add ("vvbo",
6826     "vvbo [{0|1}] : turn VBO usage On/Off; affects only newly displayed objects",
6827     __FILE__, VVbo, group);
6828   theCommands.Add ("vstereo",
6829     "\nvstereo [{0|1}] : turn stereo usage On/Off; affects only newly displayed objects",
6830     __FILE__, VStereo, group);
6831   theCommands.Add ("vcaps",
6832     "vcaps [vbo={0|1}] [sprites={0|1}] [soft={0|1}] : modify particular graphic driver options",
6833     __FILE__, VCaps, group);
6834   theCommands.Add ("vmemgpu",
6835     "vmemgpu [f]: print system-dependent GPU memory information if available;"
6836     " with f option returns free memory in bytes",
6837     __FILE__, VMemGpu, group);
6838   theCommands.Add ("vreadpixel",
6839     "vreadpixel xPixel yPixel [{rgb|rgba|depth|hls|rgbf|rgbaf}=rgba] [name]"
6840     " : Read pixel value for active view",
6841     __FILE__, VReadPixel, group);
6842   theCommands.Add("diffimage",
6843     "diffimage     : diffimage imageFile1 imageFile2 toleranceOfColor(0..1) blackWhite(1|0) borderFilter(1|0) [diffImageFile]",
6844     __FILE__, VDiffImage, group);
6845   theCommands.Add ("vselect",
6846     "vselect x1 y1 [x2 y2 [x3 y3 ... xn yn]] [shift_selection = 0|1]\n"
6847     "- emulates different types of selection:\n"
6848     "- 1) single click selection\n"
6849     "- 2) selection with rectangle having corners at pixel positions (x1,y1) and (x2,y2)\n"
6850     "- 3) selection with polygon having corners in pixel positions (x1,y1), (x2,y2),...,(xn,yn)\n"
6851     "- 4) any of these selections with shift button pressed",
6852     __FILE__, VSelect, group);
6853   theCommands.Add ("vmoveto",
6854     "vmoveto x y"
6855     "- emulates cursor movement to pixel postion (x,y)",
6856     __FILE__, VMoveTo, group);
6857   theCommands.Add ("vviewparams", "vviewparams usage:\n"
6858     "- vviewparams\n"
6859     "- vviewparams [-scale [s]] [-eye [x y z]] [-at [x y z]] [-up [x y z]]\n"
6860     "              [-proj [x y z]] [-center x y] [-size sx]\n"
6861     "-   Gets or sets current view parameters.\n"
6862     "-   If called without arguments, all view parameters are printed.\n"
6863     "-   The options are:\n"
6864     "      -scale [s]    : prints or sets viewport relative scale.\n"
6865     "      -eye [x y z]  : prints or sets eye location.\n"
6866     "      -at [x y z]   : prints or sets center of look.\n"
6867     "      -up [x y z]   : prints or sets direction of up vector.\n"
6868     "      -proj [x y z] : prints or sets direction of look.\n"
6869     "      -center x y   : sets location of center of the screen in pixels.\n"
6870     "      -size [sx]    : prints viewport projection width and height sizes\n"
6871     "                    : or changes the size of its maximum dimension.\n",
6872     __FILE__, VViewParams, group);
6873   theCommands.Add("vchangeselected",
6874     "vchangeselected shape"
6875     "- adds to shape to selection or remove one from it",
6876                 __FILE__, VChangeSelected, group);
6877   theCommands.Add("vzclipping",
6878     "vzclipping [mode] [depth width]\n"
6879     "- mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]\n"
6880     "- gets or sets ZClipping mode, width and depth",
6881     __FILE__,VZClipping,group);
6882   theCommands.Add ("vnbselected",
6883     "vnbselected", __FILE__, VNbSelected, group);
6884   theCommands.Add ("vchangecamera",
6885     " changes camera parameters \n"
6886     "- vchangecamera [param_type] [value]\n"
6887     "- vchangecamera proj {ortho/persp/left/right/stereo}\n"
6888     "     Projection type including left and right stereo parts.\n"
6889     "- vchangecamera dist [real]\n"
6890     "     Sets distance from target point to camera eye (moving eye).\n"
6891     "- vchangecamera iod [real]\n"
6892     "     Intraocular distance value.\n"
6893     "- vchangecamera zfocus [real]\n"
6894     "     Stereographic focus value.\n"
6895     "- vchangecamera fov [real]\n"
6896     "     Field Of View value (in degrees).\n"
6897     "- vchangecamera zfocustype {absolute/relative}\n"
6898     "     Stereographic focus definition type (absolute value or coefficient).\n"
6899     "- vchangecamera iodtype {absolute/relative}\n"
6900     "     Intraocular distance definition type (absolute value or coefficient).\n", 
6901     __FILE__, VChangeCamera, group);
6902   theCommands.Add ("vautozfit", "command to enable or disable automatic z-range adjusting\n"
6903     "- vautozfit [on={1|0}] [scale]\n"
6904     "    Prints or changes parameters of automatic z-fit mode:\n"
6905     "   \"on\" - turns automatic z-fit on or off\n"
6906     "   \"scale\" - specifies factor to scale computed z range.\n",
6907     __FILE__, VAutoZFit, group);
6908   theCommands.Add ("vzrange", "command to manually access znear and zfar values\n"
6909     "   vzrange                - without parameters shows current values\n"
6910     "   vzrange [znear] [zfar] - applies provided values to view",
6911     __FILE__,VZRange, group);
6912   theCommands.Add("vantialiasing",
6913     "vantialiasing 1|0",
6914     __FILE__,VAntialiasing,group);
6915   theCommands.Add ("vpurgedisplay",
6916     "vpurgedisplay"
6917     "- removes structures which don't belong to objects displayed in neutral point",
6918     __FILE__, VPurgeDisplay, group);
6919   theCommands.Add("vsetviewsize",
6920     "vsetviewsize size",
6921     __FILE__,VSetViewSize,group);
6922   theCommands.Add("vmoveview",
6923     "vmoveview Dx Dy Dz [Start = 1|0]",
6924     __FILE__,VMoveView,group);
6925   theCommands.Add("vtranslateview",
6926     "vtranslateview Dx Dy Dz [Start = 1|0)]",
6927     __FILE__,VTranslateView,group);
6928   theCommands.Add("vturnview",
6929     "vturnview Ax Ay Az [Start = 1|0]",
6930     __FILE__,VTurnView,group);
6931   theCommands.Add("vtextureenv",
6932     "Enables or disables environment mapping in the 3D view, loading the texture from the given standard "
6933     "or user-defined file and optionally applying texture mapping parameters\n"
6934     "                  Usage:\n"
6935     "                  vtextureenv off - disables environment mapping\n"
6936     "                  vtextureenv on {std_texture|texture_file_name} [rep mod flt ss st ts tt rot] - enables environment mapping\n"
6937     "                              std_texture = (0..7)\n"
6938     "                              rep         = {clamp|repeat}\n"
6939     "                              mod         = {decal|modulate}\n"
6940     "                              flt         = {nearest|bilinear|trilinear}\n"
6941     "                              ss, st      - scale factors for s and t texture coordinates\n"
6942     "                              ts, tt      - translation for s and t texture coordinates\n"
6943     "                              rot         - texture rotation angle in degrees",
6944     __FILE__, VTextureEnv, group);
6945   theCommands.Add("vhlr" ,
6946     "is_enabled={on|off} [show_hidden={1|0}]"
6947     " - Hidden line removal algorithm:"
6948     " - is_enabled: if is on HLR algorithm is applied\n"
6949     " - show_hidden: if equals to 1, hidden lines are drawn as dotted ones.\n",
6950     __FILE__,VHLR,group);
6951   theCommands.Add("vhlrtype" ,
6952     "algo_type={algo|polyalgo} [shape_1 ... shape_n]"
6953     " - Changes the type of HLR algorithm using for shapes."
6954     " - algo_type: if equals to algo, exact HLR algorithm is applied;\n"
6955     "   if equals to polyalgo, polygonal HLR algorithm is applied."
6956     "If shapes are not given HLR algoithm of given type is applied"
6957     " to all shapes in the view\n",
6958     __FILE__,VHLRType,group);
6959   theCommands.Add("vclipplane", "vclipplane usage: \n"
6960     "  maxplanes <view_name> - get plane limit for view.\n"
6961     "  create <plane_name> - create new plane.\n"
6962     "  delete <plane_name> - delete plane.\n"
6963     "  clone <source_plane> <plane_name> - clone the plane definition.\n"
6964     "  set/unset <plane_name> object <object list> - set/unset plane for IO.\n"
6965     "  set/unset <plane_name> view <view list> - set/unset plane for view.\n"
6966     "  change <plane_name> on/off - turn clipping on/off.\n"
6967     "  change <plane_name> equation <a> <b> <c> <d> - change plane equation.\n"
6968     "  change <plane_name> capping on/off - turn capping on/off.\n"
6969     "  change <plane_name> capping color <r> <g> <b> - set color.\n"
6970     "  change <plane name> capping texname <texture> - set texture.\n"
6971     "  change <plane_name> capping texscale <sx> <sy> - set tex scale.\n"
6972     "  change <plane_name> capping texorigin <tx> <ty> - set tex origin.\n"
6973     "  change <plane_name> capping texrotate <angle> - set tex rotation.\n"
6974     "  change <plane_name> capping hatch on/off/<id> - set hatching mask.\n"
6975     "  please use VSetTextureMode command to enable texture rendering in view.\n"
6976     , __FILE__, VClipPlane, group);
6977   theCommands.Add("vsettexturemode", "vsettexturemode view_name mode \n"
6978     "  mode can be:\n"
6979     "  0 - no textures enabled in view.\n"
6980     "  1 - only environment textures enabled.\n"
6981     "  2 - all textures enabled.\n"
6982     "  this command sets texture details mode for the specified view.\n"
6983     , __FILE__, VSetTextureMode, group);
6984   theCommands.Add("vdefaults",
6985     "vdefaults [absDefl=value] [devCoeff=value] [angDefl=value]",
6986     __FILE__, VDefaults, group);
6987   theCommands.Add("vlight",
6988     "tool to manage light sources, without arguments shows list of lights."
6989     "\n    Main commands: "
6990     "\n      'clear' to clear lights"
6991     "\n      '{def}aults' to load deafault lights"
6992     "\n      'add' (or 'new') <type> to add any light source"
6993     "\n          where <type> is one of {amb}ient|directional|{spot}light|positional"
6994     "\n      'change' <lightId> to edit light source with specified lightId"
6995     "\n\n      In addition to 'add' and 'change' commands you can use light parameters:"
6996     "\n        {pos}ition X Y Z"
6997     "\n        {dir}ection X Y Z (for directional light or for spotlight)"
6998     "\n        color colorName"
6999     "\n        {head}light 0|1"
7000     "\n        {constAtten}uation value"
7001     "\n        {linearAtten}uation value"
7002     "\n        angle angleDeg"
7003     "\n        {spotexp}onent value"
7004     "\n        local|global"
7005     "\n\n        example: vlight add positional head 1 pos 0 1 1 color red"
7006     "\n        example: vlight change 0 direction 0 -1 0 linearAttenuation 0.2",
7007     __FILE__, VLight, group);
7008   theCommands.Add("vrenderparams",
7009     "\n    Manages rendering parameters: "
7010     "\n      '-rayTrace'            Enables  GPU ray-tracing"
7011     "\n      '-raster'              Disables GPU ray-tracing"
7012     "\n      '-rayDepth    0..10'   Defines maximum ray-tracing depth"
7013     "\n      '-shadows     on|off'  Enables/disables shadows rendering"
7014     "\n      '-reflections on|off'  Enables/disables specular reflections"
7015     "\n      '-fsaa        on|off'  Enables/disables adaptive anti-aliasing"
7016     "\n      '-gleam       on|off'  Enables/disables transparency shadow effects",
7017     __FILE__, VRenderParams, group);
7018   theCommands.Add("vfrustumculling",
7019     "vfrustumculling [toEnable]: enables/disables objects clipping",
7020     __FILE__,VFrustumCulling,group);
7021 }