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