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

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

fixes et cvs update

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