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

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

modif mineure

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