source: trunk/source/visualization/OpenGL/src/G4OpenGLViewer.cc @ 1340

Last change on this file since 1340 was 1340, checked in by garnier, 14 years ago

update ti head

  • Property svn:mime-type set to text/cpp
File size: 27.0 KB
Line 
1//
2// ********************************************************************
3// * License and Disclaimer                                           *
4// *                                                                  *
5// * The  Geant4 software  is  copyright of the Copyright Holders  of *
6// * the Geant4 Collaboration.  It is provided  under  the terms  and *
7// * conditions of the Geant4 Software License,  included in the file *
8// * LICENSE and available at  http://cern.ch/geant4/license .  These *
9// * include a list of copyright holders.                             *
10// *                                                                  *
11// * Neither the authors of this software system, nor their employing *
12// * institutes,nor the agencies providing financial support for this *
13// * work  make  any representation or  warranty, express or implied, *
14// * regarding  this  software system or assume any liability for its *
15// * use.  Please see the license in the file  LICENSE  and URL above *
16// * for the full disclaimer and the limitation of liability.         *
17// *                                                                  *
18// * This  code  implementation is the result of  the  scientific and *
19// * technical work of the GEANT4 collaboration.                      *
20// * By using,  copying,  modifying or  distributing the software (or *
21// * any work based  on the software)  you  agree  to acknowledge its *
22// * use  in  resulting  scientific  publications,  and indicate your *
23// * acceptance of all terms of the Geant4 Software license.          *
24// ********************************************************************
25//
26//
27// $Id: G4OpenGLViewer.cc,v 1.63 2010/10/05 15:45:19 lgarnier Exp $
28// GEANT4 tag $Name:  $
29//
30//
31// Andrew Walkden  27th March 1996
32// OpenGL view - opens window, hard copy, etc.
33
34#ifdef G4VIS_BUILD_OPENGL_DRIVER
35
36#include "G4ios.hh"
37#include "G4OpenGLViewer.hh"
38#include "G4OpenGLSceneHandler.hh"
39#include "G4OpenGLTransform3D.hh"
40#include "G4OpenGL2PSAction.hh"
41
42#include "G4Scene.hh"
43#include "G4VisExtent.hh"
44#include "G4LogicalVolume.hh"
45#include "G4VSolid.hh"
46#include "G4Point3D.hh"
47#include "G4Normal3D.hh"
48#include "G4Plane3D.hh"
49#include "G4AttHolder.hh"
50#include "G4AttCheck.hh"
51
52// GL2PS
53#include "Geant4_gl2ps.h"
54
55#include <sstream>
56
57G4OpenGLViewer::G4OpenGLViewer (G4OpenGLSceneHandler& scene):
58G4VViewer (scene, -1),
59fPrintColour (true),
60fVectoredPs (true),
61fOpenGLSceneHandler(scene),
62background (G4Colour(0.,0.,0.)),
63transparency_enabled (true),
64antialiasing_enabled (false),
65haloing_enabled (false),
66fStartTime(-DBL_MAX),
67fEndTime(DBL_MAX),
68fFadeFactor(0.),
69fDisplayHeadTime(false),
70fDisplayHeadTimeX(-0.9),
71fDisplayHeadTimeY(-0.9),
72fDisplayHeadTimeSize(24.),
73fDisplayHeadTimeRed(0.),
74fDisplayHeadTimeGreen(1.),
75fDisplayHeadTimeBlue(1.),
76fDisplayLightFront(false),
77fDisplayLightFrontX(0.),
78fDisplayLightFrontY(0.),
79fDisplayLightFrontZ(0.),
80fDisplayLightFrontT(0.),
81fDisplayLightFrontRed(0.),
82fDisplayLightFrontGreen(1.),
83fDisplayLightFrontBlue(0.),
84fPrintSizeX(-1),
85fPrintSizeY(-1),
86fPrintFilename ("G4OpenGL"),
87fPrintFilenameIndex(0),
88fPointSize (0),
89fSizeHasChanged(0)
90{
91  // Make changes to view parameters for OpenGL...
92  fVP.SetAutoRefresh(true);
93  fDefaultVP.SetAutoRefresh(true);
94
95  fGL2PSAction = new G4OpenGL2PSAction();
96
97  //  glClearColor (0.0, 0.0, 0.0, 0.0);
98  //  glClearDepth (1.0);
99  //  glDisable (GL_BLEND);
100  //  glDisable (GL_LINE_SMOOTH);
101  //  glDisable (GL_POLYGON_SMOOTH);
102
103}
104
105G4OpenGLViewer::~G4OpenGLViewer () {}
106
107void G4OpenGLViewer::InitializeGLView ()
108{
109  glClearColor (0.0, 0.0, 0.0, 0.0);
110  glClearDepth (1.0);
111  glDisable (GL_BLEND);
112  glDisable (GL_LINE_SMOOTH);
113  glDisable (GL_POLYGON_SMOOTH);
114
115  fWinSize_x = fVP.GetWindowSizeHintX();
116  fWinSize_y = fVP.GetWindowSizeHintY();
117
118
119void G4OpenGLViewer::ClearView () {
120#ifdef G4DEBUG_VIS_OGL
121  printf("G4OpenGLViewer::ClearView\n");
122#endif
123  glClearColor (background.GetRed(),
124                background.GetGreen(),
125                background.GetBlue(),
126                1.);
127  glClearDepth (1.0);
128  //Below line does not compile with Mesa includes.
129  //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
130  glClear (GL_COLOR_BUFFER_BIT);
131  glClear (GL_DEPTH_BUFFER_BIT);
132  glClear (GL_STENCIL_BUFFER_BIT);
133#ifdef G4DEBUG_VIS_OGL
134  printf("G4OpenGLViewer::ClearView flush\n");
135#endif
136  glFlush ();
137}
138
139
140void G4OpenGLViewer::ResizeWindow(unsigned int aWidth, unsigned int aHeight) {
141  if ((fWinSize_x != aWidth) || (fWinSize_y != aHeight)) {
142    fWinSize_x = aWidth;
143    fWinSize_y = aHeight;
144    fSizeHasChanged = true;
145  } else {
146    fSizeHasChanged = false;
147  }
148}
149
150/**
151 * Set the viewport of the scene
152 * MAXIMUM SIZE is :
153 * GLint dims[2];
154 * glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
155 */
156void G4OpenGLViewer::ResizeGLView()
157{
158#ifdef G4DEBUG_VIS_OGL
159  printf("G4OpenGLViewer::ResizeGLView %d %d &:%d\n",fWinSize_x,fWinSize_y,this);
160#endif
161  // Check size
162  GLint dims[2];
163  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
164
165  if ((dims[0] !=0 ) && (dims[1] !=0)) {
166
167    if (fWinSize_x > (unsigned)dims[0]) {
168      G4cerr << "Try to resize view greater than max X viewport dimension. Desired size "<<dims[0] <<" is resize to "<<  dims[0] << G4endl;
169      fWinSize_x = dims[0];
170    }
171    if (fWinSize_y > (unsigned)dims[1]) {
172      G4cerr << "Try to resize view greater than max Y viewport dimension. Desired size "<<dims[0] <<" is resize to "<<  dims[1] << G4endl;
173      fWinSize_y = dims[1];
174    }
175  }
176   
177#ifdef G4DEBUG_VIS_OGL
178  printf("G4OpenGLViewer::ResizeGLView viewport X:%d Y:%d\n",fWinSize_x,fWinSize_y);
179#endif
180  glViewport(0, 0, fWinSize_x,fWinSize_y);   
181
182
183}
184
185
186void G4OpenGLViewer::SetView () {
187
188  if (!fSceneHandler.GetScene()) {
189    return;
190  }
191  // Calculates view representation based on extent of object being
192  // viewed and (initial) viewpoint.  (Note: it can change later due
193  // to user interaction via visualization system's GUI.)
194 
195  // Lighting.
196  GLfloat lightPosition [4];
197  lightPosition [0] = fVP.GetActualLightpointDirection().x();
198  lightPosition [1] = fVP.GetActualLightpointDirection().y();
199  lightPosition [2] = fVP.GetActualLightpointDirection().z();
200  lightPosition [3] = 0.;
201  // Light position is "true" light direction, so must come after gluLookAt.
202  GLfloat ambient [] = { 0.2, 0.2, 0.2, 1.};
203  GLfloat diffuse [] = { 0.8, 0.8, 0.8, 1.};
204  glEnable (GL_LIGHT0);
205  glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);
206  glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);
207 
208  G4double ratioX = 1;
209  G4double ratioY = 1;
210  if (fWinSize_y > fWinSize_x) {
211    ratioX = ((G4double)fWinSize_y) / ((G4double)fWinSize_x);
212  }
213  if (fWinSize_x > fWinSize_y) {
214    ratioY = ((G4double)fWinSize_x) / ((G4double)fWinSize_y);
215  }
216 
217  // Get radius of scene, etc.
218  // Note that this procedure properly takes into account zoom, dolly and pan.
219  const G4Point3D targetPoint
220    = fSceneHandler.GetScene()->GetStandardTargetPoint()
221    + fVP.GetCurrentTargetPoint ();
222  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
223  if(radius<=0.) radius = 1.;
224  const G4double cameraDistance = fVP.GetCameraDistance (radius);
225  const G4Point3D cameraPosition =
226    targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
227  const GLdouble pnear  = fVP.GetNearDistance (cameraDistance, radius);
228  const GLdouble pfar   = fVP.GetFarDistance  (cameraDistance, pnear, radius);
229  const GLdouble right  = fVP.GetFrontHalfHeight (pnear, radius) * ratioY;
230  const GLdouble left   = -right;
231  const GLdouble top    = fVP.GetFrontHalfHeight (pnear, radius) * ratioX;
232  const GLdouble bottom = -top;
233 
234  // FIXME
235  ResizeGLView();
236  //SHOULD SetWindowsSizeHint()...
237
238  glMatrixMode (GL_PROJECTION); // set up Frustum.
239  glLoadIdentity();
240
241  const G4Vector3D scaleFactor = fVP.GetScaleFactor();
242  glScaled(scaleFactor.x(),scaleFactor.y(),scaleFactor.z());
243 
244  if (fVP.GetFieldHalfAngle() == 0.) {
245    glOrtho (left, right, bottom, top, pnear, pfar);
246  }
247  else {
248    glFrustum (left, right, bottom, top, pnear, pfar);
249  } 
250
251  glMatrixMode (GL_MODELVIEW); // apply further transformations to scene.
252  glLoadIdentity();
253 
254  const G4Normal3D& upVector = fVP.GetUpVector (); 
255  G4Point3D gltarget;
256  if (cameraDistance > 1.e-6 * radius) {
257    gltarget = targetPoint;
258  }
259  else {
260    gltarget = targetPoint - radius * fVP.GetViewpointDirection().unit();
261  }
262
263  const G4Point3D& pCamera = cameraPosition;  // An alias for brevity.
264  gluLookAt (pCamera.x(),  pCamera.y(),  pCamera.z(),       // Viewpoint.
265             gltarget.x(), gltarget.y(), gltarget.z(),      // Target point.
266             upVector.x(), upVector.y(), upVector.z());     // Up vector.
267
268  // Light position is "true" light direction, so must come after gluLookAt.
269  glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
270
271  // OpenGL no longer seems to reconstruct clipped edges, so, when the
272  // BooleanProcessor is up to it, abandon this and use generic
273  // clipping in G4OpenGLSceneHandler::CreateSectionPolyhedron.  Also,
274  // force kernel visit on change of clipping plane in
275  // G4OpenGLStoredViewer::CompareForKernelVisit.
276  //if (fVP.IsSection () ) {  // pair of back to back clip planes.
277  if (false) {  // pair of back to back clip planes.
278    const G4Plane3D& s = fVP.GetSectionPlane ();
279    double sArray[4];
280    sArray[0] = s.a();
281    sArray[1] = s.b();
282    sArray[2] = s.c();
283    sArray[3] = s.d() + radius * 1.e-05;
284    glClipPlane (GL_CLIP_PLANE0, sArray);
285    glEnable (GL_CLIP_PLANE0);
286    sArray[0] = -s.a();
287    sArray[1] = -s.b();
288    sArray[2] = -s.c();
289    sArray[3] = -s.d() + radius * 1.e-05;
290    glClipPlane (GL_CLIP_PLANE1, sArray);
291    glEnable (GL_CLIP_PLANE1);
292  } else {
293    glDisable (GL_CLIP_PLANE0);
294    glDisable (GL_CLIP_PLANE1);
295  }
296
297  const G4Planes& cutaways = fVP.GetCutawayPlanes();
298  size_t nPlanes = cutaways.size();
299  //if (fVP.IsCutaway() &&
300  if (false &&
301      fVP.GetCutawayMode() == G4ViewParameters::cutawayIntersection &&
302      nPlanes > 0) {
303    double a[4];
304    a[0] = cutaways[0].a();
305    a[1] = cutaways[0].b();
306    a[2] = cutaways[0].c();
307    a[3] = cutaways[0].d();
308    glClipPlane (GL_CLIP_PLANE2, a);
309    glEnable (GL_CLIP_PLANE2);
310    if (nPlanes > 1) {
311      a[0] = cutaways[1].a();
312      a[1] = cutaways[1].b();
313      a[2] = cutaways[1].c();
314      a[3] = cutaways[1].d();
315      glClipPlane (GL_CLIP_PLANE3, a);
316      glEnable (GL_CLIP_PLANE3);
317    }
318    if (nPlanes > 2) {
319      a[0] = cutaways[2].a();
320      a[1] = cutaways[2].b();
321      a[2] = cutaways[2].c();
322      a[3] = cutaways[2].d();
323      glClipPlane (GL_CLIP_PLANE4, a);
324      glEnable (GL_CLIP_PLANE4);
325    }
326  } else {
327    glDisable (GL_CLIP_PLANE2);
328    glDisable (GL_CLIP_PLANE3);
329    glDisable (GL_CLIP_PLANE4);
330  }
331
332  // Background.
333  background = fVP.GetBackgroundColour ();
334
335}
336
337void G4OpenGLViewer::HaloingFirstPass () {
338 
339  //To perform haloing, first Draw all information to the depth buffer
340  //alone, using a chunky line width, and then Draw all info again, to
341  //the colour buffer, setting a thinner line width an the depth testing
342  //function to less than or equal, so if two lines cross, the one
343  //passing behind the other will not pass the depth test, and so not
344  //get rendered either side of the infront line for a short distance.
345
346  //First, disable writing to the colo(u)r buffer...
347  glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
348
349  //Now enable writing to the depth buffer...
350  glDepthMask (GL_TRUE);
351  glDepthFunc (GL_LESS);
352  glClearDepth (1.0);
353
354  //Finally, set the line width to something wide...
355  glLineWidth (3.0);
356
357}
358
359void G4OpenGLViewer::HaloingSecondPass () {
360
361  //And finally, turn the colour buffer back on with a sesible line width...
362  glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
363  glDepthFunc (GL_LEQUAL);
364  glLineWidth (1.0);
365
366}
367
368void G4OpenGLViewer::Pick(GLdouble x, GLdouble y)
369{
370  //G4cout << "X: " << x << ", Y: " << y << G4endl;
371  const G4int BUFSIZE = 512;
372  GLuint selectBuffer[BUFSIZE];
373  glSelectBuffer(BUFSIZE, selectBuffer);
374  glRenderMode(GL_SELECT);
375  glInitNames();
376  glPushName(0);
377  glMatrixMode(GL_PROJECTION);
378  G4double currentProjectionMatrix[16];
379  glGetDoublev(GL_PROJECTION_MATRIX, currentProjectionMatrix);
380  glPushMatrix();
381  glLoadIdentity();
382  GLint viewport[4];
383  glGetIntegerv(GL_VIEWPORT, viewport);
384  // Define 5x5 pixel pick area
385  gluPickMatrix(x, viewport[3] - y, 5., 5., viewport);
386  glMultMatrixd(currentProjectionMatrix);
387  glMatrixMode(GL_MODELVIEW);
388  DrawView();
389  GLint hits = glRenderMode(GL_RENDER);
390  if (hits < 0)
391    G4cout << "Too many hits.  Zoom in to reduce overlaps." << G4endl;
392  else if (hits > 0) {
393    //G4cout << hits << " hit(s)" << G4endl;
394    GLuint* p = selectBuffer;
395    for (GLint i = 0; i < hits; ++i) {
396      GLuint nnames = *p++;
397      p++; //OR GLuint zmin = *p++;
398      p++; //OR GLuint zmax = *p++;
399      //G4cout << "Hit " << i << ": " << nnames << " names"
400      //     << "\nzmin: " << zmin << ", zmax: " << zmax << G4endl;
401      for (GLuint j = 0; j < nnames; ++j) {
402        GLuint name = *p++;
403        //G4cout << "Name " << j << ": PickName: " << name << G4endl;
404        std::map<GLuint, G4AttHolder*>::iterator iter =
405          fOpenGLSceneHandler.fPickMap.find(name);
406        if (iter != fOpenGLSceneHandler.fPickMap.end()) {
407          G4AttHolder* attHolder = iter->second;
408          if(attHolder && attHolder->GetAttDefs().size()) {
409            for (size_t i = 0; i < attHolder->GetAttDefs().size(); ++i) {
410              G4cout << G4AttCheck(attHolder->GetAttValues()[i],
411                                   attHolder->GetAttDefs()[i]);
412            }
413          }
414        }
415      }
416      G4cout << G4endl;
417    }
418  }
419  glMatrixMode(GL_PROJECTION);
420  glPopMatrix();
421  glMatrixMode(GL_MODELVIEW);
422}
423
424
425
426
427GLubyte* G4OpenGLViewer::grabPixels (int inColor, unsigned int width, unsigned int height) {
428 
429  GLubyte* buffer;
430  GLint swapbytes, lsbfirst, rowlength;
431  GLint skiprows, skippixels, alignment;
432  GLenum format;
433  int size;
434
435  if (inColor) {
436    format = GL_RGB;
437    size = width*height*3;
438  } else {
439    format = GL_LUMINANCE;
440    size = width*height*1;
441  }
442
443  buffer = new GLubyte[size];
444  if (buffer == NULL)
445    return NULL;
446
447  glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
448  glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
449  glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
450
451  glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
452  glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
453  glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
454
455#ifdef G4DEBUG_VIS_OGL
456  printf("G4OpenGLViewer::grabPixels colors:%d swap:%d lsb:%d rowlenght:%d sr:%d sp:%d align:%d\n",inColor,swapbytes, lsbfirst, rowlength,skiprows, skippixels, alignment);
457#endif
458
459
460  glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
461  glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
462  glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
463
464  glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
465  glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
466  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
467
468  glFlush();
469  glReadBuffer(GL_FRONT);
470  glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, format, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
471  //  glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
472  glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
473  glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
474  glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
475 
476  glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
477  glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
478  glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
479 
480  return buffer;
481}
482
483void G4OpenGLViewer::printEPS() {
484  bool res;
485#ifdef G4DEBUG_VIS_OGL
486  printf("G4OpenGLViewer::printEPS file:%s Vec:%d Name:%s\n",getRealPrintFilename().c_str(),fVectoredPs,GetName().c_str());
487#endif
488
489  // Change the LC_NUMERIC value in order to have "." separtor and not ","
490  // This case is only useful for French, Canadien...
491  char* oldLocale = (char*)(malloc(strlen(setlocale(LC_NUMERIC,NULL))+1));
492  if(oldLocale!=NULL) strcpy(oldLocale,setlocale(LC_NUMERIC,NULL));
493  setlocale(LC_NUMERIC,"C");
494
495  if (fVectoredPs) {
496    res = printVectoredEPS();
497  } else {
498    res = printNonVectoredEPS();
499  }
500
501  // restore the local
502  if (oldLocale) {
503    setlocale(LC_NUMERIC,oldLocale);
504    free(oldLocale);
505  }
506
507  if (res == false) {
508    G4cerr << "Error while saving file... "<<getRealPrintFilename().c_str()<< G4endl;
509  } else {
510    G4cout << "File "<<getRealPrintFilename().c_str()<<" has been saved " << G4endl;
511  }
512
513  // increment index if necessary
514  if ( fPrintFilenameIndex != -1) {
515    fPrintFilenameIndex++;
516  }
517
518#ifdef G4DEBUG_VIS_OGL
519  printf("G4OpenGLViewer::printEPS END\n");
520#endif
521}
522
523bool G4OpenGLViewer::printVectoredEPS() {
524  return printGl2PS();
525}
526
527bool G4OpenGLViewer::printNonVectoredEPS () {
528
529  GLint viewport[4];
530  glGetIntegerv(GL_VIEWPORT, viewport);
531
532  int width2 = getRealPrintSizeX();
533  int height2 = getRealPrintSizeY();
534  int width = viewport[2]; // FIXME : Why -1 ????
535  int height = viewport[3];
536
537#ifdef G4DEBUG_VIS_OGL
538  printf("G4OpenGLViewer::printNonVectoredEPS file:%s Vec:%d X:%d Y:%d X2:%d Y2:%d col:%d fWinX:%d fWinY:%d\n",getRealPrintFilename().c_str(),fVectoredPs,width,height,width2,height2,fPrintColour,fWinSize_x,fWinSize_y);
539#endif
540  FILE* fp;
541  GLubyte* pixels;
542  GLubyte* curpix;
543  int components, pos, i;
544
545  pixels = grabPixels (fPrintColour, width, height);
546
547  if (pixels == NULL) {
548      G4cerr << "Failed to get pixels from OpenGl viewport" << G4endl;
549    return false;
550  }
551  if (fPrintColour) {
552    components = 3;
553  } else {
554    components = 1;
555  }
556  std::string name = getRealPrintFilename();
557  fp = fopen (name.c_str(), "w");
558  if (fp == NULL) {
559    G4cerr << "Can't open filename " << name.c_str() << G4endl;
560    return false;
561  }
562 
563  fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
564  fprintf (fp, "%%%%Title: %s\n", name.c_str());
565  fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
566  fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
567  fprintf (fp, "%%%%EndComments\n");
568  fprintf (fp, "gsave\n");
569  fprintf (fp, "/bwproc {\n");
570  fprintf (fp, "    rgbproc\n");
571  fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
572  fprintf (fp, "    5 -1 roll {\n");
573  fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
574  fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
575  fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
576  fprintf (fp, "    { 2 1 roll } ifelse\n");
577  fprintf (fp, "    }forall\n");
578  fprintf (fp, "    pop pop pop\n");
579  fprintf (fp, "} def\n");
580  fprintf (fp, "systemdict /colorimage known not {\n");
581  fprintf (fp, "   /colorimage {\n");
582  fprintf (fp, "       pop\n");
583  fprintf (fp, "       pop\n");
584  fprintf (fp, "       /rgbproc exch def\n");
585  fprintf (fp, "       { bwproc } image\n");
586  fprintf (fp, "   }  def\n");
587  fprintf (fp, "} if\n");
588  fprintf (fp, "/picstr %d string def\n", width * components);
589  fprintf (fp, "%d %d scale\n", width, height);
590  fprintf (fp, "%d %d %d\n", width, height, 8);
591  fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
592  fprintf (fp, "{currentfile picstr readhexstring pop}\n");
593  fprintf (fp, "false %d\n", components);
594  fprintf (fp, "colorimage\n");
595 
596  curpix = (GLubyte*) pixels;
597  pos = 0;
598  for (i = width*height*components; i>0; i--) {
599    fprintf (fp, "%02hx ", *(curpix++));
600    if (++pos >= 32) {
601      fprintf (fp, "\n");
602      pos = 0;
603    }
604  }
605  if (pos)
606    fprintf (fp, "\n");
607
608  fprintf (fp, "grestore\n");
609  fprintf (fp, "showpage\n");
610  delete pixels;
611  fclose (fp);
612
613  // Reset for next time (useful is size change)
614  //  fPrintSizeX = -1;
615  //  fPrintSizeY = -1;
616
617  return true;
618}
619
620
621bool G4OpenGLViewer::printGl2PS() {
622
623  int width = getRealPrintSizeX();
624  int height = getRealPrintSizeY();
625
626#ifdef G4DEBUG_VIS_OGL
627  printf("G4OpenGLViewer::printGl2PS file:%s Vec:%d X:%d Y:%d col:%d fWinX:%d fWinY:%d\n",getRealPrintFilename().c_str(),fVectoredPs,width,height,fPrintColour,fWinSize_x,fWinSize_y);
628#endif
629
630  if (!fGL2PSAction) return false;
631
632  fGL2PSAction->setFileName(getRealPrintFilename().c_str());
633  // try to resize
634  int X = fWinSize_x;
635  int Y = fWinSize_y;
636
637  fWinSize_x = width;
638  fWinSize_y = height;
639  // Laurent G. 16/03/10 : Not the good way to do.
640  // We should draw in a new offscreen context instead of
641  // resizing and drawing in current window...
642  // This should be solve when we will do an offscreen method
643  // to render OpenGL
644  // See :
645  // http://developer.apple.com/Mac/library/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_offscreen/opengl_offscreen.html
646  // http://www.songho.ca/opengl/gl_fbo.html
647
648  ResizeGLView();
649  if (fGL2PSAction->enableFileWriting()) {
650
651    // Set the viewport
652    //    fGL2PSAction->setViewport(0, 0, width, height); 
653    // By default, we choose the line width (trajectories...)
654    fGL2PSAction->setLineWidth(1);
655    // By default, we choose the point size (markers...)
656    fGL2PSAction->setPointSize(2);
657
658    DrawView ();
659    fGL2PSAction->disableFileWriting();
660  }
661
662  fWinSize_x = X;
663  fWinSize_y = Y;
664  ResizeGLView();
665  DrawView ();
666
667  // Reset for next time (useful is size change)
668  //  fPrintSizeX = 0;
669  //  fPrintSizeY = 0;
670
671  return true;
672}
673
674unsigned int G4OpenGLViewer::getWinWidth() {
675  return fWinSize_x;
676}
677
678unsigned int G4OpenGLViewer::getWinHeight() {
679  return fWinSize_y;
680}
681
682G4bool G4OpenGLViewer::sizeHasChanged() {
683  return fSizeHasChanged;
684}
685
686G4int G4OpenGLViewer::getRealPrintSizeX() {
687  if (fPrintSizeX == -1) {
688    return fWinSize_x;
689  }
690  GLint dims[2];
691  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
692
693  // L.Garnier 01-2010: Some problems with mac 10.6
694  if ((dims[0] !=0 ) && (dims[1] !=0)) {
695    if (fPrintSizeX > dims[0]){
696      return dims[0];
697    }
698  }
699  if (fPrintSizeX < -1){
700    return 0;
701  }
702#ifdef G4DEBUG_VIS_OGL
703  printf("G4OpenGLViewer::getRealPrintSizeX %d\n",fPrintSizeX);
704#endif
705  return fPrintSizeX;
706}
707
708G4int G4OpenGLViewer::getRealPrintSizeY() {
709  if (fPrintSizeY == -1) {
710    return fWinSize_y;
711  }
712  GLint dims[2];
713  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
714
715  // L.Garnier 01-2010: Some problems with mac 10.6
716  if ((dims[0] !=0 ) && (dims[1] !=0)) {
717    if (fPrintSizeY > dims[1]){
718      return dims[1];
719    }
720  }
721  if (fPrintSizeY < -1){
722    return 0;
723  }
724#ifdef G4DEBUG_VIS_OGL
725  printf("G4OpenGLViewer::getRealPrintSizeY %d\n",fPrintSizeY);
726#endif
727  return fPrintSizeY;
728}
729
730void G4OpenGLViewer::setPrintSize(G4int X, G4int Y) {
731  fPrintSizeX = X;
732  fPrintSizeY = Y;
733}
734
735void G4OpenGLViewer::setPrintFilename(G4String name,G4bool inc) {
736  if (name != "") {
737    fPrintFilename = name;
738  } else {
739    fPrintFilename = "G4OpenGL";  // by default
740  }
741  if (inc) {
742    fPrintFilenameIndex=0;
743  } else {
744    fPrintFilenameIndex=-1;
745  }
746}
747
748std::string G4OpenGLViewer::getRealPrintFilename() {
749  std::string temp = fPrintFilename;
750  if (fPrintFilenameIndex != -1) {
751    temp += std::string("_");
752    std::ostringstream os;
753    os << fPrintFilenameIndex;
754    std::string nb_str = os.str();
755    temp += nb_str;
756  }
757  temp += ".eps";
758  return temp;
759}
760
761GLdouble G4OpenGLViewer::getSceneNearWidth()
762{
763  if (!fSceneHandler.GetScene()) {
764    return 0;
765  }
766  const G4Point3D targetPoint
767    = fSceneHandler.GetScene()->GetStandardTargetPoint()
768    + fVP.GetCurrentTargetPoint ();
769  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
770  if(radius<=0.) radius = 1.;
771  const G4double cameraDistance = fVP.GetCameraDistance (radius);
772  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
773  return 2 * fVP.GetFrontHalfHeight (pnear, radius);
774}
775
776GLdouble G4OpenGLViewer::getSceneFarWidth()
777{
778  if (!fSceneHandler.GetScene()) {
779    return 0;
780  }
781  const G4Point3D targetPoint
782    = fSceneHandler.GetScene()->GetStandardTargetPoint()
783    + fVP.GetCurrentTargetPoint ();
784  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
785  if(radius<=0.) radius = 1.;
786  const G4double cameraDistance = fVP.GetCameraDistance (radius);
787  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
788  const GLdouble pfar    = fVP.GetFarDistance  (cameraDistance, pnear, radius);
789  return 2 * fVP.GetFrontHalfHeight (pfar, radius);
790}
791
792
793GLdouble G4OpenGLViewer::getSceneDepth()
794{
795  if (!fSceneHandler.GetScene()) {
796    return 0;
797  }
798  const G4Point3D targetPoint
799    = fSceneHandler.GetScene()->GetStandardTargetPoint()
800    + fVP.GetCurrentTargetPoint ();
801  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
802  if(radius<=0.) radius = 1.;
803  const G4double cameraDistance = fVP.GetCameraDistance (radius);
804  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
805  return fVP.GetFarDistance  (cameraDistance, pnear, radius)- pnear;
806}
807
808
809
810void G4OpenGLViewer::rotateScene(G4double dx, G4double dy,G4double deltaRotation)
811{
812  if (!fSceneHandler.GetScene()) {
813    return;
814  }
815
816  G4Vector3D vp;
817  G4Vector3D up;
818 
819  G4Vector3D xprime;
820  G4Vector3D yprime;
821  G4Vector3D zprime;
822 
823  G4double delta_alpha;
824  G4double delta_theta;
825 
826  G4Vector3D new_vp;
827  G4Vector3D new_up;
828 
829  G4double cosalpha;
830  G4double sinalpha;
831 
832  G4Vector3D a1;
833  G4Vector3D a2;
834  G4Vector3D delta;
835  G4Vector3D viewPoint;
836
837   
838  //phi spin stuff here
839 
840  vp = fVP.GetViewpointDirection ().unit ();
841  up = fVP.GetUpVector ().unit ();
842 
843  yprime = (up.cross(vp)).unit();
844  zprime = (vp.cross(yprime)).unit();
845 
846  if (fVP.GetLightsMoveWithCamera()) {
847    delta_alpha = dy * deltaRotation;
848    delta_theta = -dx * deltaRotation;
849  } else {
850    delta_alpha = -dy * deltaRotation;
851    delta_theta = dx * deltaRotation;
852  }   
853 
854  delta_alpha *= deg;
855  delta_theta *= deg;
856 
857  new_vp = std::cos(delta_alpha) * vp + std::sin(delta_alpha) * zprime;
858 
859  // to avoid z rotation flipping
860  // to allow more than 360° rotation
861
862  if (fVP.GetLightsMoveWithCamera()) {
863    new_up = (new_vp.cross(yprime)).unit();
864    if (new_vp.z()*vp.z() <0) {
865      new_up.set(new_up.x(),-new_up.y(),new_up.z());
866    }
867  } else {
868    new_up = up;
869    if (new_vp.z()*vp.z() <0) {
870      new_up.set(new_up.x(),-new_up.y(),new_up.z());
871    }
872  }
873  fVP.SetUpVector(new_up);
874  ////////////////
875  // Rotates by fixed azimuthal angle delta_theta.
876 
877  cosalpha = new_up.dot (new_vp.unit());
878  sinalpha = std::sqrt (1. - std::pow (cosalpha, 2));
879  yprime = (new_up.cross (new_vp.unit())).unit ();
880  xprime = yprime.cross (new_up);
881  // Projection of vp on plane perpendicular to up...
882  a1 = sinalpha * xprime;
883  // Required new projection...
884  a2 = sinalpha * (std::cos (delta_theta) * xprime + std::sin (delta_theta) * yprime);
885  // Required Increment vector...
886  delta = a2 - a1;
887  // So new viewpoint is...
888  viewPoint = new_vp.unit() + delta;
889 
890  fVP.SetViewAndLights (viewPoint);
891}
892
893
894void G4OpenGLViewer::rotateSceneInViewDirection(G4double dx, G4double dy,G4double deltaRotation)
895{
896  if (!fSceneHandler.GetScene()) {
897    return;
898  }
899
900  G4Vector3D vp;
901  G4Vector3D up;
902 
903  G4Vector3D xprime;
904  G4Vector3D yprime;
905  G4Vector3D zprime;
906 
907  G4Vector3D new_vp;
908  G4Vector3D new_up;
909 
910  G4Vector3D a1;
911  G4Vector3D a2;
912  G4Vector3D delta;
913  G4Vector3D viewPoint;
914
915   
916  //phi spin stuff here
917 
918#ifdef G4DEBUG_VIS_OGL
919  printf("G4OpenGLViewer::rotateScene dx:%f dy:%f delta:%f\n",dx,dy, deltaRotation);
920#endif
921
922  vp = fVP.GetViewpointDirection ().unit();
923  up = fVP.GetUpVector ().unit();
924
925  G4Vector3D zPrimeVector = G4Vector3D(up.y()*vp.z()-up.z()*vp.y(),
926                             up.z()*vp.x()-up.x()*vp.z(),
927                             up.x()*vp.y()-up.y()*vp.x());
928
929  viewPoint = vp/deltaRotation + (zPrimeVector*dx - up*dy) ;
930  new_up = G4Vector3D(viewPoint.y()*zPrimeVector.z()-viewPoint.z()*zPrimeVector.y(),
931                       viewPoint.z()*zPrimeVector.x()-viewPoint.x()*zPrimeVector.z(),
932                       viewPoint.x()*zPrimeVector.y()-viewPoint.y()*zPrimeVector.x());
933
934  G4Vector3D new_upUnit = new_up.unit();
935 
936 
937
938   fVP.SetUpVector(new_upUnit);
939   fVP.SetViewAndLights (viewPoint);
940}
941
942#endif
Note: See TracBrowser for help on using the repository browser.