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

Last change on this file since 1137 was 1137, checked in by garnier, 15 years ago

en cours de debug

  • Property svn:mime-type set to text/cpp
File size: 24.9 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.59 2009/10/20 12:47:45 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#ifdef G4DEBUG_VIS_OGL
116  printf("G4OpenGLViewer::InitializeGLView %d %d \n",fVP.GetWindowSizeHintX(),fVP.GetWindowSizeHintY());
117#endif
118  fWinSize_x = fVP.GetWindowSizeHintX();
119  fWinSize_y = fVP.GetWindowSizeHintY();
120
121
122void G4OpenGLViewer::ClearView () {
123#ifdef G4DEBUG_VIS_OGL
124  printf("G4OpenGLViewer::ClearView\n");
125#endif
126  glClearColor (background.GetRed(),
127                background.GetGreen(),
128                background.GetBlue(),
129                1.);
130  glClearDepth (1.0);
131  //Below line does not compile with Mesa includes.
132  //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
133  glClear (GL_COLOR_BUFFER_BIT);
134  glClear (GL_DEPTH_BUFFER_BIT);
135  glClear (GL_STENCIL_BUFFER_BIT);
136#ifdef G4DEBUG_VIS_OGL
137  printf("G4OpenGLViewer::ClearView flush\n");
138#endif
139  glFlush ();
140}
141
142
143void G4OpenGLViewer::ResizeWindow(unsigned int aWidth, unsigned int aHeight) {
144  if ((fWinSize_x != aWidth) || (fWinSize_y != aHeight)) {
145    fWinSize_x = aWidth;
146    fWinSize_y = aHeight;
147    fSizeHasChanged = true;
148  } else {
149    fSizeHasChanged = false;
150  }
151}
152
153/**
154 * Set the viewport of the scene
155 * MAXIMUM SIZE is :
156 * GLint dims[2];
157 * glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
158 */
159void G4OpenGLViewer::ResizeGLView()
160{
161#ifdef G4DEBUG_VIS_OGL
162  printf("G4OpenGLViewer::ResizeGLView %d %d\n",fWinSize_x,fWinSize_y);
163#endif
164  // Check size
165  GLint dims[2];
166  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
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  GLsizei side = fWinSize_x;
176  if (fWinSize_y < fWinSize_x) side = fWinSize_y;
177
178  // SPECIAL CASE if fWinSize_x is even (69 for example)
179  // Ex : X: 69 Y: 26
180  // side = 26
181  // width / 2 = 21,5
182  // height / 2 = 0
183  // Should be fixed to closed : 21 0 for ex
184  // Then size must by change to :
185  // X:68 Y: 26
186
187  // SPECIAL CASE
188  if ((fWinSize_x - side)%2) {
189    //    fWinSize_x --;
190
191    side = fWinSize_x;
192    if (fWinSize_y < fWinSize_x) side = fWinSize_y;
193  }
194  if ((fWinSize_y - side)%2) {
195    //    fWinSize_y --;
196
197    side = fWinSize_x;
198    if (fWinSize_y < fWinSize_x) side = fWinSize_y;
199  }
200 
201  GLint X = (fWinSize_x - side) / 2;
202  GLint Y = (fWinSize_y - side) / 2;
203 
204#ifdef G4DEBUG_VIS_OGL
205  printf("G4OpenGLViewer::ResizeGLView X:%d Y:%d W:%d H:%d --side%d\n",(fWinSize_x - side) / 2,(fWinSize_y - side) / 2,fWinSize_x,fWinSize_y,side);
206#endif
207  glViewport(X, Y, side, side);
208  //    glViewport(0, 0, fWinSize_x,fWinSize_y); 
209 
210
211}
212
213
214void G4OpenGLViewer::SetView () {
215
216  if (!fSceneHandler.GetScene()) {
217    G4cerr << "G4OpenGLStoredViewer: Creating a Viewer without a scene is not allowed. \nPlease use /vis/scene/create before /vis/open/.... "
218           << G4endl;
219    return;
220  }
221  // Calculates view representation based on extent of object being
222  // viewed and (initial) viewpoint.  (Note: it can change later due
223  // to user interaction via visualization system's GUI.)
224 
225  // Lighting.
226  GLfloat lightPosition [4];
227  lightPosition [0] = fVP.GetActualLightpointDirection().x();
228  lightPosition [1] = fVP.GetActualLightpointDirection().y();
229  lightPosition [2] = fVP.GetActualLightpointDirection().z();
230  lightPosition [3] = 0.;
231  // Light position is "true" light direction, so must come after gluLookAt.
232  GLfloat ambient [] = { 0.2, 0.2, 0.2, 1.};
233  GLfloat diffuse [] = { 0.8, 0.8, 0.8, 1.};
234  glEnable (GL_LIGHT0);
235  glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);
236  glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);
237 
238  // Get radius of scene, etc.
239  // Note that this procedure properly takes into account zoom, dolly and pan.
240  const G4Point3D targetPoint
241    = fSceneHandler.GetScene()->GetStandardTargetPoint()
242    + fVP.GetCurrentTargetPoint ();
243  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
244  if(radius<=0.) radius = 1.;
245  const G4double cameraDistance = fVP.GetCameraDistance (radius);
246  const G4Point3D cameraPosition =
247    targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
248  const GLdouble pnear  = fVP.GetNearDistance (cameraDistance, radius);
249  const GLdouble pfar   = fVP.GetFarDistance  (cameraDistance, pnear, radius);
250  const GLdouble right  = fVP.GetFrontHalfHeight (pnear, radius);
251  const GLdouble left   = -right;
252  const GLdouble bottom = left;
253  const GLdouble top    = right;
254 
255  // FIXME
256  ResizeGLView();
257  //SHOULD SetWindowsSizeHint()...
258
259  glMatrixMode (GL_PROJECTION); // set up Frustum.
260  glLoadIdentity();
261
262  const G4Vector3D scaleFactor = fVP.GetScaleFactor();
263  glScaled(scaleFactor.x(),scaleFactor.y(),scaleFactor.z());
264 
265  if (fVP.GetFieldHalfAngle() == 0.) {
266    glOrtho (left, right, bottom, top, pnear, pfar);
267  }
268  else {
269    glFrustum (left, right, bottom, top, pnear, pfar);
270  } 
271
272  glMatrixMode (GL_MODELVIEW); // apply further transformations to scene.
273  glLoadIdentity();
274 
275  const G4Normal3D& upVector = fVP.GetUpVector (); 
276  G4Point3D gltarget;
277  if (cameraDistance > 1.e-6 * radius) {
278    gltarget = targetPoint;
279  }
280  else {
281    gltarget = targetPoint - radius * fVP.GetViewpointDirection().unit();
282  }
283
284  const G4Point3D& pCamera = cameraPosition;  // An alias for brevity.
285  gluLookAt (pCamera.x(),  pCamera.y(),  pCamera.z(),       // Viewpoint.
286             gltarget.x(), gltarget.y(), gltarget.z(),      // Target point.
287             upVector.x(), upVector.y(), upVector.z());     // Up vector.
288
289  // Light position is "true" light direction, so must come after gluLookAt.
290  glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
291
292  // OpenGL no longer seems to reconstruct clipped edges, so, when the
293  // BooleanProcessor is up to it, abandon this and use generic
294  // clipping in G4OpenGLSceneHandler::CreateSectionPolyhedron.  Also,
295  // force kernel visit on change of clipping plane in
296  // G4OpenGLStoredViewer::CompareForKernelVisit.
297  if (fVP.IsSection () ) {  // pair of back to back clip planes.
298    const G4Plane3D& s = fVP.GetSectionPlane ();
299    double sArray[4];
300    sArray[0] = s.a();
301    sArray[1] = s.b();
302    sArray[2] = s.c();
303    sArray[3] = s.d() + radius * 1.e-05;
304    glClipPlane (GL_CLIP_PLANE0, sArray);
305    glEnable (GL_CLIP_PLANE0);
306    sArray[0] = -s.a();
307    sArray[1] = -s.b();
308    sArray[2] = -s.c();
309    sArray[3] = -s.d() + radius * 1.e-05;
310    glClipPlane (GL_CLIP_PLANE1, sArray);
311    glEnable (GL_CLIP_PLANE1);
312  } else {
313    glDisable (GL_CLIP_PLANE0);
314    glDisable (GL_CLIP_PLANE1);
315  }
316
317  const G4Planes& cutaways = fVP.GetCutawayPlanes();
318  size_t nPlanes = cutaways.size();
319  if (fVP.IsCutaway() &&
320      fVP.GetCutawayMode() == G4ViewParameters::cutawayIntersection &&
321      nPlanes > 0) {
322    double a[4];
323    a[0] = cutaways[0].a();
324    a[1] = cutaways[0].b();
325    a[2] = cutaways[0].c();
326    a[3] = cutaways[0].d();
327    glClipPlane (GL_CLIP_PLANE2, a);
328    glEnable (GL_CLIP_PLANE2);
329    if (nPlanes > 1) {
330      a[0] = cutaways[1].a();
331      a[1] = cutaways[1].b();
332      a[2] = cutaways[1].c();
333      a[3] = cutaways[1].d();
334      glClipPlane (GL_CLIP_PLANE3, a);
335      glEnable (GL_CLIP_PLANE3);
336    }
337    if (nPlanes > 2) {
338      a[0] = cutaways[2].a();
339      a[1] = cutaways[2].b();
340      a[2] = cutaways[2].c();
341      a[3] = cutaways[2].d();
342      glClipPlane (GL_CLIP_PLANE4, a);
343      glEnable (GL_CLIP_PLANE4);
344    }
345  } else {
346    glDisable (GL_CLIP_PLANE2);
347    glDisable (GL_CLIP_PLANE3);
348    glDisable (GL_CLIP_PLANE4);
349  }
350
351  // Background.
352  background = fVP.GetBackgroundColour ();
353
354}
355
356void G4OpenGLViewer::HaloingFirstPass () {
357 
358  //To perform haloing, first Draw all information to the depth buffer
359  //alone, using a chunky line width, and then Draw all info again, to
360  //the colour buffer, setting a thinner line width an the depth testing
361  //function to less than or equal, so if two lines cross, the one
362  //passing behind the other will not pass the depth test, and so not
363  //get rendered either side of the infront line for a short distance.
364
365  //First, disable writing to the colo(u)r buffer...
366  glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
367
368  //Now enable writing to the depth buffer...
369  glDepthMask (GL_TRUE);
370  glDepthFunc (GL_LESS);
371  glClearDepth (1.0);
372
373  //Finally, set the line width to something wide...
374  glLineWidth (3.0);
375
376}
377
378void G4OpenGLViewer::HaloingSecondPass () {
379
380  //And finally, turn the colour buffer back on with a sesible line width...
381  glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
382  glDepthFunc (GL_LEQUAL);
383  glLineWidth (1.0);
384
385}
386
387void G4OpenGLViewer::Pick(GLdouble x, GLdouble y)
388{
389  //G4cout << "X: " << x << ", Y: " << y << G4endl;
390  const G4int BUFSIZE = 512;
391  GLuint selectBuffer[BUFSIZE];
392  glSelectBuffer(BUFSIZE, selectBuffer);
393  glRenderMode(GL_SELECT);
394  glInitNames();
395  glPushName(0);
396  glMatrixMode(GL_PROJECTION);
397  G4double currentProjectionMatrix[16];
398  glGetDoublev(GL_PROJECTION_MATRIX, currentProjectionMatrix);
399  glPushMatrix();
400  glLoadIdentity();
401  GLint viewport[4];
402  glGetIntegerv(GL_VIEWPORT, viewport);
403  // Define 5x5 pixel pick area
404  gluPickMatrix(x, viewport[3] - y, 5., 5., viewport);
405  glMultMatrixd(currentProjectionMatrix);
406  glMatrixMode(GL_MODELVIEW);
407  DrawView();
408  GLint hits = glRenderMode(GL_RENDER);
409  if (hits < 0)
410    G4cout << "Too many hits.  Zoom in to reduce overlaps." << G4cout;
411  else if (hits > 0) {
412    //G4cout << hits << " hit(s)" << G4endl;
413    GLuint* p = selectBuffer;
414    for (GLint i = 0; i < hits; ++i) {
415      GLuint nnames = *p++;
416      *p++; //OR GLuint zmin = *p++;
417      *p++; //OR GLuint zmax = *p++;
418      //G4cout << "Hit " << i << ": " << nnames << " names"
419      //     << "\nzmin: " << zmin << ", zmax: " << zmax << G4endl;
420      for (GLuint j = 0; j < nnames; ++j) {
421        GLuint name = *p++;
422        //G4cout << "Name " << j << ": PickName: " << name << G4endl;
423        std::map<GLuint, G4AttHolder*>::iterator iter =
424          fOpenGLSceneHandler.fPickMap.find(name);
425        if (iter != fOpenGLSceneHandler.fPickMap.end()) {
426          G4AttHolder* attHolder = iter->second;
427          if(attHolder && attHolder->GetAttDefs().size()) {
428            for (size_t i = 0; i < attHolder->GetAttDefs().size(); ++i) {
429              G4cout << G4AttCheck(attHolder->GetAttValues()[i],
430                                   attHolder->GetAttDefs()[i]);
431            }
432          }
433        }
434      }
435      G4cout << G4endl;
436    }
437  }
438  glMatrixMode(GL_PROJECTION);
439  glPopMatrix();
440  glMatrixMode(GL_MODELVIEW);
441}
442
443
444
445
446GLubyte* G4OpenGLViewer::grabPixels (int inColor, unsigned int width, unsigned int height) {
447 
448  GLubyte* buffer;
449  GLint swapbytes, lsbfirst, rowlength;
450  GLint skiprows, skippixels, alignment;
451  GLenum format;
452  int size;
453
454  if (inColor) {
455    format = GL_RGB;
456    size = width*height*3;
457  } else {
458    format = GL_LUMINANCE;
459    size = width*height*1;
460  }
461
462  buffer = new GLubyte[size];
463  if (buffer == NULL)
464    return NULL;
465
466  glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
467  glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
468  glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
469
470  glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
471  glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
472  glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
473
474  glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
475  glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
476  glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
477
478  glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
479  glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
480  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
481
482  glReadBuffer(GL_FRONT);
483  glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, format, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
484
485  glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
486  glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
487  glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
488 
489  glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
490  glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
491  glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
492 
493  return buffer;
494}
495
496void G4OpenGLViewer::printEPS() {
497  bool res;
498#ifdef G4DEBUG_VIS_OGL
499  printf("G4OpenGLViewer::printEPS file:%s Vec:%d Name:%s\n",getRealPrintFilename().c_str(),fVectoredPs,GetName().c_str());
500#endif
501
502  // Change the LC_NUMERIC value in order to have "." separtor and not ","
503  // This case is only useful for French, Canadien...
504  char *oldLocale = strdup(setlocale(LC_NUMERIC,NULL));
505  setlocale(LC_NUMERIC,"C");
506
507  if (fVectoredPs) {
508    res = printVectoredEPS();
509  } else {
510    res = printNonVectoredEPS();
511  }
512
513  // restore the local
514  if (oldLocale) {
515    setlocale(LC_NUMERIC,oldLocale);
516    free(oldLocale);
517  }
518
519  if (res == false) {
520    G4cerr << "Error while saving file... "<<getRealPrintFilename().c_str()<< G4endl;
521  } else {
522    G4cout << "File "<<getRealPrintFilename().c_str()<<" has been saved " << G4endl;
523  }
524
525  // increment index if necessary
526  if ( fPrintFilenameIndex != -1) {
527    fPrintFilenameIndex++;
528  }
529
530}
531
532bool G4OpenGLViewer::printVectoredEPS() {
533  return printGl2PS();
534}
535
536bool G4OpenGLViewer::printNonVectoredEPS () {
537
538  int width = getRealPrintSizeX();
539  int height = getRealPrintSizeY();
540
541#ifdef G4DEBUG_VIS_OGL
542  printf("G4OpenGLViewer::printNonVectoredEPS file:%s Vec:%d X:%d Y:%d col:%d\n",getRealPrintFilename().c_str(),fVectoredPs,width,height,fPrintColour);
543#endif
544  FILE* fp;
545  GLubyte* pixels;
546  GLubyte* curpix;
547  int components, pos, i;
548
549  pixels = grabPixels (fPrintColour, width, height);
550
551  if (pixels == NULL) {
552      G4cerr << "Failed to get pixels from OpenGl viewport" << G4endl;
553    return false;
554  }
555  if (fPrintColour) {
556    components = 3;
557  } else {
558    components = 1;
559  }
560  std::string name = getRealPrintFilename();
561  fp = fopen (name.c_str(), "w");
562  if (fp == NULL) {
563    G4cerr << "Can't open filename " << name.c_str() << G4endl;
564    return false;
565  }
566 
567  fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
568  fprintf (fp, "%%%%Title: %s\n", name.c_str());
569  fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
570  fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
571  fprintf (fp, "%%%%EndComments\n");
572  fprintf (fp, "gsave\n");
573  fprintf (fp, "/bwproc {\n");
574  fprintf (fp, "    rgbproc\n");
575  fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
576  fprintf (fp, "    5 -1 roll {\n");
577  fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
578  fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
579  fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
580  fprintf (fp, "    { 2 1 roll } ifelse\n");
581  fprintf (fp, "    }forall\n");
582  fprintf (fp, "    pop pop pop\n");
583  fprintf (fp, "} def\n");
584  fprintf (fp, "systemdict /colorimage known not {\n");
585  fprintf (fp, "   /colorimage {\n");
586  fprintf (fp, "       pop\n");
587  fprintf (fp, "       pop\n");
588  fprintf (fp, "       /rgbproc exch def\n");
589  fprintf (fp, "       { bwproc } image\n");
590  fprintf (fp, "   }  def\n");
591  fprintf (fp, "} if\n");
592  fprintf (fp, "/picstr %d string def\n", width * components);
593  fprintf (fp, "%d %d scale\n", width, height);
594  fprintf (fp, "%d %d %d\n", width, height, 8);
595  fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
596  fprintf (fp, "{currentfile picstr readhexstring pop}\n");
597  fprintf (fp, "false %d\n", components);
598  fprintf (fp, "colorimage\n");
599 
600  curpix = (GLubyte*) pixels;
601  pos = 0;
602  for (i = width*height*components; i>0; i--) {
603    fprintf (fp, "%02hx ", *(curpix++));
604    if (++pos >= 32) {
605      fprintf (fp, "\n");
606      pos = 0;
607    }
608  }
609  if (pos)
610    fprintf (fp, "\n");
611
612  fprintf (fp, "grestore\n");
613  fprintf (fp, "showpage\n");
614  delete pixels;
615  fclose (fp);
616
617  // Reset for next time (useful is size change)
618  //  fPrintSizeX = -1;
619  //  fPrintSizeY = -1;
620
621  return true;
622}
623
624
625bool G4OpenGLViewer::printGl2PS() {
626
627  int width = getRealPrintSizeX();
628  int height = getRealPrintSizeY();
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  ResizeGLView();
640  if (fGL2PSAction->enableFileWriting()) {
641
642    // By default, we choose the line width (trajectories...)
643    fGL2PSAction->setLineWidth(1);
644    // By default, we choose the point size (markers...)
645    fGL2PSAction->setPointSize(2);
646
647    DrawView ();
648    fGL2PSAction->disableFileWriting();
649  }
650
651  fWinSize_x = X;
652  fWinSize_y = Y;
653  ResizeGLView();
654
655  // Reset for next time (useful is size change)
656  //  fPrintSizeX = 0;
657  //  fPrintSizeY = 0;
658
659  return true;
660}
661
662unsigned int G4OpenGLViewer::getWinWidth() {
663  return fWinSize_x;
664}
665
666unsigned int G4OpenGLViewer::getWinHeight() {
667  return fWinSize_y;
668}
669
670G4bool G4OpenGLViewer::sizeHasChanged() {
671  return fSizeHasChanged;
672}
673
674G4int G4OpenGLViewer::getRealPrintSizeX() {
675  if (fPrintSizeX == -1) {
676    return fWinSize_x;
677  }
678  GLint dims[2];
679  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
680  if (fPrintSizeX > dims[0]){
681    return dims[0];
682  }
683  if (fPrintSizeX < -1){
684    return 0;
685  }
686  return fPrintSizeX;
687}
688
689G4int G4OpenGLViewer::getRealPrintSizeY() {
690  if (fPrintSizeY == -1) {
691    return fWinSize_y;
692  }
693  GLint dims[2];
694  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
695  if (fPrintSizeY > dims[1]){
696    return dims[1];
697  }
698  if (fPrintSizeY < -1){
699    return 0;
700  }
701  return fPrintSizeY;
702}
703
704void G4OpenGLViewer::setPrintSize(G4int X, G4int Y) {
705  fPrintSizeX = X;
706  fPrintSizeY = Y;
707}
708
709void G4OpenGLViewer::setPrintFilename(G4String name,G4bool inc) {
710  if (name != "") {
711    fPrintFilename = name;
712  } else {
713    fPrintFilename = "G4OpenGL";  // by default
714  }
715  if (inc) {
716    fPrintFilenameIndex=0;
717  } else {
718    fPrintFilenameIndex=-1;
719  }
720}
721
722std::string G4OpenGLViewer::getRealPrintFilename() {
723  std::string temp = fPrintFilename;
724  if (fPrintFilenameIndex != -1) {
725    temp += std::string("_");
726    std::ostringstream os;
727    os << fPrintFilenameIndex;
728    std::string nb_str = os.str();
729    temp += nb_str;
730  }
731  temp += ".eps";
732  return temp;
733}
734
735GLdouble G4OpenGLViewer::getSceneNearWidth()
736{
737  const G4Point3D targetPoint
738    = fSceneHandler.GetScene()->GetStandardTargetPoint()
739    + fVP.GetCurrentTargetPoint ();
740  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
741  if(radius<=0.) radius = 1.;
742  const G4double cameraDistance = fVP.GetCameraDistance (radius);
743  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
744  return 2 * fVP.GetFrontHalfHeight (pnear, radius);
745}
746
747GLdouble G4OpenGLViewer::getSceneFarWidth()
748{
749  const G4Point3D targetPoint
750    = fSceneHandler.GetScene()->GetStandardTargetPoint()
751    + fVP.GetCurrentTargetPoint ();
752  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
753  if(radius<=0.) radius = 1.;
754  const G4double cameraDistance = fVP.GetCameraDistance (radius);
755  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
756  const GLdouble pfar    = fVP.GetFarDistance  (cameraDistance, pnear, radius);
757  return 2 * fVP.GetFrontHalfHeight (pfar, radius);
758}
759
760
761GLdouble G4OpenGLViewer::getSceneDepth()
762{
763  const G4Point3D targetPoint
764    = fSceneHandler.GetScene()->GetStandardTargetPoint()
765    + fVP.GetCurrentTargetPoint ();
766  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
767  if(radius<=0.) radius = 1.;
768  const G4double cameraDistance = fVP.GetCameraDistance (radius);
769  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
770  return fVP.GetFarDistance  (cameraDistance, pnear, radius)- pnear;
771}
772
773
774
775void G4OpenGLViewer::rotateScene(G4double dx, G4double dy,G4double deltaRotation)
776{
777  if (!fSceneHandler.GetScene()) {
778    return;
779  }
780
781  G4Vector3D vp;
782  G4Vector3D up;
783 
784  G4Vector3D xprime;
785  G4Vector3D yprime;
786  G4Vector3D zprime;
787 
788  G4double delta_alpha;
789  G4double delta_theta;
790 
791  G4Vector3D new_vp;
792  G4Vector3D new_up;
793 
794  G4double cosalpha;
795  G4double sinalpha;
796 
797  G4Vector3D a1;
798  G4Vector3D a2;
799  G4Vector3D delta;
800  G4Vector3D viewPoint;
801
802   
803  //phi spin stuff here
804 
805  vp = fVP.GetViewpointDirection ().unit ();
806  up = fVP.GetUpVector ().unit ();
807 
808  yprime = (up.cross(vp)).unit();
809  zprime = (vp.cross(yprime)).unit();
810 
811  if (fVP.GetLightsMoveWithCamera()) {
812    delta_alpha = dy * deltaRotation;
813    delta_theta = -dx * deltaRotation;
814  } else {
815    delta_alpha = -dy * deltaRotation;
816    delta_theta = dx * deltaRotation;
817  }   
818 
819  delta_alpha *= deg;
820  delta_theta *= deg;
821 
822  new_vp = std::cos(delta_alpha) * vp + std::sin(delta_alpha) * zprime;
823 
824  // to avoid z rotation flipping
825  // to allow more than 360° rotation
826
827  const G4Point3D targetPoint
828    = fSceneHandler.GetScene()->GetStandardTargetPoint()
829    + fVP.GetCurrentTargetPoint ();
830  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
831  if(radius<=0.) radius = 1.;
832  const G4double cameraDistance = fVP.GetCameraDistance (radius);
833  const G4Point3D cameraPosition =
834    targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
835
836  if (fVP.GetLightsMoveWithCamera()) {
837    new_up = (new_vp.cross(yprime)).unit();
838    if (new_vp.z()*vp.z() <0) {
839      new_up.set(new_up.x(),-new_up.y(),new_up.z());
840    }
841  } else {
842    new_up = up;
843    if (new_vp.z()*vp.z() <0) {
844      new_up.set(new_up.x(),-new_up.y(),new_up.z());
845    }
846  }
847  fVP.SetUpVector(new_up);
848  ////////////////
849  // Rotates by fixed azimuthal angle delta_theta.
850 
851  cosalpha = new_up.dot (new_vp.unit());
852  sinalpha = std::sqrt (1. - std::pow (cosalpha, 2));
853  yprime = (new_up.cross (new_vp.unit())).unit ();
854  xprime = yprime.cross (new_up);
855  // Projection of vp on plane perpendicular to up...
856  a1 = sinalpha * xprime;
857  // Required new projection...
858  a2 = sinalpha * (std::cos (delta_theta) * xprime + std::sin (delta_theta) * yprime);
859  // Required Increment vector...
860  delta = a2 - a1;
861  // So new viewpoint is...
862  viewPoint = new_vp.unit() + delta;
863 
864  fVP.SetViewAndLights (viewPoint);
865}
866
867#endif
Note: See TracBrowser for help on using the repository browser.