ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/px/x11image.c
Revision: 2.52
Committed: Mon Aug 17 18:00:11 1998 UTC (25 years, 8 months ago) by gwlarson
Content type: text/plain
Branch: MAIN
Changes since 2.51: +1 -4 lines
Log Message:
removed "color.h" include from tonemap.h

File Contents

# Content
1 /* Copyright (c) 1998 Silicon Graphics, Inc. */
2
3 #ifndef lint
4 static char SCCSid[] = "$SunId$ SGI";
5 #endif
6
7 /*
8 * x11image.c - driver for X-windows
9 *
10 * 3/1/90
11 */
12
13 /*
14 * Modified for X11
15 *
16 * January 1990
17 *
18 * Anat Grynberg and Greg Ward
19 */
20
21
22 #include "standard.h"
23
24 #include <signal.h>
25 #include <X11/Xlib.h>
26 #include <X11/cursorfont.h>
27 #include <X11/Xutil.h>
28 #include <X11/Xatom.h>
29
30 #undef NOPROTO
31 #define NOPROTO 1
32 #include "color.h"
33 #include "tonemap.h"
34 #include "view.h"
35 #include "x11raster.h"
36 #include "random.h"
37 #include "resolu.h"
38
39 #define FONTNAME "8x13" /* text font we'll use */
40
41 #define CTRL(c) ((c)-'@')
42
43 #define BORWIDTH 5 /* border width */
44
45 #define ICONSIZ (8*10) /* maximum icon dimension (even 8) */
46
47 #define FIXWEIGHT 20 /* weight to add for fixation points */
48
49 #define ourscreen DefaultScreen(thedisplay)
50 #define ourroot RootWindow(thedisplay,ourscreen)
51
52 #define revline(x0,y0,x1,y1) XDrawLine(thedisplay,wind,revgc,x0,y0,x1,y1)
53
54 #define redraw(x,y,w,h) patch_raster(wind,(x)-xoff,(y)-yoff,x,y,w,h,ourras)
55
56 double gamcor = 2.2; /* gamma correction */
57 char *gamstr = NULL; /* gamma value override */
58
59 int dither = 1; /* dither colors? */
60 int fast = 0; /* keep picture in Pixmap? */
61
62 char *dispname = NULL; /* our display name */
63
64 Window wind = 0; /* our output window */
65 unsigned long ourblack=0, ourwhite=1; /* black and white for this visual */
66 int maxcolors = 0; /* maximum colors */
67 int greyscale = 0; /* in grey */
68
69 int scale = 0; /* scalefactor; power of two */
70
71 int xoff = 0; /* x image offset */
72 int yoff = 0; /* y image offset */
73
74 int parent = 0; /* number of children, -1 if child */
75 int sequential = 0; /* display images in sequence */
76
77 char *tout = "od"; /* output of 't' command */
78 int tinterv = 0; /* interval between mouse reports */
79
80 int tmflags = TM_F_LINEAR; /* tone mapping flags */
81
82 VIEW ourview = STDVIEW; /* image view parameters */
83 int gotview = 0; /* got parameters from file */
84
85 COLR *scanline; /* scan line buffer */
86 TMbright *lscan; /* encoded luminance scanline */
87 BYTE *cscan; /* encoded chroma scanline */
88 BYTE *pscan; /* compute pixel scanline */
89
90 RESOLU inpres; /* input resolution and ordering */
91 int xmax, ymax; /* picture dimensions */
92 int width, height; /* window size */
93 char *fname = NULL; /* input file name */
94 FILE *fin = stdin; /* input file */
95 long *scanpos = NULL; /* scan line positions in file */
96 int cury = 0; /* current scan location */
97
98 double exposure = 1.0; /* exposure compensation used */
99
100 int wrongformat = 0; /* input in another format? */
101
102 GC ourgc; /* standard graphics context */
103 GC revgc; /* graphics context with GXinvert */
104
105 int *ourrank; /* our visual class ranking */
106 XVisualInfo ourvis; /* our visual */
107 XRASTER *ourras; /* our stored image */
108 unsigned char *ourdata; /* our image data */
109
110 struct {
111 int xmin, ymin, xsiz, ysiz;
112 } box = {0, 0, 0, 0}; /* current box */
113
114 char *geometry = NULL; /* geometry specification */
115
116 char icondata[ICONSIZ*ICONSIZ/8]; /* icon bitmap data */
117 int iconwidth = 0, iconheight = 0;
118
119 char *progname;
120
121 char errmsg[128];
122
123 BYTE clrtab[256][3]; /* global color map */
124
125 extern long ftell();
126
127 extern char *getenv();
128
129 Display *thedisplay;
130 Atom closedownAtom, wmProtocolsAtom;
131
132 int sigrecv;
133
134 int onsig() { sigrecv++; }
135
136
137 main(argc, argv)
138 int argc;
139 char *argv[];
140 {
141 int headline();
142 int i;
143 int pid;
144
145 progname = argv[0];
146
147 for (i = 1; i < argc; i++)
148 if (argv[i][0] == '-')
149 switch (argv[i][1]) {
150 case 'c': /* number of colors */
151 maxcolors = atoi(argv[++i]);
152 break;
153 case 'b': /* greyscale only */
154 greyscale = !greyscale;
155 break;
156 case 'm': /* monochrome */
157 greyscale = 1;
158 maxcolors = 2;
159 break;
160 case 'd': /* display or dither */
161 if (argv[i][2] == 'i')
162 dispname = argv[++i];
163 else
164 dither = !dither;
165 break;
166 case 'f': /* save pixmap */
167 fast = !fast;
168 break;
169 case 's': /* one at a time */
170 sequential = !sequential;
171 break;
172 case 'o': /* 't' output */
173 tout = argv[i]+2;
174 break;
175 case 't': /* msec interval */
176 tinterv = atoi(argv[++i]);
177 break;
178 case 'e': /* exposure comp. */
179 i++;
180 if (argv[i][0] == 'a') {
181 tmflags = TM_F_CAMERA;
182 break;
183 }
184 if (argv[i][0] == 'h') {
185 tmflags = TM_F_HUMAN;
186 break;
187 }
188 if (argv[i][0] != '+' && argv[i][0] != '-')
189 goto userr;
190 scale = atoi(argv[i]);
191 break;
192 case 'g': /* gamma comp. */
193 if (argv[i][2] == 'e')
194 geometry = argv[++i];
195 else
196 gamstr = argv[++i];
197 break;
198 default:
199 goto userr;
200 }
201 else if (argv[i][0] == '=')
202 geometry = argv[i];
203 else
204 break;
205
206 if (i > argc)
207 goto userr;
208 while (i < argc-1) {
209 sigrecv = 0;
210 signal(SIGCONT, onsig);
211 if ((pid=fork()) == 0) { /* a child for each picture */
212 parent = -1;
213 break;
214 }
215 if (pid < 0)
216 quiterr("fork failed");
217 parent++;
218 while (!sigrecv)
219 pause(); /* wait for wake-up call */
220 i++;
221 }
222 if (i < argc) { /* open picture file */
223 fname = argv[i];
224 fin = fopen(fname, "r");
225 if (fin == NULL)
226 quiterr("cannot open picture file");
227 }
228 /* get header */
229 getheader(fin, headline, NULL);
230 /* get picture dimensions */
231 if (wrongformat || !fgetsresolu(&inpres, fin))
232 quiterr("bad picture format");
233 xmax = scanlen(&inpres);
234 ymax = numscans(&inpres);
235 /* set view parameters */
236 if (gotview && setview(&ourview) != NULL)
237 gotview = 0;
238 if ((scanline = (COLR *)malloc(xmax*sizeof(COLR))) == NULL)
239 quiterr("out of memory");
240
241 init(argc, argv); /* get file and open window */
242
243 for ( ; ; )
244 getevent(); /* main loop */
245 userr:
246 fprintf(stderr,
247 "Usage: %s [-di disp][[-ge] spec][-b][-m][-d][-f][-c nclrs][-e spec][-g gamcor][-s][-ospec][-t intvl] pic ..\n",
248 progname);
249 exit(1);
250 }
251
252
253 headline(s) /* get relevant info from header */
254 char *s;
255 {
256 char fmt[32];
257
258 if (isexpos(s))
259 exposure *= exposval(s);
260 else if (formatval(fmt, s))
261 wrongformat = strcmp(fmt, COLRFMT);
262 else if (isview(s) && sscanview(&ourview, s) > 0)
263 gotview++;
264 }
265
266
267 init(argc, argv) /* get data and open window */
268 int argc;
269 char **argv;
270 {
271 XSetWindowAttributes ourwinattr;
272 XClassHint xclshints;
273 XWMHints xwmhints;
274 XSizeHints xszhints;
275 XTextProperty windowName, iconName;
276 XGCValues xgcv;
277 char *name;
278 register int i;
279
280 if (fname != NULL) {
281 scanpos = (long *)malloc(ymax*sizeof(long));
282 if (scanpos == NULL)
283 quiterr("out of memory");
284 for (i = 0; i < ymax; i++)
285 scanpos[i] = -1;
286 name = fname;
287 } else
288 name = progname;
289 /* remove directory prefix from name */
290 for (i = strlen(name); i-- > 0; )
291 if (name[i] == '/')
292 break;
293 name += i+1;
294 if ((thedisplay = XOpenDisplay(dispname)) == NULL)
295 quiterr("cannot open display");
296 /* set gamma value */
297 if (gamstr == NULL) /* get it from the X server */
298 gamstr = XGetDefault(thedisplay, "radiance", "gamma");
299 if (gamstr == NULL) /* get it from the environment */
300 gamstr = getenv("DISPLAY_GAMMA");
301 if (gamstr != NULL)
302 gamcor = atof(gamstr);
303 /* get best visual for default screen */
304 getbestvis();
305 /* store image */
306 getras();
307 /* get size and position */
308 xszhints.flags = 0;
309 xszhints.width = xmax; xszhints.height = ymax;
310 if (geometry != NULL) {
311 i = XParseGeometry(geometry, &xszhints.x, &xszhints.y,
312 (unsigned *)&xszhints.width,
313 (unsigned *)&xszhints.height);
314 if ((i&(WidthValue|HeightValue)) == (WidthValue|HeightValue))
315 xszhints.flags |= USSize;
316 else
317 xszhints.flags |= PSize;
318 if ((i&(XValue|YValue)) == (XValue|YValue)) {
319 xszhints.flags |= USPosition;
320 if (i & XNegative)
321 xszhints.x += DisplayWidth(thedisplay,
322 ourscreen)-1-xszhints.width-2*BORWIDTH;
323 if (i & YNegative)
324 xszhints.y += DisplayHeight(thedisplay,
325 ourscreen)-1-xszhints.height-2*BORWIDTH;
326 }
327 }
328 /* open window */
329 i = CWEventMask|CWCursor|CWBackPixel|CWBorderPixel;
330 ourwinattr.border_pixel = ourwhite;
331 ourwinattr.background_pixel = ourblack;
332 if (ourvis.visual != DefaultVisual(thedisplay,ourscreen)) {
333 ourwinattr.colormap = newcmap(thedisplay, ourscreen, ourvis.visual);
334 i |= CWColormap;
335 }
336 ourwinattr.event_mask = ExposureMask|KeyPressMask|ButtonPressMask|
337 ButtonReleaseMask|ButtonMotionMask|StructureNotifyMask;
338 ourwinattr.cursor = XCreateFontCursor(thedisplay, XC_diamond_cross);
339 wind = XCreateWindow(thedisplay, ourroot, xszhints.x, xszhints.y,
340 xszhints.width, xszhints.height, BORWIDTH,
341 ourvis.depth, InputOutput, ourvis.visual,
342 i, &ourwinattr);
343 if (wind == 0)
344 quiterr("cannot create window");
345 width = xmax;
346 height = ymax;
347 /* prepare graphics drawing context */
348 if ((xgcv.font = XLoadFont(thedisplay, FONTNAME)) == 0)
349 quiterr("cannot get font");
350 xgcv.foreground = ourblack;
351 xgcv.background = ourwhite;
352 ourgc = XCreateGC(thedisplay, wind, GCForeground|GCBackground|
353 GCFont, &xgcv);
354 xgcv.function = GXinvert;
355 revgc = XCreateGC(thedisplay, wind, GCForeground|GCBackground|
356 GCFunction, &xgcv);
357
358 /* set up the window manager */
359 xwmhints.flags = InputHint|IconPixmapHint;
360 xwmhints.input = True;
361 xwmhints.icon_pixmap = XCreateBitmapFromData(thedisplay,
362 wind, icondata, iconwidth, iconheight);
363
364 windowName.encoding = iconName.encoding = XA_STRING;
365 windowName.format = iconName.format = 8;
366 windowName.value = (u_char *)name;
367 windowName.nitems = strlen(windowName.value);
368 iconName.value = (u_char *)name;
369 iconName.nitems = strlen(windowName.value);
370
371 xclshints.res_name = NULL;
372 xclshints.res_class = "Ximage";
373 XSetWMProperties(thedisplay, wind, &windowName, &iconName,
374 argv, argc, &xszhints, &xwmhints, &xclshints);
375 closedownAtom = XInternAtom(thedisplay, "WM_DELETE_WINDOW", False);
376 wmProtocolsAtom = XInternAtom(thedisplay, "WM_PROTOCOLS", False);
377 XSetWMProtocols(thedisplay, wind, &closedownAtom, 1);
378
379 XMapWindow(thedisplay, wind);
380 } /* end of init */
381
382
383 quiterr(err) /* print message and exit */
384 char *err;
385 {
386 register int es;
387 int cs;
388
389 if (es = err != NULL)
390 fprintf(stderr, "%s: %s: %s\n", progname,
391 fname==NULL?"<stdin>":fname, err);
392 if (thedisplay != NULL)
393 XCloseDisplay(thedisplay);
394 if (parent < 0 & sigrecv == 0)
395 kill(getppid(), SIGCONT);
396 while (parent > 0 && wait(&cs) != -1) { /* wait for any children */
397 if (es == 0)
398 es = cs>>8 & 0xff;
399 parent--;
400 }
401 exit(es);
402 }
403
404
405 static int
406 viscmp(v1,v2) /* compare visual to see which is better, descending */
407 register XVisualInfo *v1, *v2;
408 {
409 int bad1 = 0, bad2 = 0;
410 register int *rp;
411
412 if (v1->class == v2->class) {
413 if (v1->class == TrueColor || v1->class == DirectColor) {
414 /* prefer 24-bit to 32-bit */
415 if (v1->depth == 24 && v2->depth == 32)
416 return(-1);
417 if (v1->depth == 32 && v2->depth == 24)
418 return(1);
419 return(0);
420 }
421 /* don't be too greedy */
422 if (maxcolors <= 1<<v1->depth && maxcolors <= 1<<v2->depth)
423 return(v1->depth - v2->depth);
424 return(v2->depth - v1->depth);
425 }
426 /* prefer Pseudo when < 24-bit */
427 if ((v1->class == TrueColor || v1->class == DirectColor) &&
428 v1->depth < 24)
429 bad1 = 1;
430 if ((v2->class == TrueColor || v2->class == DirectColor) &&
431 v2->depth < 24)
432 bad2 = -1;
433 if (bad1 | bad2)
434 return(bad1+bad2);
435 /* otherwise, use class ranking */
436 for (rp = ourrank; *rp != -1; rp++) {
437 if (v1->class == *rp)
438 return(-1);
439 if (v2->class == *rp)
440 return(1);
441 }
442 return(0);
443 }
444
445
446 getbestvis() /* get the best visual for this screen */
447 {
448 #ifdef DEBUG
449 static char vistype[][12] = {
450 "StaticGray",
451 "GrayScale",
452 "StaticColor",
453 "PseudoColor",
454 "TrueColor",
455 "DirectColor"
456 };
457 #endif
458 static int rankings[3][6] = {
459 {TrueColor,DirectColor,PseudoColor,GrayScale,StaticGray,-1},
460 {PseudoColor,GrayScale,StaticGray,-1},
461 {PseudoColor,GrayScale,StaticGray,-1}
462 };
463 XVisualInfo *xvi;
464 int vismatched;
465 register int i, j;
466
467 if (greyscale) {
468 ourrank = rankings[2];
469 if (maxcolors < 2) maxcolors = 256;
470 } else if (maxcolors >= 2 && maxcolors <= 256)
471 ourrank = rankings[1];
472 else {
473 ourrank = rankings[0];
474 maxcolors = 256;
475 }
476 /* find best visual */
477 ourvis.screen = ourscreen;
478 xvi = XGetVisualInfo(thedisplay,VisualScreenMask,&ourvis,&vismatched);
479 if (xvi == NULL)
480 quiterr("no visuals for this screen!");
481 #ifdef DEBUG
482 fprintf(stderr, "Supported visuals:\n");
483 for (i = 0; i < vismatched; i++)
484 fprintf(stderr, "\ttype %s, depth %d\n",
485 vistype[xvi[i].class], xvi[i].depth);
486 #endif
487 for (i = 0, j = 1; j < vismatched; j++)
488 if (viscmp(&xvi[i],&xvi[j]) > 0)
489 i = j;
490 /* compare to least acceptable */
491 for (j = 0; ourrank[j++] != -1; )
492 ;
493 ourvis.class = ourrank[--j];
494 ourvis.depth = 1;
495 if (viscmp(&xvi[i],&ourvis) > 0)
496 quiterr("inadequate visuals on this screen");
497 /* OK, we'll use it */
498 copystruct(&ourvis, &xvi[i]);
499 #ifdef DEBUG
500 fprintf(stderr, "Selected visual type %s, depth %d\n",
501 vistype[ourvis.class], ourvis.depth);
502 #endif
503 /* make appropriate adjustments */
504 if (ourvis.class == GrayScale || ourvis.class == StaticGray)
505 greyscale = 1;
506 if (ourvis.depth <= 8 && ourvis.colormap_size < maxcolors)
507 maxcolors = ourvis.colormap_size;
508 if (ourvis.class == StaticGray) {
509 ourblack = 0;
510 ourwhite = 255;
511 } else if (ourvis.class == PseudoColor) {
512 ourblack = BlackPixel(thedisplay,ourscreen);
513 ourwhite = WhitePixel(thedisplay,ourscreen);
514 if ((ourblack|ourwhite) & ~255L) {
515 ourblack = 0;
516 ourwhite = 1;
517 }
518 if (maxcolors > 4)
519 maxcolors -= 2;
520 } else {
521 ourblack = 0;
522 ourwhite = ourvis.red_mask|ourvis.green_mask|ourvis.blue_mask;
523 }
524 XFree((char *)xvi);
525 }
526
527
528 getras() /* get raster file */
529 {
530 XVisualInfo vinfo;
531
532 if (maxcolors <= 2) { /* monochrome */
533 ourdata = (unsigned char *)malloc(ymax*((xmax+7)/8));
534 if (ourdata == NULL)
535 goto fail;
536 ourras = make_raster(thedisplay, &ourvis, 1, ourdata,
537 xmax, ymax, 8);
538 if (ourras == NULL)
539 goto fail;
540 getmono();
541 } else if (ourvis.class == TrueColor | ourvis.class == DirectColor) {
542 ourdata = (unsigned char *)malloc(sizeof(int4)*xmax*ymax);
543 if (ourdata == NULL)
544 goto fail;
545 ourras = make_raster(thedisplay, &ourvis, sizeof(int4)*8,
546 ourdata, xmax, ymax, 32);
547 if (ourras == NULL)
548 goto fail;
549 getfull();
550 } else {
551 ourdata = (unsigned char *)malloc(xmax*ymax);
552 if (ourdata == NULL)
553 goto fail;
554 ourras = make_raster(thedisplay, &ourvis, 8, ourdata,
555 xmax, ymax, 8);
556 if (ourras == NULL)
557 goto fail;
558 if (greyscale)
559 getgrey();
560 else
561 getmapped();
562 if (ourvis.class != StaticGray && !init_rcolors(ourras,clrtab))
563 goto fail;
564 }
565 return;
566 fail:
567 quiterr("could not create raster image");
568 }
569
570
571 getevent() /* process the next event */
572 {
573 XEvent xev;
574
575 XNextEvent(thedisplay, &xev);
576 switch ((int)xev.type) {
577 case KeyPress:
578 docom(&xev.xkey);
579 break;
580 case ConfigureNotify:
581 width = xev.xconfigure.width;
582 height = xev.xconfigure.height;
583 break;
584 case MapNotify:
585 map_rcolors(ourras, wind);
586 if (fast)
587 make_rpixmap(ourras, wind);
588 if (!sequential & parent < 0 & sigrecv == 0) {
589 kill(getppid(), SIGCONT);
590 sigrecv--;
591 }
592 break;
593 case UnmapNotify:
594 if (!fast)
595 unmap_rcolors(ourras);
596 break;
597 case Expose:
598 redraw(xev.xexpose.x, xev.xexpose.y,
599 xev.xexpose.width, xev.xexpose.height);
600 break;
601 case ButtonPress:
602 if (xev.xbutton.state & (ShiftMask|ControlMask))
603 moveimage(&xev.xbutton);
604 else
605 switch (xev.xbutton.button) {
606 case Button1:
607 getbox(&xev.xbutton);
608 break;
609 case Button2:
610 traceray(xev.xbutton.x, xev.xbutton.y);
611 break;
612 case Button3:
613 trackrays(&xev.xbutton);
614 break;
615 }
616 break;
617 case ClientMessage:
618 if ((xev.xclient.message_type == wmProtocolsAtom) &&
619 (xev.xclient.data.l[0] == closedownAtom))
620 quiterr(NULL);
621 break;
622 }
623 }
624
625
626 traceray(xpos, ypos) /* print requested pixel data */
627 int xpos, ypos;
628 {
629 extern char *index();
630 FLOAT hv[2];
631 FVECT rorg, rdir;
632 COLOR cval;
633 register char *cp;
634
635 box.xmin = xpos; box.xsiz = 1;
636 box.ymin = ypos; box.ysiz = 1;
637 avgbox(cval);
638 scalecolor(cval, 1./exposure);
639 pix2loc(hv, &inpres, xpos-xoff, ypos-yoff);
640 if (!gotview || viewray(rorg, rdir, &ourview, hv[0], hv[1]) < 0)
641 rorg[0] = rorg[1] = rorg[2] =
642 rdir[0] = rdir[1] = rdir[2] = 0.;
643
644 for (cp = tout; *cp; cp++) /* print what they asked for */
645 switch (*cp) {
646 case 'o': /* origin */
647 printf("%e %e %e ", rorg[0], rorg[1], rorg[2]);
648 break;
649 case 'd': /* direction */
650 printf("%e %e %e ", rdir[0], rdir[1], rdir[2]);
651 break;
652 case 'v': /* radiance value */
653 printf("%e %e %e ", colval(cval,RED),
654 colval(cval,GRN), colval(cval,BLU));
655 break;
656 case 'l': /* luminance */
657 printf("%e ", luminance(cval));
658 break;
659 case 'p': /* pixel position */
660 printf("%d %d ", (int)(hv[0]*inpres.xr),
661 (int)(hv[1]*inpres.yr));
662 break;
663 }
664 putchar('\n');
665 fflush(stdout);
666 return(0);
667 }
668
669
670 docom(ekey) /* execute command */
671 XKeyPressedEvent *ekey;
672 {
673 char buf[80];
674 COLOR cval;
675 XColor cvx;
676 int com, n;
677 double comp;
678 FLOAT hv[2];
679
680 n = XLookupString(ekey, buf, sizeof(buf), NULL, NULL);
681 if (n == 0)
682 return(0);
683 com = buf[0];
684 switch (com) { /* interpret command */
685 case 'q':
686 case 'Q':
687 case CTRL('D'): /* quit */
688 quiterr(NULL);
689 case '\n':
690 case '\r':
691 case 'l':
692 case 'c': /* value */
693 if (!avgbox(cval))
694 return(-1);
695 switch (com) {
696 case '\n':
697 case '\r': /* radiance */
698 sprintf(buf, "%.3f", intens(cval)/exposure);
699 break;
700 case 'l': /* luminance */
701 sprintf(buf, "%.0fL", luminance(cval)/exposure);
702 break;
703 case 'c': /* color */
704 comp = pow(2.0, (double)scale);
705 sprintf(buf, "(%.2f,%.2f,%.2f)",
706 colval(cval,RED)*comp,
707 colval(cval,GRN)*comp,
708 colval(cval,BLU)*comp);
709 break;
710 }
711 XDrawImageString(thedisplay, wind, ourgc,
712 box.xmin, box.ymin+box.ysiz, buf, strlen(buf));
713 return(0);
714 case 'i': /* identify (contour) */
715 if (ourras->pixels == NULL)
716 return(-1);
717 n = ourdata[ekey->x-xoff+xmax*(ekey->y-yoff)];
718 n = ourras->pmap[n];
719 cvx.pixel = ourras->cdefs[n].pixel;
720 cvx.red = random() & 65535;
721 cvx.green = random() & 65535;
722 cvx.blue = random() & 65535;
723 cvx.flags = DoRed|DoGreen|DoBlue;
724 XStoreColor(thedisplay, ourras->cmap, &cvx);
725 return(0);
726 case 'p': /* position */
727 pix2loc(hv, &inpres, ekey->x-xoff, ekey->y-yoff);
728 sprintf(buf, "(%d,%d)", (int)(hv[0]*inpres.xr),
729 (int)(hv[1]*inpres.yr));
730 XDrawImageString(thedisplay, wind, ourgc, ekey->x, ekey->y,
731 buf, strlen(buf));
732 return(0);
733 case 't': /* trace */
734 return(traceray(ekey->x, ekey->y));
735 case 'a': /* auto exposure */
736 if (fname == NULL)
737 return(-1);
738 tmflags = TM_F_CAMERA;
739 strcpy(buf, "auto exposure...");
740 goto remap;
741 case 'h': /* human response */
742 if (fname == NULL)
743 return(-1);
744 tmflags = TM_F_HUMAN;
745 strcpy(buf, "human exposure...");
746 goto remap;
747 case '=': /* adjust exposure */
748 case '@': /* adaptation level */
749 if (!avgbox(cval))
750 return(-1);
751 comp = bright(cval);
752 if (comp < 1e-20) {
753 XBell(thedisplay, 0);
754 return(-1);
755 }
756 if (com == '@')
757 comp = 106./exposure/
758 pow(1.219+pow(comp*WHTEFFICACY/exposure,.4),2.5);
759 else
760 comp = .5/comp;
761 comp = log(comp)/.69315 - scale;
762 n = comp < 0 ? comp-.5 : comp+.5 ; /* round */
763 if (tmflags != TM_F_LINEAR)
764 tmflags = TM_F_LINEAR; /* turn off tone mapping */
765 else {
766 if (n == 0) /* else check if any change */
767 return(0);
768 scale_rcolors(ourras, pow(2.0, (double)n));
769 }
770 scale += n;
771 sprintf(buf, "%+d", scale);
772 remap:
773 XDrawImageString(thedisplay, wind, ourgc,
774 box.xmin, box.ymin+box.ysiz, buf, strlen(buf));
775 XFlush(thedisplay);
776 free(ourdata);
777 free_raster(ourras);
778 getras();
779 /* fall through */
780 case CTRL('R'): /* redraw */
781 case CTRL('L'):
782 unmap_rcolors(ourras);
783 XClearWindow(thedisplay, wind);
784 map_rcolors(ourras, wind);
785 if (fast)
786 make_rpixmap(ourras, wind);
787 redraw(0, 0, width, height);
788 return(0);
789 case 'f': /* turn on fast redraw */
790 fast = 1;
791 make_rpixmap(ourras, wind);
792 return(0);
793 case 'F': /* turn off fast redraw */
794 fast = 0;
795 free_rpixmap(ourras);
796 return(0);
797 case '0': /* recenter origin */
798 if (xoff == 0 & yoff == 0)
799 return(0);
800 xoff = yoff = 0;
801 XClearWindow(thedisplay, wind);
802 redraw(0, 0, width, height);
803 return(0);
804 case ' ': /* clear */
805 redraw(box.xmin, box.ymin, box.xsiz, box.ysiz);
806 return(0);
807 default:
808 XBell(thedisplay, 0);
809 return(-1);
810 }
811 }
812
813
814 moveimage(ebut) /* shift the image */
815 XButtonPressedEvent *ebut;
816 {
817 XEvent e;
818 int mxo, myo;
819
820 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
821 while (e.type == MotionNotify) {
822 mxo = e.xmotion.x;
823 myo = e.xmotion.y;
824 revline(ebut->x, ebut->y, mxo, myo);
825 revbox(xoff+mxo-ebut->x, yoff+myo-ebut->y,
826 xoff+mxo-ebut->x+xmax, yoff+myo-ebut->y+ymax);
827 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
828 revline(ebut->x, ebut->y, mxo, myo);
829 revbox(xoff+mxo-ebut->x, yoff+myo-ebut->y,
830 xoff+mxo-ebut->x+xmax, yoff+myo-ebut->y+ymax);
831 }
832 xoff += e.xbutton.x - ebut->x;
833 yoff += e.xbutton.y - ebut->y;
834 XClearWindow(thedisplay, wind);
835 redraw(0, 0, width, height);
836 }
837
838
839 getbox(ebut) /* get new box */
840 XButtonPressedEvent *ebut;
841 {
842 XEvent e;
843
844 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
845 while (e.type == MotionNotify) {
846 revbox(ebut->x, ebut->y, box.xmin = e.xmotion.x, box.ymin = e.xmotion.y);
847 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
848 revbox(ebut->x, ebut->y, box.xmin, box.ymin);
849 }
850 box.xmin = e.xbutton.x<0 ? 0 : (e.xbutton.x>=width ? width-1 : e.xbutton.x);
851 box.ymin = e.xbutton.y<0 ? 0 : (e.xbutton.y>=height ? height-1 : e.xbutton.y);
852 if (box.xmin > ebut->x) {
853 box.xsiz = box.xmin - ebut->x + 1;
854 box.xmin = ebut->x;
855 } else {
856 box.xsiz = ebut->x - box.xmin + 1;
857 }
858 if (box.ymin > ebut->y) {
859 box.ysiz = box.ymin - ebut->y + 1;
860 box.ymin = ebut->y;
861 } else {
862 box.ysiz = ebut->y - box.ymin + 1;
863 }
864 }
865
866
867 trackrays(ebut) /* trace rays as mouse moves */
868 XButtonPressedEvent *ebut;
869 {
870 XEvent e;
871 unsigned long lastrept;
872
873 traceray(ebut->x, ebut->y);
874 lastrept = ebut->time;
875 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
876 while (e.type == MotionNotify) {
877 if (e.xmotion.time >= lastrept + tinterv) {
878 traceray(e.xmotion.x, e.xmotion.y);
879 lastrept = e.xmotion.time;
880 }
881 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
882 }
883 }
884
885
886 revbox(x0, y0, x1, y1) /* draw box with reversed lines */
887 int x0, y0, x1, y1;
888 {
889 revline(x0, y0, x1, y0);
890 revline(x0, y1, x1, y1);
891 revline(x0, y0, x0, y1);
892 revline(x1, y0, x1, y1);
893 }
894
895
896 int
897 colavg(scn, n, cavg)
898 register COLR *scn;
899 register int n;
900 COLOR cavg;
901 {
902 COLOR col;
903
904 while (n--) {
905 colr_color(col, scn++);
906 addcolor(cavg, col);
907 }
908 }
909
910
911 int
912 avgbox(cavg) /* average color over current box */
913 COLOR cavg;
914 {
915 double d;
916 register int rval;
917
918 setcolor(cavg, 0., 0., 0.);
919 rval = dobox(colavg, (char *)cavg);
920 if (rval > 0) {
921 d = 1./rval;
922 scalecolor(cavg, d);
923 }
924 return(rval);
925 }
926
927
928 int
929 dobox(f, p) /* run function over box */
930 int (*f)(); /* function to call for each subscan */
931 char *p; /* pointer to private data */
932 {
933 int left, right, top, bottom;
934 int y;
935
936 left = box.xmin - xoff;
937 right = left + box.xsiz;
938 if (left < 0)
939 left = 0;
940 if (right > xmax)
941 right = xmax;
942 if (left >= right)
943 return(0);
944 top = box.ymin - yoff;
945 bottom = top + box.ysiz;
946 if (top < 0)
947 top = 0;
948 if (bottom > ymax)
949 bottom = ymax;
950 if (top >= bottom)
951 return(0);
952 for (y = top; y < bottom; y++) {
953 if (getscan(y) == -1)
954 return(-1);
955 (*f)(scanline+left, right-left, p);
956 }
957 return((right-left)*(bottom-top));
958 }
959
960
961 int
962 addfix(scn, n) /* add fixation points to histogram */
963 COLR *scn;
964 int n;
965 {
966 if (tmCvColrs(lscan, TM_NOCHROM, scn, n))
967 goto tmerr;
968 if (tmAddHisto(lscan, n, FIXWEIGHT))
969 goto tmerr;
970 return;
971 tmerr:
972 quiterr("tone mapping error");
973 }
974
975
976 make_tonemap() /* initialize tone mapping */
977 {
978 int flags, y;
979
980 if (tmflags != TM_F_LINEAR && fname == NULL) {
981 fprintf(stderr, "%s: cannot adjust tone of standard input\n",
982 progname);
983 tmflags = TM_F_LINEAR;
984 }
985 if (tmflags == TM_F_LINEAR) { /* linear with clamping */
986 setcolrcor(pow, 1.0/gamcor);
987 return;
988 }
989 flags = tmflags; /* histogram adjustment */
990 if (greyscale) flags |= TM_F_BW;
991 if (tmTop != NULL) { /* reuse old histogram if one */
992 tmDone(tmTop);
993 tmTop->flags = flags;
994 } else { /* else initialize */
995 if ((lscan = (TMbright *)malloc(xmax*sizeof(TMbright))) == NULL)
996 goto memerr;
997 if (greyscale) {
998 cscan = TM_NOCHROM;
999 if ((pscan = (BYTE *)malloc(sizeof(BYTE)*xmax)) == NULL)
1000 goto memerr;
1001 } else if ((pscan=cscan = (BYTE *)malloc(3*sizeof(BYTE)*xmax))
1002 == NULL)
1003 goto memerr;
1004 /* initialize tm library */
1005 if (tmInit(flags, stdprims, gamcor) == NULL)
1006 goto memerr;
1007 if (tmSetSpace(stdprims, WHTEFFICACY/exposure))
1008 goto tmerr;
1009 /* compute picture histogram */
1010 for (y = 0; y < ymax; y++) {
1011 getscan(y);
1012 if (tmCvColrs(lscan, TM_NOCHROM, scanline, xmax))
1013 goto tmerr;
1014 if (tmAddHisto(lscan, xmax, 1))
1015 goto tmerr;
1016 }
1017 }
1018 tmDup(); /* add fixations to duplicate map */
1019 dobox(addfix, NULL);
1020 /* (re)compute tone mapping */
1021 if (tmComputeMapping(gamcor, 0., 0.))
1022 goto tmerr;
1023 return;
1024 memerr:
1025 quiterr("out of memory in make_tonemap");
1026 tmerr:
1027 quiterr("tone mapping error");
1028 }
1029
1030
1031 tmap_colrs(scn, len) /* apply tone mapping to scanline */
1032 register COLR *scn;
1033 int len;
1034 {
1035 register BYTE *ps;
1036
1037 if (tmflags == TM_F_LINEAR) {
1038 if (scale)
1039 shiftcolrs(scn, len, scale);
1040 colrs_gambs(scn, len);
1041 return;
1042 }
1043 if (len > xmax)
1044 quiterr("code error 1 in tmap_colrs");
1045 if (tmCvColrs(lscan, cscan, scn, len))
1046 goto tmerr;
1047 if (tmMapPixels(pscan, lscan, cscan, len))
1048 goto tmerr;
1049 ps = pscan;
1050 if (greyscale)
1051 while (len--) {
1052 scn[0][RED] = scn[0][GRN] = scn[0][BLU] = *ps++;
1053 scn[0][EXP] = COLXS;
1054 scn++;
1055 }
1056 else
1057 while (len--) {
1058 scn[0][RED] = *ps++;
1059 scn[0][GRN] = *ps++;
1060 scn[0][BLU] = *ps++;
1061 scn[0][EXP] = COLXS;
1062 scn++;
1063 }
1064 return;
1065 tmerr:
1066 quiterr("tone mapping error");
1067 }
1068
1069
1070 getmono() /* get monochrome data */
1071 {
1072 register unsigned char *dp;
1073 register int x, err;
1074 int y, errp;
1075 short *cerr;
1076
1077 if ((cerr = (short *)calloc(xmax,sizeof(short))) == NULL)
1078 quiterr("out of memory in getmono");
1079 dp = ourdata - 1;
1080 for (y = 0; y < ymax; y++) {
1081 getscan(y);
1082 add2icon(y, scanline);
1083 normcolrs(scanline, xmax, scale);
1084 err = 0;
1085 for (x = 0; x < xmax; x++) {
1086 if (!(x&7))
1087 *++dp = 0;
1088 errp = err;
1089 err += normbright(scanline[x]) + cerr[x];
1090 if (err > 127)
1091 err -= 255;
1092 else
1093 *dp |= 1<<(7-(x&07));
1094 err /= 3;
1095 cerr[x] = err + errp;
1096 }
1097 }
1098 free((char *)cerr);
1099 }
1100
1101
1102 add2icon(y, scan) /* add a scanline to our icon data */
1103 int y;
1104 COLR *scan;
1105 {
1106 static short cerr[ICONSIZ];
1107 static int ynext;
1108 static char *dp;
1109 COLR clr;
1110 register int err;
1111 register int x, ti;
1112 int errp;
1113
1114 if (iconheight == 0) { /* initialize */
1115 if (xmax <= ICONSIZ && ymax <= ICONSIZ) {
1116 iconwidth = xmax;
1117 iconheight = ymax;
1118 } else if (xmax > ymax) {
1119 iconwidth = ICONSIZ;
1120 iconheight = ICONSIZ*ymax/xmax;
1121 if (iconheight < 1)
1122 iconheight = 1;
1123 } else {
1124 iconwidth = ICONSIZ*xmax/ymax;
1125 if (iconwidth < 1)
1126 iconwidth = 1;
1127 iconheight = ICONSIZ;
1128 }
1129 ynext = 0;
1130 dp = icondata - 1;
1131 }
1132 if (y < ynext*ymax/iconheight) /* skip this one */
1133 return;
1134 err = 0;
1135 for (x = 0; x < iconwidth; x++) {
1136 if (!(x&7))
1137 *++dp = 0;
1138 errp = err;
1139 ti = x*xmax/iconwidth;
1140 copycolr(clr, scan[ti]);
1141 normcolrs(clr, 1, scale);
1142 err += normbright(clr) + cerr[x];
1143 if (err > 127)
1144 err -= 255;
1145 else
1146 *dp |= 1<<(x&07);
1147 err /= 3;
1148 cerr[x] = err + errp;
1149 }
1150 ynext++;
1151 }
1152
1153
1154 getfull() /* get full (24-bit) data */
1155 {
1156 int y;
1157 register unsigned int4 *dp;
1158 register int x;
1159 /* initialize tone mapping */
1160 make_tonemap();
1161 /* read and convert file */
1162 dp = (unsigned int4 *)ourdata;
1163 for (y = 0; y < ymax; y++) {
1164 getscan(y);
1165 add2icon(y, scanline);
1166 tmap_colrs(scanline, xmax);
1167 if (ourras->image->blue_mask & 1)
1168 for (x = 0; x < xmax; x++)
1169 *dp++ = (unsigned int4)scanline[x][RED] << 16 |
1170 (unsigned int4)scanline[x][GRN] << 8 |
1171 (unsigned int4)scanline[x][BLU] ;
1172 else
1173 for (x = 0; x < xmax; x++)
1174 *dp++ = (unsigned int4)scanline[x][RED] |
1175 (unsigned int4)scanline[x][GRN] << 8 |
1176 (unsigned int4)scanline[x][BLU] << 16 ;
1177 }
1178 }
1179
1180
1181 getgrey() /* get greyscale data */
1182 {
1183 int y;
1184 register unsigned char *dp;
1185 register int x;
1186 /* initialize tone mapping */
1187 make_tonemap();
1188 /* read and convert file */
1189 dp = ourdata;
1190 for (y = 0; y < ymax; y++) {
1191 getscan(y);
1192 add2icon(y, scanline);
1193 tmap_colrs(scanline, xmax);
1194 if (maxcolors < 256)
1195 for (x = 0; x < xmax; x++)
1196 *dp++ = ((int4)scanline[x][GRN] *
1197 maxcolors + maxcolors/2) >> 8;
1198 else
1199 for (x = 0; x < xmax; x++)
1200 *dp++ = scanline[x][GRN];
1201 }
1202 for (x = 0; x < maxcolors; x++)
1203 clrtab[x][RED] = clrtab[x][GRN] =
1204 clrtab[x][BLU] = ((int4)x*256 + 128)/maxcolors;
1205 }
1206
1207
1208 getmapped() /* get color-mapped data */
1209 {
1210 int y;
1211 /* make sure we can do it first */
1212 if (fname == NULL)
1213 quiterr("cannot map colors from standard input");
1214 /* initialize tone mapping */
1215 make_tonemap();
1216 /* make histogram */
1217 if (new_histo((int4)xmax*ymax) == -1)
1218 quiterr("cannot initialize histogram");
1219 for (y = 0; y < ymax; y++) {
1220 if (getscan(y) < 0)
1221 break;
1222 add2icon(y, scanline);
1223 tmap_colrs(scanline, xmax);
1224 cnt_colrs(scanline, xmax);
1225 }
1226 /* map pixels */
1227 if (!new_clrtab(maxcolors))
1228 quiterr("cannot create color map");
1229 for (y = 0; y < ymax; y++) {
1230 getscan(y);
1231 tmap_colrs(scanline, xmax);
1232 if (dither)
1233 dith_colrs(ourdata+y*xmax, scanline, xmax);
1234 else
1235 map_colrs(ourdata+y*xmax, scanline, xmax);
1236 }
1237 }
1238
1239
1240 scale_rcolors(xr, sf) /* scale color map */
1241 register XRASTER *xr;
1242 double sf;
1243 {
1244 register int i;
1245 long maxv;
1246
1247 if (xr->pixels == NULL)
1248 return;
1249
1250 sf = pow(sf, 1.0/gamcor);
1251 maxv = 65535/sf;
1252
1253 for (i = xr->ncolors; i--; ) {
1254 xr->cdefs[i].red = xr->cdefs[i].red > maxv ?
1255 65535 :
1256 xr->cdefs[i].red * sf;
1257 xr->cdefs[i].green = xr->cdefs[i].green > maxv ?
1258 65535 :
1259 xr->cdefs[i].green * sf;
1260 xr->cdefs[i].blue = xr->cdefs[i].blue > maxv ?
1261 65535 :
1262 xr->cdefs[i].blue * sf;
1263 }
1264 XStoreColors(thedisplay, xr->cmap, xr->cdefs, xr->ncolors);
1265 }
1266
1267
1268 getscan(y)
1269 int y;
1270 {
1271 static int trunced = -1; /* truncated file? */
1272 skipit:
1273 if (trunced >= 0 && y >= trunced) {
1274 bzero(scanline, xmax*sizeof(COLR));
1275 return(-1);
1276 }
1277 if (y != cury) {
1278 if (scanpos == NULL || scanpos[y] == -1)
1279 return(-1);
1280 if (fseek(fin, scanpos[y], 0) == -1)
1281 quiterr("fseek error");
1282 cury = y;
1283 } else if (scanpos != NULL && scanpos[y] == -1)
1284 scanpos[y] = ftell(fin);
1285
1286 if (freadcolrs(scanline, xmax, fin) < 0) {
1287 fprintf(stderr, "%s: %s: unfinished picture\n",
1288 progname, fname==NULL?"<stdin>":fname);
1289 trunced = y;
1290 goto skipit;
1291 }
1292 cury++;
1293 return(0);
1294 }