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

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

bugged version

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