source: trunk/source/visualization/OpenGL/src/G4OpenGLXViewer.cc @ 995

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

passage de print OK

  • Property svn:mime-type set to text/cpp
File size: 23.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: G4OpenGLXViewer.cc,v 1.52 2009/04/08 16:55:44 lgarnier Exp $
28// GEANT4 tag $Name:  $
29//
30//
31// Andrew Walkden  7th February 1997
32// G4OpenGLXViewer : Class to provide XWindows specific
33//                 functionality for OpenGL in GEANT4
34
35#ifdef G4VIS_BUILD_OPENGLX_DRIVER
36
37#include "G4OpenGLXViewer.hh"
38#include "G4VViewer.hh"
39#include "G4OpenGLSceneHandler.hh"
40#include <GL/glu.h>
41
42#include "G4OpenGLFontBaseStore.hh"
43
44#include <sstream>
45
46#include "G4VisExtent.hh"
47#include "G4LogicalVolume.hh"
48#include "G4VSolid.hh"
49#include "G4Point3D.hh"
50#include "G4Normal3D.hh"
51#include "G4StateManager.hh"
52
53#include <X11/Xatom.h>
54#include <X11/Xutil.h>
55#include <X11/Xmu/StdCmap.h>
56
57#include <assert.h>
58
59int G4OpenGLXViewer::snglBuf_RGBA[12] =
60{ GLX_RGBA,
61  GLX_RED_SIZE, 1,
62  GLX_GREEN_SIZE, 1,
63  GLX_BLUE_SIZE, 1,
64  GLX_DEPTH_SIZE, 1,
65  GLX_STENCIL_SIZE, 1,
66  None };
67
68int G4OpenGLXViewer::dblBuf_RGBA[13] =
69{ GLX_RGBA,
70  GLX_RED_SIZE, 1,
71  GLX_GREEN_SIZE, 1,
72  GLX_BLUE_SIZE, 1,
73  GLX_DOUBLEBUFFER,
74  GLX_DEPTH_SIZE, 1,
75  GLX_STENCIL_SIZE, 1,
76  None };
77
78#define NewString(str) \
79 ((str) != NULL ? (strcpy((char*)malloc((unsigned)strlen(str) + 1), str)) : (char*)NULL)
80
81#define USE_DEFAULT_COLORMAP 1
82#define USE_STANDARD_COLORMAP 0
83
84XVisualInfo*  G4OpenGLXViewer::vi_single_buffer = 0;
85XVisualInfo*  G4OpenGLXViewer::vi_double_buffer = 0;
86
87extern "C" {
88  static Bool G4OpenGLXViewerWaitForNotify (Display*, XEvent* e, char* arg) {
89    return (e->type == MapNotify) && (e->xmap.window == (Window) arg);
90  }
91}
92
93void G4OpenGLXViewer::SetView () {
94#ifdef G4DEBUG_VIS_OGL
95    printf("G4OpenGLXViewer::SetView \n");
96#endif
97  Bool success = glXMakeCurrent (dpy, win, cx);
98  if (!success) {
99    fViewId = -1;  // This flags an error.
100    G4cerr << "G4OpenGLViewer::G4OpenGLViewer failed to attach a GLX context."
101           << G4endl;
102    GLint error = GL_NO_ERROR;
103    while ((error = glGetError()) != GL_NO_ERROR) {
104      G4cout << "GL Error: " << gluErrorString(error) << G4endl;
105    }
106    return;
107  }
108  G4OpenGLViewer::SetView (); 
109}
110
111void G4OpenGLXViewer::ShowView () {
112  glXWaitGL (); //Wait for effects of all previous OpenGL commands to
113                //be propagated before progressing.
114  glFlush ();
115
116  if (fVP.IsPicking()) {
117    G4cout <<
118      "Window activated for picking (left-mouse), exit (middle-mouse)."
119           << G4endl;
120    while (true) {
121      if (XPending(dpy)) {
122        XNextEvent(dpy, &event);
123        if (event.type == ButtonPress && event.xbutton.button == 1) {
124          Pick(event.xbutton.x, event.xbutton.y);
125        }
126        else if (event.type == ButtonPress && event.xbutton.button == 2) break;
127      }
128    }
129  }
130}
131
132void G4OpenGLXViewer::GetXConnection () {
133// get a connection.
134  dpy = XOpenDisplay (0);
135  if (!dpy) {
136    fViewId = -1;  // This flags an error.
137    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't open display." << G4endl;
138    return;
139  }
140
141// make sure OpenGL is supported and installed properly.
142  if (!glXQueryExtension (dpy, &errorBase, &eventBase)) {
143    fViewId = -1;  // This flags an error.
144    G4cerr << "G4OpenGLViewer::G4OpenGLViewer X Server has no GLX extension."
145         << G4endl;
146    return;
147  }
148
149}
150
151void G4OpenGLXViewer::CreateGLXContext (XVisualInfo* v) {
152
153  vi = v;
154// get window's attributes
155  if (!XGetWindowAttributes(dpy, XRootWindow (dpy, vi -> screen), &xwa)) {
156    fViewId = -1;  // This flags an error.
157    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't return window attributes"
158         << G4endl;
159    return;
160  }
161 
162// create a GLX context
163  cx = glXCreateContext (dpy, vi, 0, true);
164  if (!cx) {
165    fViewId = -1;  // This flags an error.
166    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't create context."
167         << G4endl;
168    return;
169  }
170
171// New stab at getting a colormap
172
173  Status status;
174  XStandardColormap *standardCmaps = XAllocStandardColormap ();
175  int i, numCmaps;
176
177  status = XmuLookupStandardColormap (dpy,
178                                      vi -> screen,
179                                      vi -> visualid,
180                                      vi -> depth,
181                                      XA_RGB_DEFAULT_MAP,
182                                      False,
183                                      True);
184 
185  if (status == 1) {
186    cmap = 0;
187    status = XGetRGBColormaps (dpy,
188                               XRootWindow (dpy, vi -> screen),
189                               &standardCmaps,
190                               &numCmaps,
191                               XA_RGB_DEFAULT_MAP);
192    if (status == 1)
193      for (i = 0; i < numCmaps; i++) {
194        if (standardCmaps[i].visualid == vi -> visualid) {
195          cmap = standardCmaps[i].colormap;
196          XFree (standardCmaps);
197          break;
198        }
199      }
200    if (!cmap) {
201      fViewId = -1;  // This flags an error.
202      G4cerr <<
203   "G4OpenGLViewer::G4OpenGLViewer failed to allocate a standard colormap."
204             << G4endl;
205      return;
206    }
207    G4cout << "Got standard cmap" << G4endl;
208  } else {
209    cmap = XCreateColormap (dpy,
210                            XRootWindow(dpy, vi -> screen),
211                            vi -> visual,
212                            AllocNone);
213    G4cout << "Created own cmap" << G4endl;
214  }
215
216  if (!cmap) {
217    fViewId = -1;  // This flags an error.
218    G4cerr << "G4OpenGLViewer::G4OpenGLViewer failed to allocate a Colormap."
219         << G4endl;
220    return;
221  }
222
223}
224 
225void G4OpenGLXViewer::CreateMainWindow () {
226 
227// create a window
228  swa.colormap = cmap;
229  swa.border_pixel = 0;
230  swa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;
231  swa.backing_store = WhenMapped;
232
233  // Window size and position...
234  size_hints = XAllocSizeHints();
235   
236  fWinSize_x = fVP.GetWindowSizeHintX();
237  fWinSize_y = fVP.GetWindowSizeHintY();
238  G4int x_origin = fVP.GetWindowAbsoluteLocationHintX(DisplayWidth(dpy, vi -> screen));
239
240  // FIXME,  screen size != window size on MAC, but I don't know have to get the menuBar
241  // size on MAC. L.Garnier 01/2009
242  G4int y_origin = fVP.GetWindowAbsoluteLocationHintY(DisplayHeight(dpy, vi -> screen));
243
244  size_hints->base_width = fWinSize_x;
245  size_hints->base_height = fWinSize_y;
246  size_hints->x = x_origin;
247  size_hints->y = y_origin;
248  if (fVP.IsWindowSizeHintX () && fVP.IsWindowLocationHintX () && fVP.IsWindowLocationHintY ()) {
249    size_hints->flags |= PSize | PPosition;
250  } else if (fVP.IsWindowSizeHintX () && !(fVP.IsWindowLocationHintX () || fVP.IsWindowLocationHintY ())) {
251    size_hints->flags |= PSize;
252  } else if ((!fVP.IsWindowSizeHintX ()) && fVP.IsWindowLocationHintX () && fVP.IsWindowLocationHintY ()) {
253    size_hints->flags |= PPosition;
254  }
255  G4cout << "Window name: " << fName << G4endl;
256  strncpy (charViewName, fName, 100);
257  char *window_name = charViewName;
258  char *icon_name = charViewName;
259  //char tmpatom[] = "XA_WM_NORMAL_HINTS";
260  wm_hints = XAllocWMHints();
261  class_hints = XAllocClassHint();
262
263  XStringListToTextProperty (&window_name, 1, &windowName);
264  XStringListToTextProperty (&icon_name, 1, &iconName);
265
266  wm_hints -> initial_state = NormalState;
267  wm_hints -> input = True;
268  wm_hints -> icon_pixmap = icon_pixmap;
269  wm_hints -> flags = StateHint | IconPixmapHint | InputHint;
270
271  class_hints -> res_name  = NewString("G4OpenGL");
272  class_hints -> res_class = NewString("G4OpenGL");
273
274   win = XCreateWindow (dpy, XRootWindow (dpy, vi -> screen), x_origin,
275                        y_origin, fWinSize_x, fWinSize_y, 0, vi -> depth,
276                        InputOutput, vi -> visual, 
277                        CWBorderPixel | CWColormap |
278                        CWEventMask | CWBackingStore,
279                        &swa);
280 
281   XSetWMProperties (dpy, win, &windowName, &iconName, 0, 0,
282                     size_hints, wm_hints, class_hints);
283 
284// request X to Draw window on screen.
285  XMapWindow (dpy, win);
286
287// Wait for window to appear (wait for an "expose" event).
288  XIfEvent (dpy, &event, G4OpenGLXViewerWaitForNotify, (char*) win);
289
290// connect the context to a window
291  Bool success = glXMakeCurrent (dpy, win, cx);
292  if (!success) {
293    fViewId = -1;  // This flags an error.
294    G4cerr << "G4OpenGLViewer::G4OpenGLViewer failed to attach a GLX context."
295         << G4endl;
296    GLint error = GL_NO_ERROR;
297    while ((error = glGetError()) != GL_NO_ERROR) {
298      G4cout << "GL Error: " << gluErrorString(error) << G4endl;
299    }
300    return;
301  }
302
303}
304
305void G4OpenGLXViewer::CreateFontLists () {
306
307  std::map<G4double,G4String> fonts;  // G4VMarker screen size and font name.
308  fonts[10.] = "-adobe-courier-bold-r-normal--10-100-75-75-m-60-iso8859-1";
309  fonts[11.] = "-adobe-courier-bold-r-normal--11-80-100-100-m-60-iso8859-1";
310  fonts[12.] = "-adobe-courier-bold-r-normal--12-120-75-75-m-70-iso8859-1";
311  fonts[13.] = "fixed";
312  fonts[14.] = "-adobe-courier-bold-r-normal--14-100-100-100-m-90-iso8859-1";
313  fonts[17.] = "-adobe-courier-bold-r-normal--17-120-100-100-m-100-iso8859-1";
314  fonts[18.] = "-adobe-courier-bold-r-normal--18-180-75-75-m-110-iso8859-1";
315  fonts[20.] = "-adobe-courier-bold-r-normal--20-140-100-100-m-110-iso8859-1";
316  fonts[24.] = "-adobe-courier-bold-r-normal--24-240-75-75-m-150-iso8859-1";
317  fonts[25.] = "-adobe-courier-bold-r-normal--25-180-100-100-m-150-iso8859-1";
318  fonts[34.] = "-adobe-courier-bold-r-normal--34-240-100-100-m-200-iso8859-1";
319  std::map<G4double,G4String>::const_iterator i;
320  for (i = fonts.begin(); i != fonts.end(); ++i) {
321    XFontStruct* font_info = XLoadQueryFont(dpy, i->second);
322    if (!font_info) {
323      G4cerr <<
324        "G4OpenGLXViewer: XLoadQueryFont failed for font\n  "
325             << i->second
326             << G4endl;
327      continue;
328    }
329    G4int font_base = glGenLists(256);
330    if (!font_base) {
331      G4cerr << "G4OpenGLXViewer: out of display lists for fonts."
332             << G4endl;
333      continue;
334    }
335    G4int first = font_info->min_char_or_byte2;
336    G4int last  = font_info->max_char_or_byte2;
337    glXUseXFont(font_info->fid, first, last-first+1,font_base+first);
338    G4OpenGLFontBaseStore::AddFontBase(this,font_base,i->first,i->second);
339  }
340}
341
342G4OpenGLXViewer::G4OpenGLXViewer (G4OpenGLSceneHandler& scene):
343G4VViewer (scene, -1),
344G4OpenGLViewer (scene),
345vi_immediate (0),
346vi_stored (0),
347vi (0),
348cmap (0)
349{
350  GetXConnection ();
351  if (fViewId < 0) return;
352 
353  // Try for a visual suitable for OpenGLImmediate..
354  // first try for a single buffered RGB window
355  if (!vi_single_buffer) {
356    vi_single_buffer =
357      glXChooseVisual (dpy, XDefaultScreen (dpy), snglBuf_RGBA);
358  }
359  if (!vi_double_buffer) {
360    vi_double_buffer =
361      glXChooseVisual (dpy, XDefaultScreen (dpy), dblBuf_RGBA);
362  }
363
364  if (vi_single_buffer || vi_double_buffer) {
365    if (!vi_double_buffer) {
366      G4cout <<
367        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a double buffer visual."
368        "\n  Working with a single buffer."
369             << G4endl;
370    }
371  } else {
372    if (!vi_single_buffer) {
373      G4cout <<
374        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a single buffer visual."
375             << G4endl;
376    }
377    if (!vi_double_buffer) {
378      G4cout <<
379        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a double buffer visual."
380             << G4endl;
381    }
382  }
383
384  if (vi_single_buffer) {
385    vi_immediate = vi_single_buffer;
386    attributeList = snglBuf_RGBA;
387  }
388 
389  if (!vi_immediate){
390    // next try for a double buffered RGB, but Draw to top buffer
391    if (vi_double_buffer) {
392      vi_immediate = vi_double_buffer;
393      attributeList = dblBuf_RGBA;
394    }
395  }
396
397  // Now try for a visual suitable for OpenGLStored...
398  // Try for a double buffered RGB window
399  if (vi_double_buffer) {
400    vi_stored = vi_double_buffer;
401    attributeList = dblBuf_RGBA;
402  }
403
404  if (!vi_immediate || !vi_stored) {
405    G4cout <<
406    "G4OpenGLXViewer::G4OpenGLXViewer: unable to get required visuals."
407           << G4endl;
408    fViewId = -1;  // This flags an error.
409  }
410
411  //  glClearColor (0., 0., 0., 0.);
412  //  glClearDepth (1.);
413}
414
415G4OpenGLXViewer::~G4OpenGLXViewer () {
416  if (fViewId >= 0) {
417    //Close a window from here
418    glXMakeCurrent (dpy, None, NULL);
419    glXDestroyContext (dpy, cx);
420    if (win) XDestroyWindow (dpy, win); // ...if already deleted in
421    // sub-class G4OpenGLXmViewer.
422    XFlush (dpy);
423  }
424}
425
426void G4OpenGLXViewer::printEPS() {
427 
428#ifdef G4DEBUG_VIS_OGL
429    printf("G4OpenGLXViewer::print \n");
430#endif
431
432  //using namespace std;
433  //cout << "print_col_callback requested with file name: " << fPrintFilename << G4endl;
434 
435  if (fVectoredPs) {
436#ifdef G4DEBUG_VIS_OGL
437    printf("G4OpenGLXViewer::print Vectored\n");
438#endif
439    G4OpenGLViewer::printEPS();   
440  } else {
441#ifdef G4DEBUG_VIS_OGL
442    printf("G4OpenGLXViewer::print non Vectored\n");
443#endif
444    G4OpenGLViewer::printEPS();   
445    return;
446
447
448
449    std::string fileTst = "G4OpenGL_XPixmapTestWithoutPixmap.eps";
450    generateEPSX (fileTst.c_str(),
451                  fPrintColour,
452                  fWinSize_x, fWinSize_y);
453   
454
455
456
457
458
459//     G4StateManager* stateManager = G4StateManager::GetStateManager();
460//     G4ApplicationState oldState = stateManager->GetCurrentState();
461//     stateManager->SetNewState(G4State_Idle); 
462
463//     printEPS ();
464
465//     stateManager->SetNewState(oldState); 
466   
467//     //    fPrintFilename =   fPrintFilename+"-Gl2ps.ps";
468//     return;
469
470// save context before
471    XVisualInfo* tmp_vi = vi;
472    GLXDrawable tmp_win = win;
473    tmp_cx = cx;
474
475    XVisualInfo* pvi;
476    GLXContext pcx = create_GL_print_context(pvi);
477
478    if (!pcx) {
479      G4cout << "Unable to create print context." << G4endl;
480      return;
481    }
482
483#ifdef G4DEBUG_VIS_OGL
484    printf("G4OpenGLXViewer::print Create pixmap  Size :%d %d --- %d %d %d\n",fWinSize_x, fWinSize_y,vi,win,cx);
485#endif
486    cx=pcx;
487   
488    Pixmap pmap = XCreatePixmap (dpy,
489                                 XRootWindow (dpy, pvi->screen),
490                                 fWinSize_x, fWinSize_y,
491                                 pvi->depth);
492   
493
494    if (!pmap) {
495      G4cout << "Unable to create pixmap." << G4endl;
496      return;
497    }
498
499
500    GLXPixmap glxpmap = glXCreateGLXPixmap (dpy,
501                                            pvi,
502                                            pmap);
503   
504    if (!glxpmap) {
505      G4cout << "Unable to create glx pixmap." << G4endl;
506      return;
507    }
508
509
510    win=glxpmap;
511   
512//     int winX=fWinSize_x;
513//     int winY=fWinSize_y;
514
515    //#define CHECK_MULTIPLE_PRINT 1
516#ifdef CHECK_MULTIPLE_PRINT
517    for (int tstX  = 3000-2;tstX <=3000+2;tstX++) {
518      for (int tstY  = 3000-2;tstY <=3000+2;tstY++) {
519        fWinSize_y = tstY;
520        fWinSize_x = tstX;
521        std::string file = "G4OpenGL_XPixmap";
522        file += tstX;
523        file +="x";
524        file +=tstY;
525        file +=".eps";
526#else
527        std::string file = fPrintFilename.c_str();
528#endif
529
530    // clear the buffers and window.
531    SetView();
532    ClearView ();
533
534#ifdef G4DEBUG_VIS_OGL
535    printf("G4OpenGLXViewer::print Call DrawView \n");
536#endif
537
538
539
540    // Need to force redraw for SXm mode
541    NeedKernelVisit ();
542
543    // Need to change state to IDLE
544    G4StateManager* stateManager = G4StateManager::GetStateManager();
545    G4ApplicationState oldState = stateManager->GetCurrentState();
546    stateManager->SetNewState(G4State_Idle); 
547
548   
549
550    DrawView (); // Will make current glX
551
552    // Restore state
553    stateManager->SetNewState(oldState); 
554
555
556
557   
558    generateEPSX (file.c_str(),
559                 fPrintColour,
560                 fWinSize_x, fWinSize_y);
561   
562#ifdef CHECK_MULTIPLE_PRINT
563      }
564    }
565    fWinSize_y = winY;
566    fWinSize_x = winX;
567#endif
568    vi = tmp_vi;
569    win = tmp_win;
570    cx = tmp_cx;
571   
572    glXMakeCurrent (dpy, win, cx);
573    //     XVisualInfo*  pvi = glXChooseVisual (dpy,
574    //                                          XDefaultScreen (dpy),
575    //                                          snglBuf_RGBA);
576   
577    //     if (!pvi) {
578    //       pvi = glXChooseVisual (dpy,
579    //                              XDefaultScreen (dpy),
580    //                              dblBuf_RGBA);
581    //     }
582   
583#ifdef G4DEBUG_VIS_OGL
584    printf("G4OpenGLXViewer::print Restored %d %d %d\n",vi,win,cx);
585#endif
586    //    printf("Error 1:%d 2:%d\n",er1,er2);
587   
588
589    // Free print context
590    XFreePixmap(dpy,pmap);
591    glXDestroyContext(dpy,pcx);
592    glXDestroyGLXPixmap(dpy,glxpmap);
593   
594    // Restore view in display context
595    SetView();
596   
597  }
598
599}
600
601
602GLXContext G4OpenGLXViewer::create_GL_print_context(XVisualInfo*& pvi) {
603 
604  pvi = glXChooseVisual (dpy,
605                         XDefaultScreen (dpy),
606                         snglBuf_RGBA);
607
608  if (!pvi) {
609    pvi = glXChooseVisual (dpy,
610                           XDefaultScreen (dpy),
611                           dblBuf_RGBA);
612  }
613
614//    GLXFBConfig *fbc;
615//    XVisualInfo *vi;
616//    Colormap cmap;
617//    XSetWindowAttributes swa;
618//    Window win;
619//    GLXContext cx;
620//    GLXWindow gwin;
621//    XEvent event;
622//    int nelements;
623 
624//    /* Find a FBConfig that uses RGBA.  Note that no attribute list is */
625//    /* needed since GLX_RGBA_BIT is a default attribute.               */
626//    fbc = glXChooseFBConfig(dpy,XRootWindow (dpy, pvi->screen), 0, &nelements);
627//    vi = glXGetVisualFromFBConfig(dpy, fbc[0]);
628 
629//    /* Create a GLX context using the first FBConfig in the list. */
630//    return  glXCreateNewContext(dpy, fbc[0], GLX_RGBA_TYPE, 0, GL_FALSE);
631 
632
633 
634  return glXCreateContext (dpy,
635                           pvi,
636                           0,
637                           False);
638}
639
640
641bool G4OpenGLXViewer::grabPixelsX (unsigned int width, unsigned int height,GLenum format,GLubyte* buffer) {
642#ifdef G4DEBUG_VIS_OGL
643  GLint viewport[4];
644  glGetIntegerv(GL_VIEWPORT, viewport);
645  printf("G4OpenGLXViewer::grabPixelsX %d %d     viewport %d %d %d %d\n",width,height,viewport[0],viewport[1],viewport[2],viewport[3]);
646#endif
647         
648  GLint swapbytes, lsbfirst, rowlength;
649  GLint skiprows, skippixels, alignment;
650
651  unsigned int lineSize = 0;
652  if (format == GL_RGB){
653    lineSize = width*3;
654  } else {
655    lineSize = width*1;
656  }
657 
658  GLubyte* lineBuffer = new GLubyte[lineSize];
659  if (lineBuffer == NULL)
660    return false;
661  for (unsigned int y = 0; y<lineSize; y++) {
662    lineBuffer[y] = 0;
663  }
664
665  glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
666  glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
667  glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
668       
669  glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
670  glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
671  glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
672       
673  glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
674  glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
675  glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
676       
677  glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
678  glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
679  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
680       
681  // FIXME L.Garnier 25 03 2009
682  // Try to read at first a block of width by height
683  // But on mac osX 10.5.6 on some window size their is
684  // some stranges effects:
685  // Pixels should came 3 values by 3 values but on border
686  // it seems that with some window size there is a lack of
687  // 1 or 2 values. For example a gray level picture like
688  // (1,1,1) (2,2,2) (3,3,3)
689  // (4,4,4) (5,5,5) (6,6,6)
690  // (7,7,7) (8,8,8) (9,9,9)
691  // appear as (with all buffer values init to 999) :
692  // (1,1,1) (2,2,2) (3,3,3)
693  // (999,999,4) (4,4,5) (5,5,6)
694  // (6,6,999) (999,999,7) (7,7,8)
695  // STRANGE EFFECT....
696
697  // Then we read line by line...and NO problem !
698
699
700  glReadBuffer(GL_FRONT);
701  for (unsigned int i=0;i<height;i++) {
702    glReadPixels (0, i, (GLsizei)width, 1, format, GL_UNSIGNED_BYTE, (GLvoid*) lineBuffer);
703    glXWaitGL (); //Wait for effects of all previous OpenGL commands to
704    //    printf("\n%d ",i);
705    for (unsigned int j=0;j<lineSize;j++) {
706      buffer[j+i*lineSize] = lineBuffer[j];
707      //      printf("%d ",buffer[j]);
708    }
709  }
710  //                 //be propagated before progressing.
711#ifdef G4DEBUG_VIS_OGL
712  printf("G4OpenGLXViewer::GrabPixelX flush\n");
713#endif
714  glFlush ();
715
716  delete [] lineBuffer;
717 
718  glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
719  glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
720  glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
721         
722  glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
723  glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
724  glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
725         
726 
727  return true;
728}
729       
730int G4OpenGLXViewer::generateEPSX (const char* filnam,
731                                  int inColour,
732                                  unsigned int width,
733                                  unsigned int height) {
734       
735  FILE* fp;
736  GLubyte* pixels;
737  GLubyte* curpix;
738  int components;
739
740  GLenum format;
741  int size;
742       
743  if (inColour) {
744    format = GL_RGB;
745    size = width*height*3;
746  } else {
747    format = GL_LUMINANCE;
748    size = width*height*1;
749  }
750       
751  pixels = new GLubyte[size];
752  if (pixels == NULL)
753    return NULL;
754  for (int y = 0; y<size; y++) {
755    pixels[y] = 0;
756  }
757
758       
759#ifdef G4DEBUG_VIS_OGL
760  printf("G4OpenGLXViewer::generateEPSX\n");
761#endif
762 
763
764  if (!grabPixelsX (width, height,format,pixels)) {
765    return 1;
766  }
767#ifdef G4DEBUG_VIS_OGL
768    printf("--\n--\n--\n");
769#endif
770       
771  if (inColour) {
772    components = 3;
773  } else {
774    components = 1;
775  }
776         
777  fp = fopen (filnam, "w");
778  if (fp == NULL) {
779    return 2;
780  }
781         
782  fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
783  fprintf (fp, "%%%%Title: %s\n", filnam);
784  fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
785  fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
786  fprintf (fp, "%%%%EndComments\n");
787  fprintf (fp, "gsave\n");
788  fprintf (fp, "/bwproc {\n");
789  fprintf (fp, "    rgbproc\n");
790  fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
791  fprintf (fp, "    5 -1 roll {\n");
792  fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
793  fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
794  fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
795  fprintf (fp, "    { 2 1 roll } ifelse\n");
796  fprintf (fp, "    }forall\n");
797  fprintf (fp, "    pop pop pop\n");
798  fprintf (fp, "} def\n");
799  fprintf (fp, "systemdict /colorimage known not {\n");
800  fprintf (fp, "   /colorimage {\n");
801  fprintf (fp, "       pop\n");
802  fprintf (fp, "       pop\n");
803  fprintf (fp, "       /rgbproc exch def\n");
804  fprintf (fp, "       { bwproc } image\n");
805  fprintf (fp, "   }  def\n");
806  fprintf (fp, "} if\n");
807  fprintf (fp, "/picstr %d string def\n", width * components);
808  fprintf (fp, "%d %d scale\n", width, height);
809  fprintf (fp, "%d %d %d\n", width, height, 8);
810  fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
811  fprintf (fp, "{currentfile picstr readhexstring pop}\n");
812  fprintf (fp, "false %d\n", components);
813  fprintf (fp, "colorimage\n");
814         
815  curpix = (GLubyte*) pixels;
816  unsigned int pos = 0;
817  for (unsigned int i = width*height*components; i>0; i--) {
818    fprintf (fp, "%02hx ", *(curpix++));
819    if (++pos >= width) {
820      //    if (++pos >= 32) {
821      fprintf (fp, "\n");
822      pos = 0;
823    }
824  }
825  if (pos)
826    fprintf (fp, "\n");
827       
828  fprintf (fp, "grestore\n");
829  fprintf (fp, "showpage\n");
830  delete pixels;
831  fclose (fp);
832
833#ifdef G4DEBUG_VIS_OGL
834  printf("G4OpenGLXViewer::generateEPSX END\n");
835#endif
836
837  return 0;
838}
839       
840
841#endif
Note: See TracBrowser for help on using the repository browser.