chiark / gitweb /
tidyings, more points.
[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
124 static void drawtriangle(const Triangle *t) {
125   XPoint points[4];
126   int i;
127
128   for (i=0; i<3; i++) {
129     double *v= t->vertex[i];
130     double x= v[0];
131     double y= v[1];
132     double z= v[2];
133
134     if (z < cut_z) { ncut++; return; }
135     
136     double zezezp= eye_z / (eye_z - z);
137     points[i].x= scale_wmindim * (zezezp * (x - eye_x) + eye_x) + wwidth/2;
138     points[i].y= scale_wmindim * (zezezp *  y                 ) + wheight/2;
139   }
140   points[3]= points[0];
141
142   XA( XFillPolygon(display,pixmap, dmcurrent->fillgc,
143                    points,3,Convex,CoordModeOrigin) );
144   XA( XDrawLines(display,pixmap, dmcurrent->linegc,
145                  points, 4,CoordModeOrigin) );
146 }
147
148 static const unsigned long core_event_mask=
149   ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ButtonMotionMask;
150
151 static void mkpixmaps(void) {
152   for (currentbuffer=0; currentbuffer<2; currentbuffer++) {
153     XA( pixmap= XCreatePixmap(display,window,wwidth,wheight,x11depth) );
154     doublebuffers[currentbuffer]= pixmap;
155   }
156   currentbuffer= 0;
157 }
158
159 static void mkgcs(DrawingMode *dm, unsigned long planes) {
160   XGCValues gcv;
161
162   gcv.function= GXcopy;
163   gcv.foreground= WhitePixel(display,x11screen);
164   gcv.plane_mask= planes;
165   dm->linegc= XCreateGC(display,pixmap,
166                         GCFunction|GCForeground|GCPlaneMask,
167                         &gcv);
168
169   gcv.function= GXclear;
170   dm->fillgc= XCreateGC(display,pixmap,
171                         GCFunction|GCPlaneMask,
172                         &gcv);
173 }
174
175 static void display_prepare(void) {
176   XSetWindowAttributes wa;
177   XSizeHints hints;
178   
179   XA( display= XOpenDisplay(0) );
180   x11screen= DefaultScreen(display);
181   x11depth= DefaultDepth(display,x11screen);
182   XA( XMatchVisualInfo(display,x11screen,x11depth, TrueColor,&visinfo) );
183   
184   wa.event_mask= core_event_mask;
185   XA( window= XCreateWindow(display, DefaultRootWindow(display),
186                             0,0, wwidth,wheight, 0,x11depth,
187                             InputOutput, visinfo.visual,
188                             CWEventMask, &wa) );
189
190   hints.flags= USPosition;
191   hints.x= 10;
192   hints.y= 10;
193   XSetWMNormalHints(display,window,&hints);
194
195   mkpixmaps();
196
197   mkgcs(&dmwhite, AllPlanes);
198   mkgcs(&dmblue, visinfo.blue_mask);
199   mkgcs(&dmred, visinfo.red_mask);
200 }
201
202 static void drawtriangles(const DrawingMode *dm) {
203   Triangle *const *t;
204   int i;
205
206   dmcurrent= dm;
207   for (i=0, t=displaylist, ncut=0; i<ntris; i++, t++)
208     drawtriangle(*t);
209 }
210
211 static void display_conformation(void) {
212   pixmap= doublebuffers[currentbuffer];
213
214   XA( XFillRectangle(display,pixmap,dmwhite.fillgc,0,0,wwidth,wheight) );
215
216   if (eyes_apart > 0) {
217     const double preferred=0.05, beyond=0.07;
218
219     eye_x= eyes_apart < preferred ? eyes_apart :
220            eyes_apart < beyond ? preferred :
221            eyes_apart - (beyond - preferred);
222     eye_x /= sizeadj_scale;
223     drawtriangles(&dmblue);
224     eye_x= -eye_x;
225     drawtriangles(&dmred);
226   } else {
227     drawtriangles(&dmwhite);
228     printf("shown, %d/%d triangles cut\n", ncut, ntris);
229   }
230   
231   XA( XSetWindowBackgroundPixmap(display,window,pixmap) );
232   XA( XClearWindow(display,window) );
233   currentbuffer= !currentbuffer;
234 }
235
236 static void show(void) {
237   scale_wmindim= sizeadj_scale * wmindim;
238   read_input();
239   transform_coordinates();
240   generate_display_list();
241   sort_display_list();
242   display_conformation();
243 }
244
245 typedef struct {
246   const char *name;
247   void (*start)(void);
248   void (*delta)(double dx, double dy);
249   void (*conclude)(void);
250   void (*abandon)(void);
251 } Drag;
252
253 #define DRAG(x)                                 \
254   static const Drag drag_##x= {                 \
255     #x, drag_##x##_start, drag_##x##_delta,     \
256     drag_##x##_conclude, drag_##x##_abandon     \
257   }
258
259 #define DRAG_SAVING(x, thing)                           \
260   static typeof(thing) original_##thing;                \
261   static void drag_##x##_start(void) {                  \
262     memcpy(&original_##thing, &thing, sizeof(thing));   \
263   }                                                     \
264   static void drag_##x##_conclude(void) { }             \
265   static void drag_##x##_abandon(void) {                \
266     memcpy(&thing, &original_##thing, sizeof(thing));   \
267     show();                                             \
268   }                                                     \
269   DRAG(x)
270
271 static void drag_none_start(void) { }
272 static void drag_none_delta(double dx, double dy) { }
273 static void drag_none_conclude(void) { }
274 static void drag_none_abandon(void) { }
275 DRAG(none);
276
277 static void pvectorcore(const char *n, double v[D3]) {
278   int k;
279   printf("%10s [ ",n);
280   K printf("%# 10.10f ",v[k]);
281   printf("]\n");
282 }
283 static void pvector(const char *n, double v[D3]) {
284   pvectorcore(n,v);
285   putchar('\n');
286 }
287 static void pmatrix(const char *n, double m[D3][D3]) {
288   int j;
289   for (j=0; j<D3; j++) { pvectorcore(n,m[j]); n=""; }
290   putchar('\n');
291 }
292 #define PMATRIX(x) pmatrix(#x,x);
293
294 static void drag_rotate_delta(double dx, double dy) {
295   /* We multiple our transformation matrix by a matrix:
296    *
297    * If we just had y movement, we would rotate about x axis:
298    *  rotation X = [  1    0   0 ]
299    *               [  0   cy  sy ]
300    *               [  0  -sy  cy ]
301    *  where cy and sy are sin and cos of y rotation
302    *
303    * But we should pre-rotate this by a rotation about the z axis
304    * to get it to the right angle (to include x rotation).  So
305    * we make cy and sy be cos() and sin(hypot(x,y)) and use
306    * with cr,sr as cos() and sin(atan2(y,y)):
307    *
308    * Ie we would do  T' = R^T X R T   where
309    *             or  T' =    C    T   where  C = R^T X R  and
310    *
311    *  adjustment R = [  cr  sr  0 ]
312    *                 [ -sr  cr  0 ]
313    *                 [  0    0  1 ]
314    */
315
316   double rotx[D3][D3], adjr[D3][D3];
317   GSL_MATRIX(rotx);
318   GSL_MATRIX(adjr);
319
320   static double temp[D3][D3], change[D3][D3];
321   static GSL_MATRIX(temp);
322   static GSL_MATRIX(change);
323
324   double d= hypot(dx,dy);
325   if (d < 1e-6) return;
326
327   double ang= d*2.0;
328   
329   double cy= cos(ang);
330   double sy= sin(ang);
331   double cr= -dy / d;
332   double sr=  dx / d;
333   printf("\n d=%g cy,sy=%g,%g cr,sr=%g,%g\n\n", d,cy,sy,cr,sr);
334   
335   rotx[0][0]=   1;    rotx[0][1]=   0;     rotx[0][2]=  0;
336   rotx[1][0]=   0;    rotx[1][1]=  cy;     rotx[1][2]= sy;
337   rotx[2][0]=   0;    rotx[2][1]= -sy;     rotx[2][2]= cy;
338   PMATRIX(rotx);
339
340   adjr[0][0]=  cr;    adjr[0][1]=  sr;     adjr[0][2]=  0;
341   adjr[1][0]= -sr;    adjr[1][1]=  cr;     adjr[1][2]=  0;
342   adjr[2][0]=   0;    adjr[2][1]=   0;     adjr[2][2]=  1;
343   PMATRIX(adjr);
344
345   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
346                      &rotx_gsl,&adjr_gsl,
347                      0.0, &temp_gsl) );
348   PMATRIX(temp);
349   
350   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
351                      &adjr_gsl,&temp_gsl,
352                      0.0, &change_gsl) );
353   PMATRIX(change);
354
355   static double skew[D3][D3];
356   static GSL_MATRIX(skew);
357   
358   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
359                      &change_gsl,&transform_gsl,
360                      0.0, &skew_gsl) );
361   PMATRIX(skew);
362
363   memcpy(&transform,&skew,sizeof(transform));
364   show();
365   return;
366
367   /* Now we want to normalise skew, the result becomes new transform */
368   double svd_v[D3][D3];
369   GSL_MATRIX(svd_v);
370
371   double sigma[D3], tau[D3];
372   GSL_VECTOR(sigma);
373   GSL_VECTOR(tau);
374   
375   /* We use notation from Wikipedia Polar_decomposition
376    *     Wikipedia's  W      is GSL's U
377    *     Wikipedia's  Sigma  is GSL's S
378    *     Wikipedia's  V      is GSL's V
379    *     Wikipedia's  U      is our desired result
380    * Wikipedia which says if the SVD is    A = W Sigma V*
381    * then the polar decomposition is       A = U P
382    *   where                               P = V Sigma V*
383    *   and                                 U = W V*
384    */
385   
386   GA( gsl_linalg_SV_decomp(&skew_gsl, &svd_v_gsl, &sigma_gsl, &tau_gsl) );
387   pmatrix("W",    skew);
388   pvector("Sigma",sigma);
389   pmatrix("V",    svd_v);
390
391   /* We only need U, not P. */
392   GA( gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,
393                      &skew_gsl,&svd_v_gsl,
394                      0.0,&transform_gsl) );
395
396   pmatrix("U", transform);
397
398   printf("drag_rotate_delta...\n");
399   show();
400 }
401 DRAG_SAVING(rotate, transform);
402
403 static void drag_sizeadj_delta(double dx, double dy) {
404   sizeadj_scale *= pow(3.0, -dy);
405   show();
406 }
407 DRAG_SAVING(sizeadj, sizeadj_scale);
408
409 static void drag_3d_delta(double dx, double dy) {
410   const double min_eyes_apart= -0.02;
411   eyes_apart += dx * 0.1;
412   if (eyes_apart < min_eyes_apart) eyes_apart= min_eyes_apart;
413   printf("sizeadj eyes_apart %g\n", eyes_apart);
414   show();
415 }
416 DRAG_SAVING(3d, eyes_apart);
417
418 static const Drag *drag= &drag_none;
419
420 static int drag_last_x, drag_last_y;
421
422 static void drag_position(int x, int y) {
423   drag->delta((x - drag_last_x) * 1.0 / wmaxdim,
424               (y - drag_last_y) * 1.0 / wmaxdim);
425   drag_last_x= x;
426   drag_last_y= y;
427 }
428
429 static void event_button(XButtonEvent *e) {
430   if (e->window != window || !e->same_screen) return;
431   if (e->type == ButtonPress) {
432     if (e->state || drag != &drag_none) {
433       printf("drag=%s press state=0x%lx abandon\n",
434              drag->name, (unsigned long)e->state);
435       drag->abandon();
436       drag= &drag_none;
437       return;
438     }
439     switch (e->button) {
440     case Button1: drag= &drag_rotate;  break;
441     case Button2: drag= &drag_sizeadj; break;
442     case Button3: drag= &drag_3d;      break;
443     default: printf("unknown drag start %d\n", e->button);
444     }
445     printf("drag=%s press button=%lu start %d,%d\n",
446            drag->name, (unsigned long)e->button, e->x, e->y);
447     drag_last_x= e->x;
448     drag_last_y= e->y;
449     drag->start();
450   }
451   if (e->type == ButtonRelease) {
452     printf("drag=%s release %d,%d\n", drag->name, e->x, e->y);
453     drag_position(e->x, e->y);
454     drag->conclude();
455     drag= &drag_none;
456   }
457 }
458
459 static void event_motion(int x, int y) {
460   printf("drag=%s motion %d,%d\n", drag->name, x, y);
461   drag_position(x,y);
462 }
463
464 static void event_config(XConfigureEvent *e) {
465   if (e->width == wwidth && e->height == wheight)
466     return;
467
468   wwidth= e->width;  wheight= e->height;
469   wmaxdim= wwidth > wheight ? wwidth : wheight;
470   wmindim= wwidth < wheight ? wwidth : wheight;
471   
472   XA( XSetWindowBackground(display,window,BlackPixel(display,x11screen)) );
473   for (currentbuffer=0; currentbuffer<2; currentbuffer++)
474     XA( XFreePixmap(display, doublebuffers[currentbuffer]) );
475
476   mkpixmaps();
477   show();
478 }
479
480 static void check_input(void) {
481   struct stat newstab;
482   int r;
483
484   r= stat(input_filename, &newstab);
485   if (r<0) diee("could not check input");
486
487 #define CI(x) if (newstab.st_##x == input_stab.st_##x) ; else goto changed
488   CI(dev);
489   CI(ino);
490   CI(size);
491   CI(mtime);
492 #undef CI
493   return;
494
495  changed:
496   show();
497 }
498
499 int main(int argc, const char *const *argv) {
500   static const int wantedevents= POLLIN|POLLPRI|POLLERR|POLLHUP;
501
502   XEvent event;
503   int k, i, r, *xfds, nxfds, polls_alloc=0;
504   struct pollfd *polls=0;
505   int motion_deferred=0, motion_x=-1, motion_y=-1;
506   
507   if (argc != 2 || argv[1][0]=='-') {
508     fputs("need filename\n",stderr); exit(8);
509   }
510   input_filename= argv[1];
511
512   read_input();
513   K transform[k][k]= 1.0;
514   display_prepare();
515   show();
516
517   XMapWindow(display,window);
518   for (;;) {
519
520     XA( XInternalConnectionNumbers(display, &xfds, &nxfds) );
521     if (polls_alloc <= nxfds) {
522       polls_alloc= nxfds + polls_alloc + 1;
523       polls= realloc(polls, sizeof(*polls) * polls_alloc);
524       if (!polls) diee("realloc for pollfds");
525     }
526     for (i=0; i<nxfds; i++) {
527       polls[i].fd= xfds[i];
528       polls[i].events= wantedevents;
529       polls[i].revents= 0;
530     }
531     XFree(xfds);
532
533     polls[i].fd= ConnectionNumber(display);
534     polls[i].events= wantedevents;
535
536     r= poll(polls, nxfds+1, motion_deferred ? 0 : 200);
537     if (r<0) diee("poll");
538
539     for (i=0; i<nxfds; i++)
540       if (polls[i].revents)
541         XProcessInternalConnection(display, polls[i].fd);
542
543     r= XCheckMaskEvent(display,~0UL,&event);
544     if (!r) {
545       if (motion_deferred) {
546         event_motion(motion_x, motion_y);
547         motion_deferred=0;
548       }
549       check_input();
550       continue;
551     }
552     
553     switch (event.type) {
554
555     case ButtonPress:
556     case ButtonRelease:     event_button(&event.xbutton);     break;
557       
558     case ConfigureNotify:   event_config(&event.xconfigure);  break;
559
560     case MotionNotify:
561       motion_x= event.xmotion.x;
562       motion_y= event.xmotion.y;
563       motion_deferred= 1;
564       continue;
565       
566     default:
567       printf("unknown event type %u 0x%x\n", event.type,event.type);
568     }
569   }
570 }
571