xref: /petsc/src/sys/classes/viewer/impls/glvis/glvis.c (revision 11a4995d88c6b984f3abb7b1ba77d48c471e7283)
1 #include <petsc/private/viewerimpl.h> /*I   "petscviewer.h" I*/
2 #include <petsc/private/petscimpl.h>  /*I   "petscsys.h"    I*/
3 #include <petsc/private/glvisviewerimpl.h>
4 
5 /* we may eventually make this function public */
6 static PetscErrorCode PetscViewerASCIISocketOpen(MPI_Comm,const char*,PetscInt,PetscViewer*);
7 
8 struct _n_PetscViewerGLVis {
9   PetscViewerGLVisStatus status;
10   PetscViewerGLVisType   type;                                                  /* either PETSC_VIEWER_GLVIS_DUMP or PETSC_VIEWER_GLVIS_SOCKET */
11   char                   *name;                                                 /* prefix for filename, or hostname, depending on the type */
12   PetscInt               port;                                                  /* used just for the socket case */
13   PetscReal              pause;                                                 /* if positive, calls PetscSleep(pause) after each VecView_GLVis call */
14   PetscViewer            meshwindow;                                            /* used just by the ASCII dumping */
15   PetscObject            dm;                                                    /* DM as passed by PetscViewerGLVisSetDM_Private(): should contain discretization info */
16   PetscInt               nwindow;                                               /* number of windows/fields to be visualized */
17   PetscViewer            *window;
18   char                   **windowtitle;
19   char                   **fec_type;                                            /* type of elements to be used for visualization, see FiniteElementCollection::Name() */
20   PetscErrorCode         (*g2lfield)(PetscObject,PetscInt,PetscObject[],void*); /* global to local operation for generating dofs to be visualized */
21   PetscInt               *locandbs;                                             /* local and block sizes for work vectors */
22   PetscObject            *Ufield;                                               /* work vectors for visualization */
23   PetscInt               snapid;                                                /* snapshot id, use PetscViewerGLVisSetSnapId to change this value*/
24   void                   *userctx;                                              /* User context, used by g2lfield */
25   PetscErrorCode         (*destroyctx)(void*);                                  /* destroy routine for userctx */
26 };
27 typedef struct _n_PetscViewerGLVis *PetscViewerGLVis;
28 
29 /*@
30      PetscViewerGLVisSetSnapId - Set the snapshot id. Only relevant when the viewer is of type PETSC_VIEWER_GLVIS_DUMP
31 
32   Logically Collective on PetscViewer
33 
34   Input Parameters:
35 +  viewer - the PetscViewer
36 -  id     - the current snapshot id in a time-dependent simulation
37 
38   Level: beginner
39 
40 .seealso: PetscViewerGLVisOpen(), PetscViewerCreate(), PetscViewerSetType()
41 @*/
42 PetscErrorCode PetscViewerGLVisSetSnapId(PetscViewer viewer, PetscInt id)
43 {
44   PetscErrorCode ierr;
45 
46   PetscFunctionBegin;
47   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,1);
48   PetscValidLogicalCollectiveInt(viewer,id,2);
49   ierr = PetscTryMethod(viewer,"PetscViewerGLVisSetSnapId_C",(PetscViewer,PetscInt),(viewer,id));CHKERRQ(ierr);
50   PetscFunctionReturn(0);
51 }
52 
53 static PetscErrorCode PetscViewerGLVisSetSnapId_GLVis(PetscViewer viewer, PetscInt id)
54 {
55   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
56 
57   PetscFunctionBegin;
58   socket->snapid = id;;
59   PetscFunctionReturn(0);
60 }
61 
62 /*
63      PetscViewerGLVisSetFields - Sets the required information to visualize different fields from within a vector.
64 
65   Logically Collective on PetscViewer
66 
67   Input Parameters:
68 +  viewer     - the PetscViewer
69 .  nf         - number of fields to be visualized
70 .  namefield  - optional name for each field
71 .  fec_type   - the type of finite element to be used to visualize the data (see FiniteElementCollection::Name() in MFEM)
72 .  nlocal     - array of local sizes for field vectors (can be NULL if nf == 1)
73 .  bs         - array of block sizes for field vectors (can be NULL if nf == 1)
74 .  g2lfields  - User routine to compute the local field vectors to be visualized; PetscObject is used in place of Vec on the prototype
75 .  ctx        - User context to store the relevant data to apply g2lfields
76 -  destroyctx - Destroy function for userctx
77 
78   Notes: g2lfields is called on the Vec V to be visualized, in order to extract the relevant dofs to be put in Vfield[], as
79 .vb
80   g2lfields((PetscObject)V,nfields,(PetscObject*)Vfield[],ctx). Misses Fortran binding
81 .ve
82 
83   Level: intermediate
84 
85 .seealso: PetscViewerGLVisOpen(), PetscViewerCreate(), PetscViewerSetType()
86 */
87 PetscErrorCode PetscViewerGLVisSetFields(PetscViewer viewer, PetscInt nf, const char* namefield[], const char* fec_type[], PetscInt nlocal[], PetscInt bs[], PetscErrorCode(*g2l)(PetscObject,PetscInt,PetscObject[],void*), void* ctx, PetscErrorCode(*destroyctx)(void*))
88 {
89   PetscErrorCode ierr;
90 
91   PetscFunctionBegin;
92   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,1);
93   PetscValidLogicalCollectiveInt(viewer,nf,2);
94   if (namefield) PetscValidPointer(namefield,3);
95   if (!fec_type) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"You need to provide the FiniteElementCollection names for the fields");
96   PetscValidPointer(fec_type,4);
97   if (nf > 1) {
98     PetscValidPointer(nlocal,5);
99     PetscValidPointer(bs,6);
100   }
101   ierr = PetscTryMethod(viewer,"PetscViewerGLVisSetFields_C",(PetscViewer,PetscInt,const char*[],const char*[],PetscInt[],PetscInt[],PetscErrorCode(*)(PetscObject,PetscInt,PetscObject[],void*),void*,PetscErrorCode(*)(void*)),(viewer,nf,namefield,fec_type,nlocal,bs,g2l,ctx,destroyctx));CHKERRQ(ierr);
102   PetscFunctionReturn(0);
103 }
104 
105 static PetscErrorCode PetscViewerGLVisSetFields_GLVis(PetscViewer viewer, PetscInt nfields, const char* namefield[], const char* fec_type[], PetscInt nlocal[], PetscInt bs[], PetscErrorCode(*g2l)(PetscObject,PetscInt,PetscObject[],void*),void* ctx, PetscErrorCode(*destroyctx)(void*))
106 {
107   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
108   PetscInt         i;
109   PetscErrorCode   ierr;
110 
111   PetscFunctionBegin;
112   if (socket->nwindow && socket->nwindow != nfields) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot set number of fields %D with number of windows %D",nfields,socket->nwindow);
113   if (!socket->nwindow) {
114     socket->nwindow = nfields;
115 
116     ierr = PetscCalloc5(nfields,&socket->window,nfields,&socket->windowtitle,nfields,&socket->fec_type,2*nfields,&socket->locandbs,nfields,&socket->Ufield);CHKERRQ(ierr);
117     for (i=0;i<nfields;i++) {
118       if (!namefield || !namefield[i]) {
119         char name[16];
120 
121         ierr = PetscSNPrintf(name,16,"Field%d",i);CHKERRQ(ierr);
122         ierr = PetscStrallocpy(name,&socket->windowtitle[i]);CHKERRQ(ierr);
123       } else {
124         ierr = PetscStrallocpy(namefield[i],&socket->windowtitle[i]);CHKERRQ(ierr);
125       }
126       ierr = PetscStrallocpy(fec_type[i],&socket->fec_type[i]);CHKERRQ(ierr);
127       socket->locandbs[2*i  ] = nlocal[i];
128       socket->locandbs[2*i+1] = bs[i];
129     }
130   }
131   /* number of fields are not allowed to vary */
132   if (nfields != socket->nwindow) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Cannot visualize %D fields using %D socket windows",nfields,socket->nwindow);
133   socket->g2lfield = g2l;
134   if (socket->destroyctx && socket->userctx) { ierr = (*socket->destroyctx)(socket->userctx);CHKERRQ(ierr); }
135   socket->userctx = ctx;
136   socket->destroyctx = destroyctx;
137   PetscFunctionReturn(0);
138 }
139 
140 static PetscErrorCode PetscViewerGLVisInfoDestroy_Private(void *ptr)
141 {
142   PetscViewerGLVisInfo info = (PetscViewerGLVisInfo)ptr;
143   PetscErrorCode       ierr;
144 
145   PetscFunctionBeginUser;
146   ierr = PetscFree(info);CHKERRQ(ierr);
147   PetscFunctionReturn(0);
148 }
149 
150 /* we can decide to prevent specific processes from using the viewer */
151 static PetscErrorCode PetscViewerGLVisAttachInfo_Private(PetscViewer viewer, PetscViewer window)
152 {
153   PetscViewerGLVis     socket = (PetscViewerGLVis)viewer->data;
154   PetscErrorCode       ierr;
155   PetscContainer       container;
156   PetscViewerGLVisInfo info;
157 
158   PetscFunctionBeginUser;
159   ierr = PetscNew(&info);CHKERRQ(ierr);
160   info->enabled = PETSC_TRUE;
161   info->init    = PETSC_FALSE;
162   info->pause   = socket->pause;
163   ierr = PetscContainerCreate(PetscObjectComm((PetscObject)window),&container);CHKERRQ(ierr);
164   ierr = PetscContainerSetPointer(container,(void*)info);CHKERRQ(ierr);
165   ierr = PetscContainerSetUserDestroy(container,PetscViewerGLVisInfoDestroy_Private);CHKERRQ(ierr);
166   ierr = PetscObjectCompose((PetscObject)window,"_glvis_info_container",(PetscObject)container);CHKERRQ(ierr);
167   ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
168   PetscFunctionReturn(0);
169 }
170 
171 static PetscErrorCode PetscViewerGLVisGetNewWindow_Private(PetscViewer viewer,PetscViewer *view)
172 {
173   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
174   PetscViewer      window = NULL;
175   PetscBool        ldis,dis;
176   PetscErrorCode   ierr;
177 
178   PetscFunctionBegin;
179   ierr = PetscViewerASCIISocketOpen(PETSC_COMM_SELF,socket->name,socket->port,&window);
180   /* if we could not estabilish a connection the first time,
181      we disable the socket viewer */
182   ldis = ierr ? PETSC_TRUE : PETSC_FALSE;
183   ierr = MPI_Allreduce(&ldis,&dis,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)viewer));CHKERRQ(ierr);
184   if (dis) {
185     socket->status = PETSCVIEWERGLVIS_DISABLED;
186     ierr  = PetscViewerDestroy(&window);CHKERRQ(ierr);
187   }
188   *view = window;
189   PetscFunctionReturn(0);
190 }
191 
192 PetscErrorCode PetscViewerGLVisPause_Private(PetscViewer viewer)
193 {
194   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
195   PetscErrorCode   ierr;
196 
197   PetscFunctionBegin;
198   if (socket->pause > 0) {
199     ierr = PetscSleep(socket->pause);CHKERRQ(ierr);
200   }
201   PetscFunctionReturn(0);
202 }
203 
204 /* DM specific support */
205 PetscErrorCode PetscViewerGLVisSetDM_Private(PetscViewer viewer, PetscObject dm)
206 {
207   PetscErrorCode   ierr;
208   PetscViewerGLVis socket  = (PetscViewerGLVis)viewer->data;
209 
210   PetscFunctionBegin;
211   if (socket->dm && socket->dm != dm) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Cannot change DM associated with the GLVis viewer");
212   if (!socket->dm) {
213     PetscErrorCode (*setupwithdm)(PetscObject,PetscViewer) = NULL;
214 
215     ierr = PetscObjectQueryFunction(dm,"DMSetUpGLVisViewer_C",&setupwithdm);CHKERRQ(ierr);
216     if (setupwithdm) {
217       ierr = (*setupwithdm)(dm,viewer);CHKERRQ(ierr);
218     } else SETERRQ1(PetscObjectComm(dm),PETSC_ERR_SUP,"No support for DM type %s",dm->type_name);
219     ierr = PetscObjectReference(dm);CHKERRQ(ierr);
220     socket->dm = dm;
221   }
222   PetscFunctionReturn(0);
223 }
224 
225 PetscErrorCode PetscViewerGLVisGetDMWindow_Private(PetscViewer viewer,PetscViewer* view)
226 {
227   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
228   PetscErrorCode   ierr;
229 
230   PetscFunctionBegin;
231   if (!socket->meshwindow) {
232     if (socket->type == PETSC_VIEWER_GLVIS_SOCKET) {
233       ierr = PetscViewerGLVisGetNewWindow_Private(viewer,&socket->meshwindow);CHKERRQ(ierr);
234     } else {
235       PetscMPIInt rank;
236       char        filename[PETSC_MAX_PATH_LEN];
237 
238       ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
239       ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN,"%s-mesh.%06d",socket->name,rank);CHKERRQ(ierr);
240       ierr = PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&socket->meshwindow);CHKERRQ(ierr);
241     }
242     if (socket->meshwindow) {
243       ierr = PetscViewerGLVisAttachInfo_Private(viewer,socket->meshwindow);CHKERRQ(ierr);
244       ierr = PetscViewerPushFormat(socket->meshwindow,PETSC_VIEWER_ASCII_GLVIS);CHKERRQ(ierr);
245     }
246   }
247   *view = socket->meshwindow;
248   PetscFunctionReturn(0);
249 }
250 
251 PetscErrorCode PetscViewerGLVisGetType_Private(PetscViewer viewer,PetscViewerGLVisType *type)
252 {
253   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
254 
255   PetscFunctionBegin;
256   PetscValidPointer(type,2);
257   *type = socket->type;
258   PetscFunctionReturn(0);
259 }
260 
261 /* This function is only relevant in the SOCKET_GLIVS case. The status is computed the first time it is requested, as GLVis currently has issues when connecting the first time through the socket */
262 PetscErrorCode PetscViewerGLVisGetStatus_Private(PetscViewer viewer, PetscViewerGLVisStatus *sockstatus)
263 {
264   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
265 
266   PetscFunctionBegin;
267   PetscValidPointer(sockstatus,2);
268   if (socket->type == PETSC_VIEWER_GLVIS_DUMP) {
269     socket->status = PETSCVIEWERGLVIS_DISCONNECTED;
270   } else if (socket->status == PETSCVIEWERGLVIS_DISCONNECTED && socket->nwindow) {
271     PetscInt       i;
272     PetscBool      lconn,conn;
273     PetscErrorCode ierr;
274 
275     for (i=0,lconn=PETSC_TRUE;i<socket->nwindow;i++)
276       if (!socket->window[i])
277         lconn = PETSC_FALSE;
278 
279     ierr = MPI_Allreduce(&lconn,&conn,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)viewer));CHKERRQ(ierr);
280     if (conn) socket->status = PETSCVIEWERGLVIS_CONNECTED;
281   }
282   *sockstatus = socket->status;
283   PetscFunctionReturn(0);
284 }
285 
286 PetscErrorCode PetscViewerGLVisGetDM_Private(PetscViewer viewer, PetscObject* dm)
287 {
288   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
289 
290   PetscFunctionBegin;
291   *dm = socket->dm;
292   PetscFunctionReturn(0);
293 }
294 
295 PetscErrorCode PetscViewerGLVisGetFields_Private(PetscViewer viewer, PetscInt* nfield, const char** names[], const char **fec[], PetscInt *locandbs[], PetscErrorCode(**g2lfield)(PetscObject,PetscInt,PetscObject[],void*), PetscObject *Ufield[], void **userctx)
296 {
297   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
298 
299   PetscFunctionBegin;
300   if (nfield)   *nfield   = socket->nwindow;
301   if (names)    *names    = (const char**)socket->windowtitle;
302   if (fec)      *fec      = (const char**)socket->fec_type;
303   if (locandbs) *locandbs = socket->locandbs;
304   if (g2lfield) *g2lfield = socket->g2lfield;
305   if (Ufield)   *Ufield   = socket->Ufield;
306   if (userctx)  *userctx  = socket->userctx;
307   PetscFunctionReturn(0);
308 }
309 
310 /* accessor routines for the viewer windows:
311    PETSC_VIEWER_GLVIS_DUMP   : it returns a new viewer every time
312    PETSC_VIEWER_GLVIS_SOCKET : it returns the socket, and creates it if not yet done.
313 */
314 PetscErrorCode PetscViewerGLVisGetWindow_Private(PetscViewer viewer,PetscInt wid,PetscViewer* view)
315 {
316   PetscViewerGLVis       socket = (PetscViewerGLVis)viewer->data;
317   PetscViewerGLVisStatus status;
318   PetscErrorCode         ierr;
319 
320   PetscFunctionBegin;
321   PetscValidLogicalCollectiveInt(viewer,wid,2);
322   PetscValidPointer(view,3);
323   if (wid < 0 || wid > socket->nwindow-1) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot get window id %D: allowed range [0,%D)",wid,socket->nwindow-1);
324   status = socket->status;
325   if (socket->type == PETSC_VIEWER_GLVIS_DUMP && socket->window[wid]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_USER,"Window %D is already in use",wid);
326   switch (status) {
327     case PETSCVIEWERGLVIS_DISCONNECTED:
328       if (socket->window[wid]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"This should not happen");
329       if (socket->type == PETSC_VIEWER_GLVIS_DUMP) {
330         PetscMPIInt rank;
331         char        filename[PETSC_MAX_PATH_LEN];
332 
333         ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
334         ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN,"%s-%s-%d.%06d",socket->name,socket->windowtitle[wid],socket->snapid,rank);CHKERRQ(ierr);
335         ierr = PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&socket->window[wid]);CHKERRQ(ierr);
336       } else {
337         ierr = PetscViewerGLVisGetNewWindow_Private(viewer,&socket->window[wid]);CHKERRQ(ierr);
338       }
339       if (socket->window[wid]) {
340         ierr = PetscViewerGLVisAttachInfo_Private(viewer,socket->window[wid]);CHKERRQ(ierr);
341         ierr = PetscViewerPushFormat(socket->window[wid],PETSC_VIEWER_ASCII_GLVIS);CHKERRQ(ierr);
342       }
343       *view = socket->window[wid];
344       break;
345     case PETSCVIEWERGLVIS_CONNECTED:
346       *view = socket->window[wid];
347       break;
348     case PETSCVIEWERGLVIS_DISABLED:
349       *view = NULL;
350       break;
351     default:
352       SETERRQ1(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Unhandled socket status %d\n",(int)status);
353       break;
354   }
355   PetscFunctionReturn(0);
356 }
357 
358 /* Restore the window viewer
359    PETSC_VIEWER_GLVIS_DUMP  : destroys the temporary created ASCII viewer used for dumping
360    PETSC_VIEWER_GLVIS_SOCKET: - if the returned window viewer is not NULL, just zeros the pointer.
361                  - it the returned window viewer is NULL, assumes something went wrong
362                    with the socket (i.e. SIGPIPE when a user closes the popup window)
363                    and that the caller already handled it (see VecView_GLVis).
364 */
365 PetscErrorCode PetscViewerGLVisRestoreWindow_Private(PetscViewer viewer,PetscInt wid, PetscViewer* view)
366 {
367   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
368   PetscErrorCode   ierr;
369 
370   PetscFunctionBegin;
371   PetscValidLogicalCollectiveInt(viewer,wid,2);
372   PetscValidPointer(view,3);
373   if (wid < 0 || wid > socket->nwindow-1) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot restore window id %D: allowed range [0,%D)",wid,socket->nwindow);
374   if (*view && *view != socket->window[wid]) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Viewer was not obtained from PetscViewerGLVisGetWindow");
375   if (*view) {
376     ierr = PetscViewerFlush(*view);CHKERRQ(ierr);
377     ierr = PetscBarrier((PetscObject)viewer);CHKERRQ(ierr);
378   }
379   if (socket->type == PETSC_VIEWER_GLVIS_DUMP) { /* destroy the viewer, as it is associated with a single time step */
380     ierr = PetscViewerDestroy(&socket->window[wid]);CHKERRQ(ierr);
381   } else if (!*view) { /* something went wrong (SIGPIPE) so we just zero the private pointer */
382     socket->window[wid] = NULL;
383   }
384   *view = NULL;
385   PetscFunctionReturn(0);
386 }
387 
388 /* default window appearance in the PETSC_VIEWER_GLVIS_SOCKET case */
389 PetscErrorCode PetscViewerGLVisInitWindow_Private(PetscViewer viewer, PetscBool mesh, PetscInt dim, const char *name)
390 {
391   PetscErrorCode       ierr;
392   PetscViewerGLVisInfo info;
393   PetscContainer       container;
394 
395   PetscFunctionBegin;
396   ierr = PetscObjectQuery((PetscObject)viewer,"_glvis_info_container",(PetscObject*)&container);CHKERRQ(ierr);
397   if (!container) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Viewer was not obtained from PetscGLVisViewerGetNewWindow_Private");
398   ierr = PetscContainerGetPointer(container,(void**)&info);CHKERRQ(ierr);
399   if (info->init) {
400     if (info->pause < 0) {
401       ierr = PetscViewerASCIIPrintf(viewer,"pause\n");CHKERRQ(ierr); /* pause */
402     }
403     PetscFunctionReturn(0);
404   }
405   ierr = PetscViewerASCIIPrintf(viewer,"window_size 800 800\n");CHKERRQ(ierr);
406   if (name) {
407     ierr = PetscViewerASCIIPrintf(viewer,"window_title '%s'\n",name);CHKERRQ(ierr);
408   }
409   if (mesh) {
410     switch (dim) {
411     case 1:
412       break;
413     case 2:
414       ierr = PetscViewerASCIIPrintf(viewer,"keys cmeeppppp\n");CHKERRQ(ierr); /* show colorbar, mesh and ranks */
415       break;
416     case 3: /* TODO: decide default view in 3D */
417       break;
418     }
419   } else {
420     ierr = PetscViewerASCIIPrintf(viewer,"keys cm\n");CHKERRQ(ierr); /* show colorbar and mesh */
421     switch (dim) {
422     case 1:
423       ierr = PetscViewerASCIIPrintf(viewer,"keys RRj\n");CHKERRQ(ierr); /* set to 1D (side view) and turn off perspective */
424       break;
425     case 2:
426       ierr = PetscViewerASCIIPrintf(viewer,"keys Rjl\n");CHKERRQ(ierr); /* set to 2D (top view), turn off perspective and light */
427       break;
428     case 3:
429       break;
430     }
431     ierr = PetscViewerASCIIPrintf(viewer,"autoscale value\n");CHKERRQ(ierr); /* update value-range; keep mesh-extents fixed */
432     if (info->pause == 0) {
433       ierr = PetscViewerASCIIPrintf(viewer,"pause\n");CHKERRQ(ierr); /* pause */
434     }
435   }
436   info->init = PETSC_TRUE;
437   PetscFunctionReturn(0);
438 }
439 
440 static PetscErrorCode PetscViewerDestroy_GLVis(PetscViewer viewer)
441 {
442   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
443   PetscInt         i;
444   PetscErrorCode   ierr;
445 
446   PetscFunctionBegin;
447   for (i=0;i<socket->nwindow;i++) {
448     ierr = PetscViewerDestroy(&socket->window[i]);CHKERRQ(ierr);
449     ierr = PetscFree(socket->windowtitle[i]);CHKERRQ(ierr);
450     ierr = PetscFree(socket->fec_type[i]);CHKERRQ(ierr);
451     ierr = PetscObjectDestroy(&socket->Ufield[i]);CHKERRQ(ierr);
452   }
453   ierr = PetscFree(socket->name);CHKERRQ(ierr);
454   ierr = PetscFree5(socket->window,socket->windowtitle,socket->fec_type,socket->locandbs,socket->Ufield);CHKERRQ(ierr);
455   ierr = PetscViewerDestroy(&socket->meshwindow);CHKERRQ(ierr);
456   ierr = PetscObjectDestroy(&socket->dm);CHKERRQ(ierr);
457   if (socket->destroyctx && socket->userctx) { ierr = (*socket->destroyctx)(socket->userctx);CHKERRQ(ierr); }
458 
459   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetSnapId_C",NULL);CHKERRQ(ierr);
460   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetFields_C",NULL);CHKERRQ(ierr);
461   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerFileSetName_C",NULL);CHKERRQ(ierr);
462   ierr = PetscFree(socket);CHKERRQ(ierr);
463   viewer->data = NULL;
464   PetscFunctionReturn(0);
465 }
466 
467 static PetscErrorCode PetscViewerSetFromOptions_GLVis(PetscOptionItems *PetscOptionsObject,PetscViewer v)
468 {
469   PetscErrorCode   ierr;
470   PetscViewerGLVis socket = (PetscViewerGLVis)v->data;
471 
472   PetscFunctionBegin;
473   ierr = PetscOptionsHead(PetscOptionsObject,"GLVis PetscViewer Options");CHKERRQ(ierr);
474   ierr = PetscOptionsReal("-viewer_glvis_pause","-1 to pause after each visualization, otherwise sleeps for given seconds",NULL,socket->pause,&socket->pause,NULL);CHKERRQ(ierr);
475   ierr = PetscOptionsTail();CHKERRQ(ierr);
476   PetscFunctionReturn(0);
477 }
478 
479 static PetscErrorCode PetscViewerSetFileName_GLVis(PetscViewer viewer, const char name[])
480 {
481   char             *sport;
482   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
483   PetscErrorCode   ierr;
484 
485   PetscFunctionBegin;
486   socket->type = PETSC_VIEWER_GLVIS_DUMP;
487   /* we accept localhost^port */
488   ierr = PetscFree(socket->name);CHKERRQ(ierr);
489   ierr = PetscStrallocpy(name,&socket->name);CHKERRQ(ierr);
490   ierr = PetscStrchr(socket->name,'^',&sport);CHKERRQ(ierr);
491   if (sport) {
492     PetscInt port = 19916;
493     size_t   len;
494 
495     *sport++ = 0;
496     ierr = PetscStrlen(sport,&len);CHKERRQ(ierr);
497     if (len) ierr = PetscOptionsStringToInt(sport,&port);
498     if (!ierr) {
499       socket->port = (port != PETSC_DECIDE && port != PETSC_DEFAULT) ? port : 19916;
500     } else {
501       socket->port = 19916;
502     }
503     socket->type = PETSC_VIEWER_GLVIS_SOCKET;
504   }
505   PetscFunctionReturn(0);
506 }
507 
508 /*
509      PetscViewerGLVisOpen - Opens a GLVis type viewer
510 
511   Collective on comm
512 
513   Input Parameters:
514 +  comm      - the MPI communicator
515 .  type      - the viewer type: PETSC_VIEWER_GLVIS_SOCKET for real-time visualization or PETSC_VIEWER_GLVIS_DUMP for dumping to disk
516 .  name      - either the hostname where the GLVis server is running or the base filename for dumping the data for subsequent visualizations
517 -  port      - socket port where the GLVis server is listening. Not referenced when type is PETSC_VIEWER_GLVIS_DUMP
518 
519   Output Parameters:
520 -  viewer    - the PetscViewer object
521 
522   Notes: misses Fortran binding
523 
524   Level: beginner
525 
526 .seealso: PetscViewerCreate(), PetscViewerSetType(), PetscViewerGLVisType
527 */
528 PETSC_EXTERN PetscErrorCode PetscViewerGLVisOpen(MPI_Comm comm, PetscViewerGLVisType type, const char* name, PetscInt port, PetscViewer* viewer)
529 {
530   PetscViewerGLVis socket;
531   PetscErrorCode   ierr;
532 
533   PetscFunctionBegin;
534   ierr = PetscViewerCreate(comm,viewer);CHKERRQ(ierr);
535   ierr = PetscViewerSetType(*viewer,PETSCVIEWERGLVIS);CHKERRQ(ierr);
536 
537   socket       = (PetscViewerGLVis)((*viewer)->data);
538   ierr         = PetscFree(socket->name);
539   ierr         = PetscStrallocpy(name,&socket->name);CHKERRQ(ierr);
540   socket->type = type;
541   socket->port = port;
542 
543   ierr = PetscViewerSetFromOptions(*viewer);CHKERRQ(ierr);
544   PetscFunctionReturn(0);
545 }
546 
547 /*
548   PETSC_VIEWER_GLVIS_ - Creates an GLVIS PetscViewer shared by all processors in a communicator.
549 
550   Collective on MPI_Comm
551 
552   Input Parameter:
553 . comm - the MPI communicator to share the GLVIS PetscViewer
554 
555   Level: intermediate
556 
557   Notes: misses Fortran bindings
558 
559   Environmental variables:
560 + PETSC_VIEWER_GLVIS_FILENAME : output filename (if specified dump to disk, and takes precedence on PETSC_VIEWER_GLVIS_HOSTNAME)
561 . PETSC_VIEWER_GLVIS_HOSTNAME : machine where the GLVis server is listening (defaults to localhost)
562 - PETSC_VIEWER_GLVIS_PORT     : port opened by the GLVis server (defaults to 19916)
563 
564   Notes:
565   Unlike almost all other PETSc routines, PETSC_VIEWER_GLVIS_ does not return
566   an error code.  The GLVIS PetscViewer is usually used in the form
567 $       XXXView(XXX object, PETSC_VIEWER_GLVIS_(comm));
568 
569 .seealso: PetscViewerGLVISOpen(), PetscViewerGLVisType, PetscViewerCreate(), PetscViewerDestroy()
570 */
571 PETSC_EXTERN PetscViewer PETSC_VIEWER_GLVIS_(MPI_Comm comm)
572 {
573   PetscErrorCode       ierr;
574   PetscBool            flg;
575   PetscViewer          viewer;
576   PetscViewerGLVisType type;
577   char                 fname[PETSC_MAX_PATH_LEN],sport[16];
578   PetscInt             port = 19916; /* default for GLVis */
579 
580   PetscFunctionBegin;
581   ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_FILENAME",fname,PETSC_MAX_PATH_LEN,&flg);
582   if (!flg) {
583     type = PETSC_VIEWER_GLVIS_SOCKET;
584     ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_HOSTNAME",fname,PETSC_MAX_PATH_LEN,&flg);
585     if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
586     if (!flg) {
587       ierr = PetscStrcpy(fname,"localhost");
588       if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
589     }
590     ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_PORT",sport,16,&flg);
591     if (flg) {
592       ierr = PetscOptionsStringToInt(sport,&port);
593       if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
594     }
595   } else {
596     type = PETSC_VIEWER_GLVIS_DUMP;
597   }
598   ierr = PetscViewerGLVisOpen(comm,type,fname,port,&viewer);
599   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
600   ierr = PetscObjectRegisterDestroy((PetscObject)viewer);
601   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
602   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
603   PetscFunctionReturn(viewer);
604 }
605 
606 PETSC_EXTERN PetscErrorCode PetscViewerCreate_GLVis(PetscViewer viewer)
607 {
608   PetscViewerGLVis socket;
609   PetscErrorCode   ierr;
610 
611   PetscFunctionBegin;
612   ierr = PetscNewLog(viewer,&socket);CHKERRQ(ierr);
613 
614   /* defaults to socket viewer */
615   ierr = PetscStrallocpy("localhost",&socket->name);CHKERRQ(ierr);
616   socket->port  = 19916; /* GLVis default listening port */
617   socket->type  = PETSC_VIEWER_GLVIS_SOCKET;
618   socket->pause = 0; /* just pause the first time */
619 
620   viewer->data                = (void*)socket;
621   viewer->ops->destroy        = PetscViewerDestroy_GLVis;
622   viewer->ops->setfromoptions = PetscViewerSetFromOptions_GLVis;
623 
624   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetSnapId_C",PetscViewerGLVisSetSnapId_GLVis);CHKERRQ(ierr);
625   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetFields_C",PetscViewerGLVisSetFields_GLVis);CHKERRQ(ierr);
626   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerFileSetName_C",PetscViewerSetFileName_GLVis);CHKERRQ(ierr);
627   PetscFunctionReturn(0);
628 }
629 
630 /* this is a private implementation of a SOCKET with ASCII data format
631    GLVis does not currently handle binary socket streams */
632 #include <petsc/private/viewerimpl.h>
633 
634 #if defined(PETSC_HAVE_UNISTD_H)
635 #include <unistd.h>
636 #endif
637 
638 static PetscErrorCode (*PetscViewerDestroy_ASCII)(PetscViewer);
639 
640 static PetscErrorCode PetscViewerDestroy_ASCII_Socket(PetscViewer viewer)
641 {
642   FILE *stream;
643   PetscErrorCode ierr = 0;
644   PetscFunctionBegin;
645   ierr = PetscViewerASCIIGetPointer(viewer,&stream);CHKERRQ(ierr);
646   if (stream) {
647     ierr = fclose(stream);
648     if (ierr) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on stream");
649   }
650   ierr = PetscViewerDestroy_ASCII(viewer);CHKERRQ(ierr);
651   PetscFunctionReturn(0);
652 }
653 
654 #include <stdio.h>
655 
656 static PetscErrorCode PetscViewerASCIISocketOpen(MPI_Comm comm,const char* hostname,PetscInt port,PetscViewer* viewer)
657 {
658   FILE           *stream = NULL;
659   int            fd;
660   PetscErrorCode ierr;
661 
662   PetscFunctionBegin;
663   PetscValidPointer(hostname,2);
664   PetscValidPointer(viewer,4);
665   ierr = PetscOpenSocket(hostname,port,&fd);
666   if (ierr) {
667     PetscInt sierr = ierr;
668     char     err[1024];
669 
670     ierr    = PetscSNPrintf(err,1024,"Cannot connect to socket on %s:%D. Socket visualization is disabled\n",hostname,port);CHKERRQ(ierr);
671     ierr    = PetscInfo(NULL,err);CHKERRQ(ierr);
672     *viewer = NULL;
673     PetscFunctionReturn(sierr);
674   } else {
675     char msg[1024];
676 
677     ierr = PetscSNPrintf(msg,1024,"Successfully connect to socket on %s:%D. Socket visualization is enabled\n",hostname,port);CHKERRQ(ierr);
678     ierr = PetscInfo(NULL,msg);CHKERRQ(ierr);
679   }
680   stream = fdopen(fd,"w"); /* Not possible on Windows */
681   if (!stream) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SYS,"Cannot open stream from socket %s:%d",hostname,port);
682   ierr = PetscViewerASCIIOpenWithFILE(PETSC_COMM_SELF,stream,viewer);CHKERRQ(ierr);
683   PetscViewerDestroy_ASCII = (*viewer)->ops->destroy;
684   (*viewer)->ops->destroy = PetscViewerDestroy_ASCII_Socket;
685   PetscFunctionReturn(0);
686 }
687