Debian Codegraph @

apps/tools/ivview/ivview.c++

raw
1 /*
2 *
3 * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * Further, this software is distributed without any warranty that it is
16 * free of the rightful claim of any third person regarding infringement
17 * or the like. Any license provided herein, whether implied or
18 * otherwise, applies only to this software file. Patent licenses, if
19 * any, provided herein do not apply to combinations of this program with
20 * other software, or any other product whatsoever.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 *
26 * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
27 * Mountain View, CA 94043, or:
28 *
29 * http://www.sgi.com
30 *
31 * For further information regarding this notice, see:
32 *
33 * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
34 *
35 */
36
37 #include <cstdio>
38 #include <cstdlib>
39 #include <cstring>
40 #include <unistd.h>
41 #ifdef __sgi
42 #include <alloca.h>
43 #endif
44 #include <assert.h>
45 #include <locale.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <Inventor/SoDB.h>
49 #include <Inventor/SoInput.h>
50 #include <Inventor/Xt/SoXt.h>
51 #include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
52 #include <Inventor/Xt/viewers/SoXtWalkViewer.h>
53 #include <Inventor/actions/SoCallbackAction.h>
54 #include <Inventor/actions/SoWriteAction.h>
55 #include <Inventor/elements/SoCacheElement.h>
56 #include <Inventor/nodes/SoCallback.h>
57 #include <Inventor/nodes/SoFont.h>
58 #include <Inventor/nodes/SoOrthographicCamera.h>
59 #include <Inventor/nodes/SoShape.h>
60 #include <Inventor/nodes/SoSeparator.h>
61 #include <Inventor/nodes/SoText2.h>
62 #include <Inventor/sensors/SoTimerSensor.h>
63
64 #include "../../samples/widgets/MyColorEditor.h"
65 #include "ivviewMenus.h"
66
67 #define SCREEN(w) XScreenNumberOfScreen(XtScreen(w))
68
69 typedef struct {
70 int count; // Number of files read
71 char **names; // File names
72 SoNode *original; // Un-munged scene
73 SoSeparator *optimized; // Optimized scene
74 SoSeparator *ivfixed; // Ivfixed scene
75 } FileInfo;
76
77 // Function prototypes
78 static void print_usage(const char *);
79 static void parse_args(int , char **);
80 static SbBool readScene(FileInfo &); // Returns TRUE if error
81 static void initPerfMeter(SoXtViewer *);
82 static void viewStartCB(void *, SoXtViewer *);
83 static void setBusyCursor(SbBool);
84 static void createBusyCursor(Display *);
85 static void overlayViewportCB(void *, SoAction *);
86 static void countUpdatesCB(void *, SoAction *);
87 static void perfSensorCB(void *, SoSensor *);
88 static void showAboutDialog();
89 static void getNewScene();
90 static void optimizationChanged(FileInfo &, SbBool);
91 static void newSceneCB(Widget, void *, XmFileSelectionBoxCallbackStruct *);
92 static void editBackgroundColor();
93 static void backgroundColorCB(void *, const SbColor *);
94 static void processTopbarEvent(Widget, ivMenuItem *, XmAnyCallbackStruct *);
95 static Widget buildAndLayoutMenus(Widget );
96 static SoXtViewer *buildAndLayoutViewer(Widget , Widget, SbBool);
97 static SoSeparator *addUpdateCounter(SoNode *);
98 static int countTriangles(SoNode *);
99 static void countTriangleCB(void *, SoCallbackAction *,
100 const SoPrimitiveVertex *, const SoPrimitiveVertex *,
101 const SoPrimitiveVertex *);
102
103 // Global variables
104 static SoXtViewer *viewer = NULL;
105 static Widget shell = NULL;
106 static SbBool useWalkViewer = FALSE;
107 static FileInfo files = { 0, NULL, NULL, NULL, NULL };
108 static SbBool showPerfMeter = FALSE;
109 static int numTris = 0;
110 static int numFramesRendered = 0;
111 static SbBool ivfix = FALSE;
112 static SbBool shapeHintBackface = FALSE;
113
114 // Definitions for busy cursor:
115 static Cursor busyCursor = 0;
116 #define hourglass_width 17
117 #define hourglass_height 21
118 #define hourglass_x_hot 8
119 #define hourglass_y_hot 11
120 static char hourglass_bits[] = {
121 0x00, 0x00, 0x00, 0xfe, 0xff, 0x00, 0x04, 0x40, 0x00, 0x04, 0x40, 0x00,
122 0x04, 0x40, 0x00, 0xe8, 0x2e, 0x00, 0xd0, 0x17, 0x00, 0xa0, 0x0b, 0x00,
123 0x40, 0x05, 0x00, 0x40, 0x05, 0x00, 0x40, 0x04, 0x00, 0x40, 0x04, 0x00,
124 0x40, 0x04, 0x00, 0x20, 0x09, 0x00, 0x10, 0x11, 0x00, 0x88, 0x23, 0x00,
125 0xc4, 0x47, 0x00, 0xe4, 0x4f, 0x00, 0xf4, 0x5f, 0x00, 0xfe, 0xff, 0x00,
126 0x00, 0x00, 0x00};
127
128 static char hourglass_mask_bits[] = {
129 0xff, 0xff, 0x01, 0xff, 0xff, 0x01, 0xfe, 0xff, 0x00, 0xfe, 0xff, 0x00,
130 0xfe, 0xff, 0x00, 0xfc, 0x7f, 0x00, 0xf8, 0x3f, 0x00, 0xf0, 0x1f, 0x00,
131 0xe0, 0x0f, 0x00, 0xe0, 0x0f, 0x00, 0xe0, 0x0f, 0x00, 0xe0, 0x0f, 0x00,
132 0xe0, 0x0f, 0x00, 0xf0, 0x1f, 0x00, 0xf8, 0x3f, 0x00, 0xfc, 0x7f, 0x00,
133 0xfe, 0xff, 0x00, 0xfe, 0xff, 0x00, 0xfe, 0xff, 0x00, 0xff, 0xff, 0x01,
134 0xff, 0xff, 0x01};
135
136 //////////////////////////////////////////////////////////////////////
137 //
138 // Print the help message
139 //
140 static void
141 print_usage(const char *progname)
142 {
143 fprintf(stderr, "Usage: %s [-hpw] [infiles]\n", progname);
144 fprintf(stderr,
145 "\t-h : Print this message (help) and exit\n"
146 "\t-p : Enable performance meter\n"
147 "\t-w : Use walk viewer (examiner viewer is default)\n"
148 );
149
150 exit(99);
151 }
152
153 /////////////////////////////////////////////////////////////////////
154 //
155 // Parse the command line arguments
156 //
157 static void
158 parse_args(int argc, char **argv)
159 {
160 int err = FALSE; // Flag: error in options?
161 int c;
162
163 showPerfMeter = FALSE;
164
165 while ((c = getopt(argc, argv, "hpqw")) != -1) {
166 switch(c) {
167 case 'h': // Help
168 err = TRUE;
169 break;
170 case 'p':
171 showPerfMeter = TRUE;
172 break;
173 case 'q':
174 // no-op for backward compatibility only
175 break;
176 case 'w':
177 useWalkViewer = TRUE;
178 break;
179 default:
180 err = TRUE;
181 break;
182 }
183 }
184
185 // Can't handle -pw, at least right now:
186 if (showPerfMeter && useWalkViewer) {
187 fprintf(stderr, "Sorry, can't show performance when using "
188 "walk viewer. Ignoring -p option\n");
189 showPerfMeter = FALSE;
190 }
191
192 /* Handle multiple filenames */
193 if (optind == argc) {
194 // Act like one argument "-" was given
195 argc++;
196 argv[optind] = "-";
197 }
198
199 files.count = argc - optind;
200 files.names = (char **) malloc (files.count * sizeof(char *));
201 for (int i=0; i<files.count; i++, optind++)
202 files.names[i] = argv[optind];
203
204 if (err)
205 print_usage(argv[0]);
206 }
207
208
209 /////////////////////////////////////////////////////////////////////
210 //
211 // Read the scene from the file(s).
212 // If there are multiple files, combine their contents under one separator.
213 // Returns TRUE if read was OK, FALSE if read error.
214 //
215 static SbBool
216 readScene(FileInfo &files)
217 {
218 SoInput in;
219 SoSeparator *root;
220
221 if (files.count == 0)
222 return 0;
223
224 // Watch out! There's a hidden dependence here between this code
225 // and the code in the optimizationChanged routine that runs files
226 // through ivfix. In particular, the optimizationChanged code
227 // assumes that, if stdin is being read from, that no other
228 // filenames are given.
229 if (files.count==1 && strcmp(files.names[0], "-")==0) {
230 // Read from stdin
231 if (isatty(fileno(stdin))) {
232 fprintf(stderr, "Trying to read from standard input, ");
233 fprintf(stderr, "but standard input is a tty!\n");
234 return 0;
235 }
236 else
237 in.setFilePointer(stdin);
238
239 root = SoDB::readAll(&in);
240 if (root == NULL)
241 fprintf(stderr, "Error reading file %s\n", files.names[0]);
242 else
243 root->ref();
244
245 // SoInput destructor automatically closes file.
246 }
247 else { // Not reading from stdin:
248 root = new SoSeparator;
249 root->ref();
250
251 //
252 // Combine all the files under one separator
253 //
254 for (int i=0; i<files.count; i++) {
255 if (!in.openFile(files.names[i])) {
256 root->unref();
257 return 0;
258 }
259 SoSeparator *inputRoot = SoDB::readAll(&in);
260 if (inputRoot == NULL) {
261 root->unref();
262 return 0;
263 }
264 root->addChild(inputRoot);
265 in.closeFile();
266 }
267 }
268
269 if (root && showPerfMeter) {
270 SoSeparator *oldRoot = root;
271 root = addUpdateCounter(oldRoot);
272 root->ref();
273 oldRoot->unref();
274 numTris = countTriangles(root);
275 }
276
277 // Nuke old scene(s):
278 if (files.original) {
279 files.original->unref();
280 files.original = NULL;
281 }
282 if (files.optimized) {
283 files.optimized->unref();
284 files.optimized = NULL;
285 }
286 if (files.ivfixed) {
287 files.ivfixed->unref();
288 files.ivfixed = NULL;
289 }
290
291 // And create new ones:
292 if (root) {
293 files.original = root;
294 optimizationChanged(files, FALSE);
295 }
296
297 return (root != NULL);
298 }
299
300 /////////////////////////////////////////////////////////////////////
301 //
302 // Called when optimization options change, or when a new file is
303 // read.
304 //
305 static void
306 optimizationChanged(FileInfo &files, SbBool maintainCamera)
307 {
308 // If no original file, have nothing to do:
309 if (files.original == NULL) return;
310
311 // We'll recreate the optimized graph:
312 if (files.optimized) {
313 files.optimized->unref();
314 files.optimized = NULL;
315 }
316 if (ivfix) {
317 SbBool err = FALSE;
318 char *tempFile = NULL;
319 setBusyCursor(TRUE);
320
321 if (files.ivfixed == NULL) do {
322
323 // First, special case-- read from stdin:
324 if (files.count==1 && strcmp(files.names[0], "-")==0) {
325 tempFile = tempnam(NULL, "ivfix");
326 if (tempFile == NULL) {
327 err = 1;
328 break;
329 }
330 //
331 // Run ivfix on the original scene
332 //
333
334 // String long enough for temp filename plus "ivfix >"
335 char ivfixCommand[L_tmpnam + 10];
336 sprintf(ivfixCommand, "ivfix > %s", tempFile);
337 FILE *ivfixPipe = popen(ivfixCommand, "w");
338 if (ivfixPipe == NULL) {
339 err = TRUE;
340 break;
341 }
342
343 // Write to ivfix through pipe:
344 SoOutput out;
345 out.setBinary(TRUE);
346 out.setFilePointer(ivfixPipe);
347 SoWriteAction wa(&out);
348 wa.apply(files.original);
349 if (ferror(ivfixPipe)) {
350 err = TRUE;
351 break;
352 }
353 pclose(ivfixPipe);
354
355 // Now read tempFile:
356 SoInput in;
357 if (!in.openFile(tempFile)) {
358 err = TRUE;
359 break;
360 }
361 files.ivfixed = SoDB::readAll(&in);
362 if (files.ivfixed == NULL) {
363 err = TRUE;
364 break;
365 } else {
366 files.ivfixed->ref();
367 }
368 in.closeFile();
369 }
370 else { // Not reading from stdin:
371 files.ivfixed = new SoSeparator;
372 files.ivfixed->ref();
373 for (int i = 0; i < files.count; i++) {
374 const char *filename = files.names[i];
375 char *ivfixCommand = (char *)
376 alloca(strlen("ivfix ")+strlen(filename)+1);
377 sprintf(ivfixCommand, "ivfix %s", filename);
378
379 // Read from ivfix:
380 FILE *ivfixPipe = popen(ivfixCommand, "r");
381 if (ivfixPipe == NULL) {
382 files.ivfixed->unref();
383 files.ivfixed = NULL;
384 err = TRUE;
385 break;
386 }
387
388 // If the filename includes a directory path, add
389 // the directory name to the list of directories
390 // where to look for input files:
391 const char *slashPtr;
392 char *searchPath = NULL;
393 if ((slashPtr = strrchr(filename, '/')) != NULL) {
394 searchPath = strdup(filename);
395 searchPath[slashPtr - filename] = '\0';
396 SoInput::addDirectoryFirst(searchPath);
397 }
398
399 SoInput in;
400 in.setFilePointer(ivfixPipe);
401 SoSeparator *root = SoDB::readAll(&in);
402
403 if (searchPath) {
404 SoInput::removeDirectory(searchPath);
405 free(searchPath);
406 }
407
408 if (root == NULL) {
409 files.ivfixed->unref();
410 files.ivfixed = NULL;
411 err = TRUE;
412 break;
413 }
414 files.ivfixed->addChild(root);
415
416 pclose(ivfixPipe);
417 }
418 }
419
420 if (showPerfMeter) {
421 SoNode *oldRoot = files.ivfixed;
422 files.ivfixed = addUpdateCounter(oldRoot);
423 files.ivfixed->ref();
424 oldRoot->unref();
425 numTris = countTriangles(files.ivfixed);
426 }
427 } while (0);
428
429 if (files.ivfixed) {
430 files.optimized = files.ivfixed;
431 files.optimized->ref();
432 }
433
434 setBusyCursor(FALSE);
435
436 // Clean up temporary file (whether or not there was an error):
437 if (tempFile && unlink(tempFile) < 0) {
438 fprintf(stderr, "Warning: Error removing %s after ivfix\n",
439 tempFile);
440 }
441 if (tempFile) free(tempFile);
442
443 // If there was an error:
444 if (err) {
445 system("xmessage 'Error running ivfix' > /dev/null");
446 }
447 }
448
449 if (shapeHintBackface) {
450 SoSeparator *optRoot = new SoSeparator;
451 optRoot->renderCaching = SoSeparator::OFF;
452 optRoot->boundingBoxCaching = SoSeparator::OFF;
453 optRoot->pickCulling = SoSeparator::OFF;
454
455 if (files.optimized != NULL) {
456 // user also wants ivfix....
457 optRoot->addChild(files.ivfixed);
458 files.optimized->unref();
459 files.optimized = NULL;
460 } else {
461 optRoot->addChild(files.original);
462 }
463 files.optimized = optRoot;
464 files.optimized->ref();
465
466 // Insert a ShapeHints node as the first child of files.optimized
467 SoShapeHints *hints = new SoShapeHints;
468 hints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE;
469 hints->shapeType = SoShapeHints::SOLID;
470 hints->setOverride(TRUE);
471 files.optimized->insertChild(hints, 0);
472 }
473
474 //
475 // Set scene graph to either optimized or original scene graph:
476 //
477 SoNode *currentCamera = NULL;
478 if (maintainCamera) {
479 SoNode *viewerCamera = viewer->getCamera();
480 if (viewerCamera) {
481 // Make a copy:
482 currentCamera = viewerCamera->copy(FALSE);
483 currentCamera->ref();
484 }
485 }
486
487 if (files.optimized) {
488 // optimized AND/OR ivfixed
489 if (viewer->getSceneGraph() != files.optimized)
490 viewer->setSceneGraph(files.optimized);
491 } else {
492 if (viewer->getSceneGraph() != files.original) {
493 viewer->setSceneGraph(files.original);
494 }
495 }
496 if (currentCamera) {
497 SoNode *viewerCamera = viewer->getCamera();
498 if (viewerCamera) {
499 // Copy back:
500 viewerCamera->copyFieldValues(currentCamera, FALSE);
501 }
502 currentCamera->unref();
503 }
504 }
505
506 ////////////////////////////////////////////////////////////////////
507 //
508 // Initialize the performance meter in the overlay planes
509 //
510 static void
511 initPerfMeter(SoXtViewer *vwr)
512 {
513 //
514 // Create the overlay scene
515 //
516 SoSeparator *perfMeter = new SoSeparator;
517
518 // Add a callback node which will set the viewport
519 SoCallback *overlayCB = new SoCallback;
520 overlayCB->setCallback(overlayViewportCB);
521 perfMeter->addChild(overlayCB);
522
523 // Add an orthographic camera
524 perfMeter->addChild(new SoOrthographicCamera());
525
526 // Add the text string to display the tris per second
527 char str[150];
528 SoFont *perfMeterFont = new SoFont;
529 perfMeterFont->size = 18;
530 perfMeterFont->name = "Helvetica";
531 perfMeter->addChild(perfMeterFont);
532 SoText2 *perfMeterText = new SoText2;
533 perfMeterText->justification = SoText2::LEFT;
534 sprintf (str, "%d tris/frame", numTris);
535 perfMeterText->string.setValue(str);
536 perfMeter->addChild(perfMeterText);
537
538 SbColor col(1, 1, 1);
539 vwr->setOverlayColorMap(1, 1, &col);
540 vwr->setOverlaySceneGraph(perfMeter);
541
542 // Update the performance meter every two seconds
543 SoTimerSensor *perfSensor =
544 new SoTimerSensor(perfSensorCB, perfMeterText);
545 perfSensor->setInterval(2.0);
546 perfSensor->schedule();
547
548 // Reset the meter to only show the number of tris/frame -
549 // otherwise the numbers might look misleading
550 vwr->addStartCallback(viewStartCB, perfMeterText);
551 }
552
553
554 static void
555 overlayViewportCB(void *, SoAction *action)
556 {
557 if (action->isOfType(SoGLRenderAction::getClassTypeId()))
558 glViewport(0, 0, 40, 40);
559 }
560
561
562 ////////////////////////////////////////////////////////////////////
563 //
564 // A sensor callback in the overlay scene updates the
565 // performance meter while the object is animating.
566 //
567 static void
568 perfSensorCB(void *data, SoSensor *)
569 {
570 SoText2 *perfText = (SoText2 *) data;
571 static SbBool wasAnimating = FALSE;
572 static SbTime startTime;
573 static double lastFrames = 0;
574 char str[100];
575
576 assert(!useWalkViewer);
577
578 if (((SoXtExaminerViewer *)viewer)->isAnimating()) {
579 if (wasAnimating) {
580 SbTime timeDiff = SbTime::getTimeOfDay() - startTime;
581 double frames =
582 numFramesRendered * 1000.0 / timeDiff.getMsecValue();
583 frames = floor(frames * 100.0 + 0.5) / 100.0;
584
585 // Update the perf meter display if the numbers have changed
586 if (frames != lastFrames) {
587 sprintf (str,
588 "%d tris/frame, %.2lf frames/sec, %.0lf tris/sec",
589 numTris, frames, frames * numTris);
590 perfText->string.setValue(str);
591 lastFrames = frames;
592 }
593
594 // Don't reset the timer here. By using the total
595 // time from when the object started animating
596 // we will get more accurate numbers - especially
597 // for slow objects.
598 }
599 else {
600 // Reset the timer when we detect the object has
601 // started animating.
602 numFramesRendered = 0;
603 startTime = SbTime::getTimeOfDay();
604 wasAnimating = TRUE;
605 }
606 }
607 else
608 wasAnimating = FALSE;
609 }
610
611 //
612 // Reset the meter to only show the tris/sec number.
613 // Otherwise the numbers might look misleading
614 //
615 static void
616 viewStartCB(void *data, SoXtViewer *)
617 {
618 char str[150];
619 SoText2 *perfText = (SoText2 *) data;
620
621 sprintf (str, "%d tris/frame", numTris);
622 perfText->string.setValue(str);
623 }
624
625 ////////////////////////////////////////////////////////////////////
626 //
627 // Turn busy cursor on/off
628 //
629 static void
630 setBusyCursor(SbBool showBusy)
631 {
632 Display *display = shell ? XtDisplay(shell) : NULL;
633 Window window = shell ? XtWindow(shell) : (Window) NULL;
634
635 if (!shell || !display || !window) return;
636
637 // make sure we have defined the cursor
638 if (! busyCursor)
639 createBusyCursor(display);
640
641 if (showBusy)
642 XDefineCursor(display, window, busyCursor);
643 else
644 XUndefineCursor(display, window);
645
646 if (viewer)
647 viewer->setCursorEnabled(!showBusy);
648
649 // force the busy cursor to show up right now
650 if (showBusy)
651 XSync(display, False);
652 }
653
654 ////////////////////////////////////////////////////////////////////
655 //
656 // Define busy cursor
657 //
658 static void
659 createBusyCursor(Display *display)
660 {
661 Drawable d = DefaultRootWindow(display);
662 XColor foreground, background;
663 foreground.red = 65535;
664 foreground.green = foreground.blue = 0;
665 background.red = background.green = background.blue = 65535;
666
667 Pixmap source = XCreateBitmapFromData(display, d,
668 hourglass_bits, hourglass_width, hourglass_height);
669 Pixmap mask = XCreateBitmapFromData(display, d,
670 hourglass_mask_bits, hourglass_width, hourglass_height);
671
672 busyCursor = XCreatePixmapCursor(display, source, mask,
673 &foreground, &background, hourglass_x_hot, hourglass_y_hot);
674
675 XFreePixmap(display, source);
676 XFreePixmap(display, mask);
677 }
678
679 ////////////////////////////////////////////////////////////////////
680 //
681 // Add a callback node to the main scene which will count the number
682 // of frames that have been rendered (to compute the tris/sec).
683 // Make sure the callback doesn't get cached or ruin the caching for
684 // the rest of the scene
685 //
686 static SoSeparator *
687 addUpdateCounter(SoNode *root)
688 {
689 SoSeparator *newRoot = new SoSeparator;
690 newRoot->renderCaching = SoSeparator::OFF;
691 newRoot->boundingBoxCaching = SoSeparator::OFF;
692 newRoot->pickCulling = SoSeparator::OFF;
693
694 SoCallback *countUpdates = new SoCallback;
695 countUpdates->setCallback(countUpdatesCB);
696
697 newRoot->addChild(countUpdates);
698 newRoot->addChild(root);
699
700 return (newRoot);
701 }
702
703 static void
704 countUpdatesCB(void *, SoAction *action)
705 {
706 if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
707 numFramesRendered++;
708 }
709 }
710
711 ///////////////////////////////////////////////////////////////////
712 //
713 // Brings up the "About..." dialog
714 //
715 static void
716 showAboutDialog()
717 {
718 if (access(IVHELPDIR"/ivview/ivview.about.pdf", R_OK) != 0) {
719 system("xmessage 'Sorry, could not find "
720 IVHELPDIR"/ivview/ivview.about.pdf' > /dev/null");
721 return;
722 }
723
724 char command[2*PATH_MAX+100];
725 sprintf(command, "which " PDFVIEWER " > /dev/null");
726
727 int err = system(command);
728 if (err) {
729 system("xmessage 'You must install " PDFVIEWER
730 " for this function to work' > /dev/null");
731 return;
732 }
733
734 sprintf(command, PDFVIEWER " "IVHELPDIR"/ivview/ivview.about.pdf &");
735 system(command);
736 }
737
738 ///////////////////////////////////////////////////////////////////
739 //
740 // Use a motif file selection dialog to get the new filename.
741 // Set up a callback to open the file and create the new scenegraph.
742 //
743 static void
744 getNewScene()
745 {
746 static Widget fileDialog = NULL;
747
748
749 if (fileDialog == NULL) {
750 Arg args[5];
751 int n = 0;
752
753 // Unmanage when ok/cancel are pressed
754 XtSetArg(args[n], XmNautoUnmanage, TRUE); n++;
755 fileDialog = XmCreateFileSelectionDialog(
756 shell, "File Dialog", args, n);
757
758 XtAddCallback(fileDialog, XmNokCallback,
759 (XtCallbackProc)newSceneCB, NULL);
760 }
761
762 // Manage the dialog
763 XtManageChild(fileDialog);
764 }
765
766 //
767 // Callback routine that gets called when the new filename
768 // has been entered
769 //
770 static void
771 newSceneCB(Widget, void *, XmFileSelectionBoxCallbackStruct *data)
772 {
773
774 // Get the file name
775 char *filename;
776 XmStringGetLtoR(data->value,
777 (XmStringCharSet) XmSTRING_DEFAULT_CHARSET, &filename);
778
779 files.count = 1;
780 files.names[0] = strdup(filename);
781 XtFree(filename);
782
783 setBusyCursor(TRUE);
784 SbBool readOk = readScene(files);
785 setBusyCursor(FALSE);
786
787 if (!readOk) {
788 char str[100];
789 strcpy(str, "Error reading file: ");
790 strcat(str, files.names[0]);
791 SoXt::createSimpleErrorDialog(shell, "File Error Dialog", str);
792 return;
793 }
794 }
795
796
797 ///////////////////////////////////////////////////////////////////
798 //
799 // Modify the viewer's background color using the color editor
800 // from the sample directory
801 //
802 static void
803 editBackgroundColor()
804 {
805 static MyColorEditor *backgroundColorEditor = NULL;
806
807 if (backgroundColorEditor == NULL) {
808 backgroundColorEditor = new MyColorEditor;
809 backgroundColorEditor->setColor(SbColor(0, 0, 0));
810 backgroundColorEditor->setTitle( "Background Color" );
811 backgroundColorEditor->addColorChangedCallback(
812 backgroundColorCB);
813 }
814
815 backgroundColorEditor->show();
816 }
817
818 //
819 // Callback routine that gets called when the background
820 // color editor values change
821 //
822 static void
823 backgroundColorCB(void *, const SbColor *color)
824 {
825 viewer->setBackgroundColor(*color);
826 }
827
828
829 ///////////////////////////////////////////////////////////////////
830 //
831 // Process the topbar menu events.
832 static void
833 processTopbarEvent(Widget, ivMenuItem *data, XmAnyCallbackStruct *)
834 {
835 switch (data->id) {
836
837 //
838 // File
839 //
840
841 case IV_FILE_ABOUT:
842 showAboutDialog();
843 break;
844
845 case IV_FILE_OPEN:
846 getNewScene();
847 break;
848
849 case IV_FILE_QUIT:
850 exit (0);
851 break;
852
853 //
854 // Edit
855 //
856
857 case IV_EDIT_TRANSPARENCY:
858 // Toggle the transparency mode
859 if (viewer->getTransparencyType() == SoGLRenderAction::SCREEN_DOOR)
860 viewer->setTransparencyType(SoGLRenderAction::DELAYED_BLEND);
861 else
862 viewer->setTransparencyType(SoGLRenderAction::SCREEN_DOOR);
863 break;
864
865 case IV_EDIT_BACKGROUND_CLR:
866 editBackgroundColor();
867 break;
868
869 //
870 // Optimize
871 //
872 case IV_OPTIMIZE_IVFIX:
873 ivfix = !ivfix;
874 optimizationChanged(files, TRUE);
875 break;
876
877 case IV_OPTIMIZE_SHAPEHINTS:
878 shapeHintBackface = !shapeHintBackface;
879 optimizationChanged(files, TRUE);
880 break;
881
882 }
883 }
884
885 ///////////////////////////////////////////////////////////////////////
886 //
887 // Create the top menu bar and the associated menus
888 //
889 static Widget
890 buildAndLayoutMenus(Widget parent)
891 {
892 ivMenuItem *menuItems = new ivMenuItem[IV_MENU_NUM];
893 int i;
894 for (i=0; i<IV_MENU_NUM; i++) {
895 menuItems[i].id = i;
896 menuItems[i].widget = NULL;
897 }
898
899 //
900 // Create the topbar menu
901 //
902 Widget menuWidget = XmCreateMenuBar(parent, "menuBar", NULL, 0);
903
904 Arg popupargs[4];
905 int popupn = 0;
906 #ifdef MENUS_IN_POPUP
907 Widget shell = SoXt::getShellWidget(menuWidget);
908 SoXt::getPopupArgs(XtDisplay(menuWidget), SCREEN(menuWidget),
909 popupargs, &popupn);
910 #endif
911
912 int itemCount = XtNumber(pulldownData);
913 WidgetList buttons = (WidgetList) XtMalloc(itemCount * sizeof(Widget));
914
915
916 Arg args[12];
917 int n;
918 for (i=0; i<itemCount; i++) {
919 //
920 // Make Topbar menu button
921 //
922 Widget subMenu =
923 XmCreatePulldownMenu(menuWidget, "subMenu", popupargs, popupn);
924
925 #ifdef MENUS_IN_POPUP
926 // register callbacks to load/unload the pulldown colormap when the
927 // pulldown menu is posted.
928 SoXt::registerColormapLoad(subMenu, shell);
929 #endif
930
931 int id = pulldownData[i].id;
932 menuItems[id].widget = subMenu;
933
934 XtSetArg(args[0], XmNsubMenuId, subMenu);
935 buttons[i] = XtCreateWidget(pulldownData[i].name,
936 xmCascadeButtonGadgetClass, menuWidget, args, 1);
937
938 //
939 // Make subMenu buttons
940 //
941 int subItemCount = pulldownData[i].subItemCount;
942 WidgetList subButtons =
943 (WidgetList) XtMalloc(subItemCount * sizeof(Widget));
944
945 for (int j=0; j<subItemCount; j++) {
946 if (pulldownData[i].subMenu[j].buttonType == IV_SEPARATOR) {
947 subButtons[j] = XtCreateWidget(
948 NULL, xmSeparatorGadgetClass, subMenu, NULL, 0);
949 }
950 else {
951 String callbackReason;
952 WidgetClass widgetClass;
953
954 switch (pulldownData[i].subMenu[j].buttonType) {
955 case IV_PUSH_BUTTON:
956 widgetClass = xmPushButtonGadgetClass;
957 callbackReason = XmNactivateCallback;
958 n = 0;
959 break;
960 case IV_TOGGLE_BUTTON:
961 widgetClass = xmToggleButtonGadgetClass;
962 callbackReason = XmNvalueChangedCallback;
963 n = 0;
964 break;
965 case IV_RADIO_BUTTON:
966 widgetClass = xmToggleButtonGadgetClass;
967 callbackReason = XmNvalueChangedCallback;
968 XtSetArg(args[0], XmNindicatorType, XmONE_OF_MANY);
969 n = 1;
970 break;
971 default:
972 fprintf(stderr,
973 "ivview INTERNAL ERROR: bad buttonType\n");
974 break;
975 }
976
977 //
978 // Check for keyboard accelerator
979 //
980 char *accel = pulldownData[i].subMenu[j].accelerator;
981 char *accelText = pulldownData[i].subMenu[j].accelText;
982 XmString xmstr = NULL;
983 if (accel != NULL) {
984 XtSetArg(args[n], XmNaccelerator, accel); n++;
985
986 if (accelText != NULL) {
987 xmstr = XmStringCreate(accelText,
988 XmSTRING_DEFAULT_CHARSET);
989 XtSetArg(args[n], XmNacceleratorText, xmstr); n++;
990 }
991 }
992
993 subButtons[j] = XtCreateWidget(
994 pulldownData[i].subMenu[j].name,
995 widgetClass, subMenu, args, n);
996 if (xmstr != NULL)
997 XmStringFree(xmstr);
998 id = pulldownData[i].subMenu[j].id;
999 menuItems[id].widget = subButtons[j];
1000 XtAddCallback(subButtons[j], callbackReason,
1001 (XtCallbackProc)processTopbarEvent,
1002 (XtPointer) &menuItems[id]);
1003 }
1004 }
1005 XtManageChildren(subButtons, subItemCount);
1006 XtFree((char *)subButtons);
1007 }
1008 XtManageChildren(buttons, itemCount);
1009 XtFree((char *)buttons);
1010
1011 //
1012 // Layout the menu bar
1013 //
1014 n = 0;
1015 XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
1016 XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
1017 XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
1018 XtSetValues(menuWidget, args, n);
1019 XtManageChild(menuWidget);
1020
1021 return (menuWidget);
1022 }
1023
1024
1025 ///////////////////////////////////////////////////////////////////
1026 // Create the viewer and lay it out so that it is attached
1027 // to the bottom of the menu bar
1028 //
1029 static SoXtViewer *
1030 buildAndLayoutViewer(Widget parent, Widget menuWidget, SbBool walk)
1031 {
1032 //
1033 //
1034 Arg args[12];
1035 int n = 0;
1036 SoXtViewer *viewer = NULL;
1037 if (!walk)
1038 viewer = new SoXtExaminerViewer(parent);
1039 else
1040 viewer = new SoXtWalkViewer(parent);
1041
1042 viewer->setViewing(TRUE); // default to VIEW
1043
1044 XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
1045 XtSetArg(args[n], XmNtopWidget, menuWidget); n++;
1046 XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
1047 XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
1048 XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
1049 XtSetValues(viewer->getWidget(), args, n);
1050
1051 return (viewer);
1052 }
1053
1054
1055
1056 ///////////////////////////////////////////////////////////////////
1057 //
1058
1059 static void
1060 countTriangleCB(void *userData, SoCallbackAction *,
1061 const SoPrimitiveVertex *,
1062 const SoPrimitiveVertex *,
1063 const SoPrimitiveVertex *)
1064 {
1065 int32_t *curCount = (int32_t *) userData;
1066 (*curCount)++;
1067 }
1068
1069
1070 int
1071 countTriangles(SoNode *root)
1072 {
1073 SoCallbackAction ca;
1074 int32_t numTris = 0;
1075
1076 root->ref();
1077
1078 ca.addTriangleCallback(SoShape::getClassTypeId(), countTriangleCB,
1079 (void *) &numTris);
1080 ca.apply(root);
1081
1082 root->unrefNoDelete();
1083
1084 return (numTris);
1085 }
1086
1087
1088 // Stolen from Annotator.
1089 //
1090 static String _myXtDefaultLanguageProc(Display *, String xnl, XtPointer)
1091 {
1092 if (! setlocale(LC_ALL, xnl))
1093 XtWarning("locale not supported by C library, locale unchanged");
1094
1095 if (! XSupportsLocale()) {
1096 XtWarning("locale not supported by Xlib, locale set to C");
1097 setlocale(LC_ALL, "C");
1098 }
1099 if (! XSetLocaleModifiers(""))
1100 XtWarning("X locale modifiers not supported, using default");
1101
1102 setlocale(LC_NUMERIC, "C");
1103
1104 return setlocale(LC_CTYPE, NULL);
1105 }
1106
1107
1108 ///////////////////////////////////////////////////////////////////
1109 //
1110 int
1111 main(int argc, char **argv)
1112 {
1113 XtAppContext appContext;
1114
1115 XtSetLanguageProc( NULL, _myXtDefaultLanguageProc, NULL );
1116
1117 shell = XtAppInitialize(
1118 &appContext, // context will be returned
1119 "Ivview", // application class
1120 NULL, 0, // options
1121 (int *) &argc, argv, // command line args in/out
1122 NULL, // fallback_resources
1123 NULL, 0); // args, num_args
1124
1125 XtGetSubresources( shell, &fileData[0], "intl", "Intl",
1126 intl_file_resources, intl_num_file_resources,
1127 NULL, 0 );
1128 XtGetSubresources( shell, &editData[0], "intl", "Intl",
1129 intl_edit_resources, intl_num_edit_resources,
1130 NULL, 0 );
1131 XtGetSubresources( shell, &optimizeData[0], "intl", "Intl",
1132 intl_optimize_resources, intl_num_optimize_resources,
1133 NULL, 0 );
1134 XtGetSubresources( shell, &pulldownData[0], "intl", "Intl",
1135 intl_pulldown_resources, intl_num_pulldown_resources,
1136 NULL, 0 );
1137
1138 // Parse command line arguments
1139 parse_args(argc, argv);
1140
1141 // build the main window - this is done FIRST (before initialzing
1142 // Inventor and reading) to make the application startup feel
1143 // faster.
1144
1145 Widget form = XtCreateWidget("Form", xmFormWidgetClass, shell, NULL, 0);
1146 XtVaSetValues(shell, XmNwidth, 520, XmNheight, 510, NULL);
1147
1148 Widget menuWidget = buildAndLayoutMenus(form);
1149 XtManageChild(form);
1150 XtRealizeWidget(shell);
1151 XmUpdateDisplay(shell); // better than XSync() because it redraws too
1152 setBusyCursor(TRUE);
1153
1154 // Initialize Inventor
1155 SoXt::init(shell);
1156
1157 // Create and lay out the viewer
1158 viewer = buildAndLayoutViewer(form, menuWidget, useWalkViewer);
1159 viewer->show();
1160 XSync(XtDisplay(shell), False);
1161
1162 // Read the input scene from the file(s)
1163 SbBool readOk = readScene(files);
1164
1165 // The lower left corner of the window is used to draw
1166 // the tris/second meter (if enabled)
1167 if (showPerfMeter)
1168 initPerfMeter(viewer);
1169
1170 setBusyCursor(FALSE);
1171
1172 SoXt::mainLoop();
1173 return 0;
1174 }