chiark / gitweb /
e269e25a77e347515ad70a1e3617e96435e8ff3d
[moebius2.git] / view.c
1 /*
2  * Displays a conformation
3  */
4
5 #include <X11/Xlib.h>
6 #include <X11/Xutil.h>
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <sys/poll.h>
11
12 #include "mgraph.h"
13
14 #define MAXTRIS (N*2)
15
16 typedef struct { double vertex[3][D3]; } Triangle;
17
18 static Triangle trisbuffer[MAXTRIS], *displaylist[MAXTRIS];
19 static int ntris;
20 static Vertices conformation;
21
22 static double transform[D3][D3]= {{1,0,0}, {0,1,0}, {0,0,1}};
23 static GSL_MATRIX(transform);
24
25 static FILE *input_f;
26 static struct stat input_stab;
27 static const char *input_filename;
28
29 static void read_input(void) {
30   int r;
31   
32   if (input_f) fclose(input_f);
33   input_f= fopen(input_filename, "rb");  if (!input_f) diee("input file");
34
35   if (fstat(fileno(input_f), &input_stab)) diee("fstat input file");
36
37   errno= 0;
38   r= fread(&conformation,sizeof(conformation),1,input_f);
39   if (r!=1) diee("fread");
40 }
41
42 static void transform_coordinates(void) {
43   double result[D3];
44   GSL_VECTOR(result);
45   gsl_vector input_gsl= { D3,1 };
46
47   int v, k;
48   
49   FOR_VERTEX(v) {
50     input_gsl.data= &conformation[v][0];
51     GA( gsl_blas_dgemv(CblasNoTrans, 1.0,&transform_gsl, &input_gsl,
52                        0.0, &result_gsl) );
53     K conformation[v][k]= result[k];
54   }
55 }
56
57 static void addtriangle(int va, int vb, int vc) {
58   Triangle *t= &trisbuffer[ntris];
59   int k;
60   
61   assert(ntris < MAXTRIS);
62   K {
63     t->vertex[0][k]= conformation[va][k];
64     t->vertex[1][k]= conformation[vb][k];
65     t->vertex[2][k]= conformation[vc][k];
66   }
67   displaylist[ntris++]= t;
68 }
69
70 static void generate_display_list(void) {
71   int vb, ve[3], e;
72
73   ntris= 0;
74   FOR_VERTEX(vb) {
75     /* We use the two triangles in the parallelogram vb, vb+e0, vb+e1, vb+e2.
76      * We go round each triangle clockwise (although our surface is non-
77      * orientable so it shouldn't matter).
78      */
79     for (e=0; e<3; e++) ve[e]= EDGE_END2(vb,e);
80     if (ve[1]>=0) {
81       if (ve[0]>=0) addtriangle(vb,ve[0],ve[1]);
82       if (ve[2]>=0) addtriangle(vb,ve[1],ve[2]);
83     }
84   }
85 }    
86
87 static int dl_compare(const void *tav, const void *tbv) {
88   int i;
89   const Triangle *const *tap= tav, *ta= *tap;
90   const Triangle *const *tbp= tbp, *tb= *tbp;
91   double za=0, zb=0;
92   for (i=0; i<3; i++) {
93     za += ta->vertex[i][2];
94     zb += tb->vertex[i][2];
95   }
96   return za > zb ? -1 :
97          za < zb ? +1 : 0;
98 }
99
100 static void sort_display_list(void) {
101   qsort(displaylist, ntris, sizeof(*displaylist), dl_compare);
102 }
103
104 /*---------- X stuff ----------*/
105
106 #define WSZ 400
107
108 typedef struct { GC fillgc, linegc; } DrawingMode;
109
110 static Display *display;
111 static Pixmap pixmap, doublebuffers[2];
112 static Window window;
113
114 static DrawingMode dmred, dmblue, dmwhite;
115 static const DrawingMode *dmcurrent;
116 static int wwidth=WSZ, wheight=WSZ, wmindim=WSZ, wmaxdim=WSZ;
117 static int ncut, currentbuffer, x11depth, x11screen;
118 XVisualInfo visinfo;
119
120 static double sizeadj_scale= 0.3, eyes_apart, scale_wmindim;
121 static double eye_z= -10, eye_x=0;
122 static double cut_z= -9;
123 static const double eyes_apart_preferred=0.05, eyes_apart_min= -0.02;
124
125
126 static void drawtriangle(const Triangle *t) {
127   XPoint points[4];
128   int i;
129
130   for (i=0; i<3; i++) {
131     double *v= t->vertex[i];
132     double x= v[0];
133     double y= v[1];
134     double z= v[2];
135
136     if (z < cut_z) { ncut++; return; }
137     
138     double zezezp= eye_z / (eye_z - z);
139     points[i].x= scale_wmindim * (zezezp * (x - eye_x) + eye_x) + wwidth/2;
140     points[i].y= scale_wmindim * (zezezp *  y                 ) + wheight/2;
141   }
142   points[3]= points[0];
143
144   XA( XFillPolygon(display,pixmap, dmcurrent->fillgc,
145                    points,3,Convex,CoordModeOrigin) );
146   XA( XDrawLines(display,pixmap, dmcurrent->linegc,
147                  points, 4,CoordModeOrigin) );
148 }
149
150 static const unsigned long core_event_mask=
151   ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ButtonMotionMask|
152   KeyPressMask;
153
154 static void mkpixmaps(void) {
155   for (currentbuffer=0; currentbuffer<2; currentbuffer++) {
156     XA( pixmap= XCreatePixmap(display,window,wwidth,wheight,x11depth) );
157     doublebuffers[currentbuffer]= pixmap;
158   }
159   currentbuffer= 0;
160 }
161
162 static void mkgcs(DrawingMode *dm, unsigned long planes) {
163   XGCValues gcv;
164
165   gcv.function= GXcopy;
166   gcv.foreground= WhitePixel(display,x11screen);
167   gcv.plane_mask= planes;
168   dm->linegc= XCreateGC(display,pixmap,
169                         GCFunction|GCForeground|GCPlaneMask,
170                         &gcv);
171
172   gcv.function= GXclear;
173   dm->fillgc= XCreateGC(display,pixmap,
174                         GCFunction|GCPlaneMask,
175                         &gcv);
176 }
177
178 static void display_prepare(void) {
179   XSetWindowAttributes wa;
180   XSizeHints hints;
181   
182   XA( display= XOpenDisplay(0) );
183   x11screen= DefaultScreen(display);
184   x11depth= DefaultDepth(display,x11screen);
185   XA( XMatchVisualInfo(display,x11screen,x11depth, TrueColor,&visinfo) );
186   
187   wa.event_mask= core_event_mask;
188   XA( window= XCreateWindow(display, DefaultRootWindow(display),
189                             0,0, wwidth,wheight, 0,x11depth,
190                             InputOutput, visinfo.visual,
191                             CWEventMask, &wa) );
192
193   hints.flags= USPosition;
194   hints.x= 10;
195   hints.y= 10;
196   XSetWMNormalHints(display,window,&hints);
197
198   mkpixmaps();
199
200   mkgcs(&dmwhite, AllPlanes);
201   mkgcs(&dmblue, visinfo.blue_mask);
202   mkgcs(&dmred, visinfo.red_mask);
203 }
204
205 static void drawtriangles(const DrawingMode *dm) {
206   Triangle *const *t;
207   int i;
208
209   dmcurrent= dm;
210   for (i=0, t=displaylist, ncut=0; i<ntris; i++, t++)
211     drawtriangle(*t);
212 }
213
214 static void display_conformation(void) {
215   pixmap= doublebuffers[currentbuffer];
216
217   XA( XFillRectangle(display,pixmap,dmwhite.fillgc,0,0,wwidth,wheight) );
218
219   if (eyes_apart > 0) {
220     const double stationary= 0.07;
221
222     eye_x= eyes_apart < eyes_apart_preferred
223               ? eyes_apart :
224            eyes_apart < (eyes_apart_preferred + stationary)
225               ? eyes_apart_preferred
226               : eyes_apart - stationary;
227     eye_x /= sizeadj_scale;
228     drawtriangles(&dmblue);
229     eye_x= -eye_x;
230     drawtriangles(&dmred);
231   } else {
232     drawtriangles(&dmwhite);
233     printf("shown, %d/%d triangles cut\n", ncut, ntris);
234   }
235   
236   XA( XSetWindowBackgroundPixmap(display,window,pixmap) );
237   XA( XClearWindow(display,window) );
238   currentbuffer= !currentbuffer;
239 }
240
241 static void show(void) {
242   scale_wmindim= sizeadj_scale * wmindim;
243   read_input();
244   transform_coordinates();
245   generate_display_list();
246   sort_display_list();
247   display_conformation();
248 }
249
250 typedef struct {
251   const char *name;
252   void (*start)(const XButtonEvent *e);
253   void (*delta)(double dx, double dy);
254   void (*conclude)(void);
255   void (*abandon)(void);
256 } Drag;
257
258 #define DRAG(x)                                 \
259   static const Drag drag_##x= {                 \
260     #x, drag_##x##_start, drag_##x##_delta,     \
261     drag_##x##_conclude, drag_##x##_abandon     \
262   }
263
264 #define DRAG_SAVING(x, thing, hook)                     \
265   static typeof(thing) original_##thing;                \
266   static void drag_##x##_start(const XButtonEvent *e) { \
267     memcpy(&original_##thing, &thing, sizeof(thing));   \
268     hook;                                               \
269   }                                                     \
270   static void drag_##x##_conclude(void) { }             \
271   static void drag_##x##_abandon(void) {                \
272     memcpy(&thing, &original_##thing, sizeof(thing));   \
273     show();                                             \
274   }                                                     \
275   DRAG(x)
276
277 static void drag_none_start(const XButtonEvent *e) { }
278 static void drag_none_delta(double dx, double dy) { }
279 static void drag_none_conclude(void) { }
280 static void drag_none_abandon(void) { }
281 DRAG(none);
282
283 static void pvectorcore(const char *n, double v[D3]) {
284   int k;
285   printf("%10s [ ",n);
286   K printf("%# 10.10f ",v[k]);
287   printf("]\n");
288 }
289 static void pvector(const char *n, double v[D3]) {
290   pvectorcore(n,v);
291   putchar('\n');
292 }
293 static void pmatrix(const char *n, double m[D3][D3]) {
294   int j;
295   for (j=0; j<D3; j++) { pvectorcore(n,m[j]); n=""; }
296   putchar('\n');
297 }
298 #define PMATRIX(x) pmatrix(#x,x);
299
300 static double drag_transform_conv_x_z= 0;
301 static double drag_transform_conv_y_z= 0;
302
303 static void drag_transform_prep(const XButtonEvent *e) {
304   static const double factor= 2.5;
305   drag_transform_conv_x_z= MAX( MIN(e->y * factor / wheight - (factor/2),
306                                     1.0), -1.0);
307   drag_transform_conv_y_z= MAX( MIN(e->x * factor / wwidth  - (factor/2),
308                                     1.0), -1.0);
309   printf("drag_transform_conv_{x,y}_z = %g,%g\n",
310          drag_transform_conv_x_z, drag_transform_conv_y_z);
311 }
312
313 static void make_z_rotation(double rotz[D3][D3], double cz, double sz) {
314   rotz[0][0]=  cz;    rotz[0][1]=  sz;     rotz[0][2]=  0;
315   rotz[1][0]= -sz;    rotz[1][1]=  cz;     rotz[1][2]=  0;
316   rotz[2][0]=   0;    rotz[2][1]=   0;     rotz[2][2]=  1;
317 }  
318
319 static void drag_rotate_delta(double dx, double dy) {
320   /* We multiple our transformation matrix by a matrix:
321    *
322    * If we just had y movement, we would rotate about x axis:
323    *  rotation X = [  1    0   0 ]
324    *               [  0   cy  sy ]
325    *               [  0  -sy  cy ]
326    *  where cy and sy are sin and cos of y rotation
327    *
328    * But we should pre-rotate this by a rotation about the z axis
329    * to get it to the right angle (to include x rotation).  So
330    * we make cy and sy be cos() and sin(hypot(x,y)) and use
331    * with cr,sr as cos() and sin(atan2(y,y)):
332    *
333    * Ie we would do  T' = Z R^T X R T   where
334    *             or  T' = Z    C    T   where  C = R^T X R  and
335    *
336    *  adjustment R = [  cr  sr  0 ]
337    *                 [ -sr  cr  0 ]
338    *                 [  0    0  1 ]    or make_z_rotation(cr,sr)
339    *
340    *  rotation Z   = [  cz  sz  0 ]
341    *                 [ -sz  cz  0 ]
342    *                 [  0    0  1 ]    or make_z_rotation(cz,sz)
343    */
344
345   double rotx[D3][D3], adjr[D3][D3], rotz[D3][D3];
346   GSL_MATRIX(rotx);
347   GSL_MATRIX(adjr);
348   GSL_MATRIX(rotz);
349
350   static double temp[D3][D3], change[D3][D3];
351   static GSL_MATRIX(temp);
352   static GSL_MATRIX(change);
353
354   printf("\nTRANSFORM %g, %g\n", dx,dy);
355
356   double dz= -drag_transform_conv_x_z * dx +
357               drag_transform_conv_y_z * dy;
358           
359   dx *= (1 - fabs(drag_transform_conv_x_z));
360   dy *= (1 - fabs(drag_transform_conv_y_z));
361
362   double d= hypot(dx,dy);
363
364   printf(" dx,dy,dz = %g, %g, %g    d = %g\n", dx,dy,dz, d);
365
366   if (hypot(d,dz) < 1e-6) return;
367
368   printf(" no xy rotation\n");
369
370   double ang= d*2.0;
371   
372   double cy= cos(ang);
373   double sy= sin(ang);
374
375   double cr, sr;
376   if (d > 1e-6) {
377     cr= -dy / d;
378     sr=  dx / d;
379   } else {
380     cr= 1;
381     sr= 0;
382   }
383   printf("\n d=%g cy,sy=%g,%g cr,sr=%g,%g\n\n", d,cy,sy,cr,sr);
384   
385   rotx[0][0]=   1;    rotx[0][1]=   0;     rotx[0][2]=  0;
386   rotx[1][0]=   0;    rotx[1][1]=  cy;     rotx[1][2]= sy;
387   rotx[2][0]=   0;    rotx[2][1]= -sy;     rotx[2][2]= cy;
388   PMATRIX(rotx);
389
390   make_z_rotation(adjr,cr,sr);
391   PMATRIX(adjr);
392
393   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
394                      &rotx_gsl,&adjr_gsl,
395                      0.0, &temp_gsl) );
396   pmatrix("X R", temp);
397   
398   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
399                      &adjr_gsl,&temp_gsl,
400                      0.0, &change_gsl) );
401   PMATRIX(change);
402
403   double angz= dz*2.0;
404   make_z_rotation(rotz,cos(angz),sin(angz));
405   PMATRIX(rotz);
406
407   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
408                      &rotz_gsl,&change_gsl,
409                      0.0, &temp_gsl) );
410   pmatrix("Z C", temp);
411
412   static double skew[D3][D3];
413   static GSL_MATRIX(skew);
414   
415   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
416                      &temp_gsl, &transform_gsl,
417                      0.0, &skew_gsl) );
418   PMATRIX(skew);
419
420   memcpy(&transform,&skew,sizeof(transform));
421   show();
422   return;
423
424   /* Now we want to normalise skew, the result becomes new transform */
425   double svd_v[D3][D3];
426   GSL_MATRIX(svd_v);
427
428   double sigma[D3], tau[D3];
429   GSL_VECTOR(sigma);
430   GSL_VECTOR(tau);
431   
432   /* We use notation from Wikipedia Polar_decomposition
433    *     Wikipedia's  W      is GSL's U
434    *     Wikipedia's  Sigma  is GSL's S
435    *     Wikipedia's  V      is GSL's V
436    *     Wikipedia's  U      is our desired result
437    * Wikipedia which says if the SVD is    A = W Sigma V*
438    * then the polar decomposition is       A = U P
439    *   where                               P = V Sigma V*
440    *   and                                 U = W V*
441    */
442   
443   GA( gsl_linalg_SV_decomp(&skew_gsl, &svd_v_gsl, &sigma_gsl, &tau_gsl) );
444   pmatrix("W",    skew);
445   pvector("Sigma",sigma);
446   pmatrix("V",    svd_v);
447
448   /* We only need U, not P. */
449   GA( gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,
450                      &skew_gsl,&svd_v_gsl,
451                      0.0,&transform_gsl) );
452
453   pmatrix("U", transform);
454
455   printf("drag_rotate_delta...\n");
456   show();
457 }
458 DRAG_SAVING(rotate, transform, drag_transform_prep(e));
459
460 static void drag_sizeadj_delta(double dx, double dy) {
461   sizeadj_scale *= pow(3.0, -dy);
462   show();
463 }
464 DRAG_SAVING(sizeadj, sizeadj_scale, );
465
466 static void drag_3d_delta(double dx, double dy) {
467   eyes_apart += dx * 0.1;
468   if (eyes_apart < eyes_apart_min) eyes_apart= eyes_apart_min;
469   printf("sizeadj eyes_apart %g\n", eyes_apart);
470   show();
471 }
472 DRAG_SAVING(3d, eyes_apart, );
473
474 static const Drag *drag= &drag_none;
475
476 static int drag_last_x, drag_last_y;
477
478 static void drag_position(int x, int y) {
479   drag->delta((x - drag_last_x) * 1.0 / wmaxdim,
480               (y - drag_last_y) * 1.0 / wmaxdim);
481   drag_last_x= x;
482   drag_last_y= y;
483 }
484
485 static void event_button(XButtonEvent *e) {
486   if (e->window != window || !e->same_screen) return;
487   if (e->type == ButtonPress) {
488     if (e->state || drag != &drag_none) {
489       printf("drag=%s press state=0x%lx abandon\n",
490              drag->name, (unsigned long)e->state);
491       drag->abandon();
492       drag= &drag_none;
493       return;
494     }
495     switch (e->button) {
496     case Button1: drag= &drag_rotate;  break;
497     case Button2: drag= &drag_sizeadj; break;
498     case Button3: drag= &drag_3d;      break;
499     default: printf("unknown drag start %d\n", e->button);
500     }
501     printf("drag=%s press button=%lu start %d,%d\n",
502            drag->name, (unsigned long)e->button, e->x, e->y);
503     drag_last_x= e->x;
504     drag_last_y= e->y;
505     drag->start(e);
506   }
507   if (e->type == ButtonRelease) {
508     printf("drag=%s release %d,%d\n", drag->name, e->x, e->y);
509     drag_position(e->x, e->y);
510     drag->conclude();
511     drag= &drag_none;
512   }
513 }
514
515 static void event_motion(int x, int y) {
516   printf("drag=%s motion %d,%d\n", drag->name, x, y);
517   drag_position(x,y);
518 }
519
520 static void event_key(XKeyEvent *e) {
521   KeySym ks;
522   char buf[10];
523   int r;
524
525   r= XLookupString(e,buf,sizeof(buf)-1,&ks,0);
526   if (!r) {
527     printf("XLookupString keycode=%u state=0x%x gave %d\n",
528            e->keycode, e->state, r);
529     return;
530   }
531
532   if (!strcmp(buf,"q")) exit(0);
533   if (!strcmp(buf,"d")) {
534     eyes_apart= eyes_apart>0 ? eyes_apart_min : eyes_apart_preferred;
535     show();
536     return;
537   }
538 }
539
540 static void event_config(XConfigureEvent *e) {
541   if (e->width == wwidth && e->height == wheight)
542     return;
543
544   wwidth= e->width;  wheight= e->height;
545   wmaxdim= wwidth > wheight ? wwidth : wheight;
546   wmindim= wwidth < wheight ? wwidth : wheight;
547   
548   XA( XSetWindowBackground(display,window,BlackPixel(display,x11screen)) );
549   for (currentbuffer=0; currentbuffer<2; currentbuffer++)
550     XA( XFreePixmap(display, doublebuffers[currentbuffer]) );
551
552   mkpixmaps();
553   show();
554 }
555
556 static void check_input(void) {
557   struct stat newstab;
558   int r;
559
560   r= stat(input_filename, &newstab);
561   if (r<0) diee("could not check input");
562
563 #define CI(x) if (newstab.st_##x == input_stab.st_##x) ; else goto changed
564   CI(dev);
565   CI(ino);
566   CI(size);
567   CI(mtime);
568 #undef CI
569   return;
570
571  changed:
572   show();
573 }
574
575 int main(int argc, const char *const *argv) {
576   static const int wantedevents= POLLIN|POLLPRI|POLLERR|POLLHUP;
577
578   XEvent event;
579   int k, i, r, *xfds, nxfds, polls_alloc=0;
580   struct pollfd *polls=0;
581   int motion_deferred=0, motion_x=-1, motion_y=-1;
582   
583   if (argc != 2 || argv[1][0]=='-') {
584     fputs("need filename\n",stderr); exit(8);
585   }
586   input_filename= argv[1];
587
588   read_input();
589   K transform[k][k]= 1.0;
590   display_prepare();
591   show();
592
593   XMapWindow(display,window);
594   for (;;) {
595
596     XA( XInternalConnectionNumbers(display, &xfds, &nxfds) );
597     if (polls_alloc <= nxfds) {
598       polls_alloc= nxfds + polls_alloc + 1;
599       polls= realloc(polls, sizeof(*polls) * polls_alloc);
600       if (!polls) diee("realloc for pollfds");
601     }
602     for (i=0; i<nxfds; i++) {
603       polls[i].fd= xfds[i];
604       polls[i].events= wantedevents;
605       polls[i].revents= 0;
606     }
607     XFree(xfds);
608
609     polls[i].fd= ConnectionNumber(display);
610     polls[i].events= wantedevents;
611
612     r= poll(polls, nxfds+1, motion_deferred ? 0 : 200);
613     if (r<0) diee("poll");
614
615     for (i=0; i<nxfds; i++)
616       if (polls[i].revents)
617         XProcessInternalConnection(display, polls[i].fd);
618
619     r= XCheckMaskEvent(display,~0UL,&event);
620     if (!r) {
621       if (motion_deferred) {
622         event_motion(motion_x, motion_y);
623         motion_deferred=0;
624       }
625       check_input();
626       continue;
627     }
628     
629     switch (event.type) {
630
631     case ButtonPress:
632     case ButtonRelease:     event_button(&event.xbutton);     break;
633       
634     case KeyPress:          event_key(&event.xkey);           break;
635
636     case ConfigureNotify:   event_config(&event.xconfigure);  break;
637
638     case MotionNotify:
639       motion_x= event.xmotion.x;
640       motion_y= event.xmotion.y;
641       motion_deferred= 1;
642       continue;
643       
644     default:
645       printf("unknown event type %u 0x%x\n", event.type,event.type);
646     }
647   }
648 }
649