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