]> git.tdb.fi Git - ext/subsurface.git/blob - profile.c
Plot tank pressures for multiple tanks
[ext/subsurface.git] / profile.c
1 /* profile.c */
2 /* creates all the necessary data for drawing the dive profile 
3  * uses cairo to draw it
4  */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <string.h>
9 #include <time.h>
10
11 #include "dive.h"
12 #include "display.h"
13 #include "divelist.h"
14
15 int selected_dive = 0;
16
17 typedef enum { STABLE, SLOW, MODERATE, FAST, CRAZY } velocity_t;
18 /* Plot info with smoothing, velocity indication
19  * and one-, two- and three-minute minimums and maximums */
20 struct plot_info {
21         int nr;
22         int maxtime;
23         int meandepth, maxdepth;
24         int minpressure, maxpressure;
25         int endpressure; /* start pressure better be max pressure */
26         int mintemp, maxtemp;
27         struct plot_data {
28                 unsigned int same_cylinder:1;
29                 unsigned int cylinderindex;
30                 int sec;
31                 /* pressure[0] is sensor pressure
32                  * pressure[1] is interpolated pressure */
33                 int pressure[2];
34                 int temperature;
35                 /* Depth info */
36                 int depth;
37                 int smoothed;
38                 velocity_t velocity;
39                 struct plot_data *min[3];
40                 struct plot_data *max[3];
41                 int avg[3];
42         } entry[];
43 };
44 #define SENSOR_PR 0
45 #define INTERPOLATED_PR 1
46 #define SENSOR_PRESSURE(_entry) (_entry)->pressure[SENSOR_PR]
47 #define INTERPOLATED_PRESSURE(_entry) (_entry)->pressure[INTERPOLATED_PR]
48
49 /* convert velocity to colors */
50 typedef struct { double r, g, b; } rgb_t;
51 static const rgb_t rgb[] = {
52         [STABLE]   = {0.0, 0.4, 0.0},
53         [SLOW]     = {0.4, 0.8, 0.0},
54         [MODERATE] = {0.8, 0.8, 0.0},
55         [FAST]     = {0.8, 0.5, 0.0},
56         [CRAZY]    = {1.0, 0.0, 0.0},
57 };
58
59 #define plot_info_size(nr) (sizeof(struct plot_info) + (nr)*sizeof(struct plot_data))
60
61 /* Scale to 0,0 -> maxx,maxy */
62 #define SCALEX(gc,x)  (((x)-gc->leftx)/(gc->rightx-gc->leftx)*gc->maxx)
63 #define SCALEY(gc,y)  (((y)-gc->topy)/(gc->bottomy-gc->topy)*gc->maxy)
64 #define SCALE(gc,x,y) SCALEX(gc,x),SCALEY(gc,y)
65
66 static void move_to(struct graphics_context *gc, double x, double y)
67 {
68         cairo_move_to(gc->cr, SCALE(gc, x, y));
69 }
70
71 static void line_to(struct graphics_context *gc, double x, double y)
72 {
73         cairo_line_to(gc->cr, SCALE(gc, x, y));
74 }
75
76 static void set_source_rgba(struct graphics_context *gc, double r, double g, double b, double a)
77 {
78         /*
79          * For printers, we still honor 'a', but ignore colors
80          * for now. Black is white and white is black
81          */
82         if (gc->printer) {
83                 double sum = r+g+b;
84                 if (sum > 0.8)
85                         r = g = b = 0;
86                 else
87                         r = g = b = 1;
88         }
89         cairo_set_source_rgba(gc->cr, r, g, b, a);
90 }
91
92 void set_source_rgb(struct graphics_context *gc, double r, double g, double b)
93 {
94         set_source_rgba(gc, r, g, b, 1);
95 }
96
97 #define ROUND_UP(x,y) ((((x)+(y)-1)/(y))*(y))
98
99 /*
100  * When showing dive profiles, we scale things to the
101  * current dive. However, we don't scale past less than
102  * 30 minutes or 90 ft, just so that small dives show
103  * up as such.
104  * we also need to add 180 seconds at the end so the min/max
105  * plots correctly
106  */
107 static int get_maxtime(struct plot_info *pi)
108 {
109         int seconds = pi->maxtime;
110         /* min 30 minutes, rounded up to 5 minutes, with at least 2.5 minutes to spare */
111         return MAX(30*60, ROUND_UP(seconds+150, 60*5));
112 }
113
114 static int get_maxdepth(struct plot_info *pi)
115 {
116         unsigned mm = pi->maxdepth;
117         /* Minimum 30m, rounded up to 10m, with at least 3m to spare */
118         return MAX(30000, ROUND_UP(mm+3000, 10000));
119 }
120
121 typedef struct {
122         int size;
123         double r,g,b;
124         double hpos, vpos;
125 } text_render_options_t;
126
127 #define RIGHT (-1.0)
128 #define CENTER (-0.5)
129 #define LEFT (0.0)
130
131 #define TOP (1)
132 #define MIDDLE (0)
133 #define BOTTOM (-1)
134
135 static void plot_text(struct graphics_context *gc, const text_render_options_t *tro,
136                       double x, double y, const char *fmt, ...)
137 {
138         cairo_t *cr = gc->cr;
139         cairo_font_extents_t fe;
140         cairo_text_extents_t extents;
141         double dx, dy;
142         char buffer[80];
143         va_list args;
144
145         va_start(args, fmt);
146         vsnprintf(buffer, sizeof(buffer), fmt, args);
147         va_end(args);
148
149         cairo_set_font_size(cr, tro->size);
150         cairo_font_extents(cr, &fe);
151         cairo_text_extents(cr, buffer, &extents);
152         dx = tro->hpos * extents.width + extents.x_bearing;
153         dy = tro->vpos * extents.height + fe.descent;
154
155         move_to(gc, x, y);
156         cairo_rel_move_to(cr, dx, dy);
157
158         cairo_text_path(cr, buffer);
159         set_source_rgb(gc, 0, 0, 0);
160         cairo_stroke(cr);
161
162         move_to(gc, x, y);
163         cairo_rel_move_to(cr, dx, dy);
164
165         set_source_rgb(gc, tro->r, tro->g, tro->b);
166         cairo_show_text(cr, buffer);
167 }
168
169 static void plot_one_event(struct graphics_context *gc, struct plot_info *pi, struct event *event, const text_render_options_t *tro)
170 {
171         int i, depth = 0;
172         int x,y;
173
174         for (i = 0; i < pi->nr; i++) {
175                 struct plot_data *data = pi->entry + i;
176                 if (event->time.seconds < data->sec)
177                         break;
178                 depth = data->depth;
179         }
180         /* draw a little tirangular marker and attach tooltip */
181         x = SCALEX(gc, event->time.seconds);
182         y = SCALEY(gc, depth);
183         set_source_rgba(gc, 1.0, 1.0, 0.1, 0.8);
184         cairo_move_to(gc->cr, x-15, y+6);
185         cairo_line_to(gc->cr, x-3  , y+6);
186         cairo_line_to(gc->cr, x-9, y-6);
187         cairo_line_to(gc->cr, x-15, y+6);
188         cairo_stroke_preserve(gc->cr);
189         cairo_fill(gc->cr);
190         set_source_rgba(gc, 0.0, 0.0, 0.0, 0.8);
191         cairo_move_to(gc->cr, x-9, y-3);
192         cairo_line_to(gc->cr, x-9, y+1);
193         cairo_move_to(gc->cr, x-9, y+4);
194         cairo_line_to(gc->cr, x-9, y+4);
195         cairo_stroke(gc->cr);
196         attach_tooltip(x-15, y-6, 12, 12, event->name);
197 }
198
199 static void plot_events(struct graphics_context *gc, struct plot_info *pi, struct dive *dive)
200 {
201         static const text_render_options_t tro = {14, 1.0, 0.2, 0.2, CENTER, TOP};
202         struct event *event = dive->events;
203
204         if (gc->printer)
205                 return;
206
207         while (event) {
208                 plot_one_event(gc, pi, event, &tro);
209                 event = event->next;
210         }
211 }
212
213 static void render_depth_sample(struct graphics_context *gc, struct plot_data *entry, const text_render_options_t *tro)
214 {
215         int sec = entry->sec, decimals;
216         double d;
217
218         d = get_depth_units(entry->depth, &decimals, NULL);
219
220         plot_text(gc, tro, sec, entry->depth, "%.*f", decimals, d);
221 }
222
223 static void plot_text_samples(struct graphics_context *gc, struct plot_info *pi)
224 {
225         static const text_render_options_t deep = {14, 1.0, 0.2, 0.2, CENTER, TOP};
226         static const text_render_options_t shallow = {14, 1.0, 0.2, 0.2, CENTER, BOTTOM};
227         int i;
228
229         for (i = 0; i < pi->nr; i++) {
230                 struct plot_data *entry = pi->entry + i;
231
232                 if (entry->depth < 2000)
233                         continue;
234
235                 if (entry == entry->max[2])
236                         render_depth_sample(gc, entry, &deep);
237
238                 if (entry == entry->min[2])
239                         render_depth_sample(gc, entry, &shallow);
240         }
241 }
242
243 static void plot_depth_text(struct graphics_context *gc, struct plot_info *pi)
244 {
245         int maxtime, maxdepth;
246
247         /* Get plot scaling limits */
248         maxtime = get_maxtime(pi);
249         maxdepth = get_maxdepth(pi);
250
251         gc->leftx = 0; gc->rightx = maxtime;
252         gc->topy = 0; gc->bottomy = maxdepth;
253
254         plot_text_samples(gc, pi);
255 }
256
257 static void plot_smoothed_profile(struct graphics_context *gc, struct plot_info *pi)
258 {
259         int i;
260         struct plot_data *entry = pi->entry;
261
262         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
263         move_to(gc, entry->sec, entry->smoothed);
264         for (i = 1; i < pi->nr; i++) {
265                 entry++;
266                 line_to(gc, entry->sec, entry->smoothed);
267         }
268         cairo_stroke(gc->cr);
269 }
270
271 static void plot_minmax_profile_minute(struct graphics_context *gc, struct plot_info *pi,
272                                 int index, double a)
273 {
274         int i;
275         struct plot_data *entry = pi->entry;
276
277         set_source_rgba(gc, 1, 0.2, 1, a);
278         move_to(gc, entry->sec, entry->min[index]->depth);
279         for (i = 1; i < pi->nr; i++) {
280                 entry++;
281                 line_to(gc, entry->sec, entry->min[index]->depth);
282         }
283         for (i = 1; i < pi->nr; i++) {
284                 line_to(gc, entry->sec, entry->max[index]->depth);
285                 entry--;
286         }
287         cairo_close_path(gc->cr);
288         cairo_fill(gc->cr);
289 }
290
291 static void plot_minmax_profile(struct graphics_context *gc, struct plot_info *pi)
292 {
293         if (gc->printer)
294                 return;
295         plot_minmax_profile_minute(gc, pi, 2, 0.1);
296         plot_minmax_profile_minute(gc, pi, 1, 0.1);
297         plot_minmax_profile_minute(gc, pi, 0, 0.1);
298 }
299
300 static void plot_depth_profile(struct graphics_context *gc, struct plot_info *pi)
301 {
302         int i;
303         cairo_t *cr = gc->cr;
304         int sec, depth;
305         struct plot_data *entry;
306         int maxtime, maxdepth, marker;
307
308         /* Get plot scaling limits */
309         maxtime = get_maxtime(pi);
310         maxdepth = get_maxdepth(pi);
311
312         /* Time markers: every 5 min */
313         gc->leftx = 0; gc->rightx = maxtime;
314         gc->topy = 0; gc->bottomy = 1.0;
315         for (i = 5*60; i < maxtime; i += 5*60) {
316                 move_to(gc, i, 0);
317                 line_to(gc, i, 1);
318         }
319
320         /* Depth markers: every 30 ft or 10 m*/
321         gc->leftx = 0; gc->rightx = 1.0;
322         gc->topy = 0; gc->bottomy = maxdepth;
323         switch (output_units.length) {
324         case METERS: marker = 10000; break;
325         case FEET: marker = 9144; break;        /* 30 ft */
326         }
327
328         set_source_rgba(gc, 1, 1, 1, 0.5);
329         for (i = marker; i < maxdepth; i += marker) {
330                 move_to(gc, 0, i);
331                 line_to(gc, 1, i);
332         }
333         cairo_stroke(cr);
334
335         /* Show mean depth */
336         if (! gc->printer) {
337                 set_source_rgba(gc, 1, 0.2, 0.2, 0.40);
338                 move_to(gc, 0, pi->meandepth);
339                 line_to(gc, 1, pi->meandepth);
340                 cairo_stroke(cr);
341         }
342
343         gc->leftx = 0; gc->rightx = maxtime;
344
345         /*
346          * These are good for debugging text placement etc,
347          * but not for actual display..
348          */
349         if (0) {
350                 plot_smoothed_profile(gc, pi);
351                 plot_minmax_profile(gc, pi);
352         }
353
354         set_source_rgba(gc, 1, 0.2, 0.2, 0.80);
355
356         /* Do the depth profile for the neat fill */
357         gc->topy = 0; gc->bottomy = maxdepth;
358         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
359
360         entry = pi->entry;
361         move_to(gc, 0, 0);
362         for (i = 0; i < pi->nr; i++, entry++)
363                 line_to(gc, entry->sec, entry->depth);
364         cairo_close_path(gc->cr);
365         if (gc->printer) {
366                 set_source_rgba(gc, 1, 1, 1, 0.2);
367                 cairo_fill_preserve(cr);
368                 set_source_rgb(gc, 1, 1, 1);
369                 cairo_stroke(cr);
370                 return;
371         }
372         cairo_fill(gc->cr);
373
374         /* Now do it again for the velocity colors */
375         entry = pi->entry;
376         for (i = 1; i < pi->nr; i++) {
377                 entry++;
378                 sec = entry->sec;
379                 /* we want to draw the segments in different colors
380                  * representing the vertical velocity, so we need to
381                  * chop this into short segments */
382                 rgb_t color = rgb[entry->velocity];
383                 depth = entry->depth;
384                 set_source_rgb(gc, color.r, color.g, color.b);
385                 move_to(gc, entry[-1].sec, entry[-1].depth);
386                 line_to(gc, sec, depth);
387                 cairo_stroke(cr);
388         }
389 }
390
391 static int setup_temperature_limits(struct graphics_context *gc, struct plot_info *pi)
392 {
393         int maxtime, mintemp, maxtemp, delta;
394
395         /* Get plot scaling limits */
396         maxtime = get_maxtime(pi);
397         mintemp = pi->mintemp;
398         maxtemp = pi->maxtemp;
399
400         gc->leftx = 0; gc->rightx = maxtime;
401         /* Show temperatures in roughly the lower third, but make sure the scale
402            is at least somewhat reasonable */
403         delta = maxtemp - mintemp;
404         if (delta > 3000) { /* more than 3K in fluctuation */
405                 gc->topy = maxtemp + delta*2;
406                 gc->bottomy = mintemp - delta/2;
407         } else {
408                 gc->topy = maxtemp + 1500 + delta*2;
409                 gc->bottomy = mintemp - delta/2;
410         }
411
412         return maxtemp > mintemp;
413 }
414
415 static void plot_single_temp_text(struct graphics_context *gc, int sec, int mkelvin)
416 {
417         int deg;
418         const char *unit;
419         static const text_render_options_t tro = {12, 0.2, 0.2, 1.0, LEFT, TOP};
420         temperature_t temperature = { mkelvin };
421
422         if (output_units.temperature == FAHRENHEIT) {
423                 deg = to_F(temperature);
424                 unit = UTF8_DEGREE "F";
425         } else {
426                 deg = to_C(temperature);
427                 unit = UTF8_DEGREE "C";
428         }
429         plot_text(gc, &tro, sec, temperature.mkelvin, "%d%s", deg, unit);
430 }
431
432 static void plot_temperature_text(struct graphics_context *gc, struct plot_info *pi)
433 {
434         int i;
435         int last = 0, sec = 0;
436         int last_temperature = 0, last_printed_temp = 0;
437
438         if (!setup_temperature_limits(gc, pi))
439                 return;
440
441         for (i = 0; i < pi->nr; i++) {
442                 struct plot_data *entry = pi->entry+i;
443                 int mkelvin = entry->temperature;
444
445                 if (!mkelvin)
446                         continue;
447                 last_temperature = mkelvin;
448                 sec = entry->sec;
449                 if (sec < last + 300)
450                         continue;
451                 last = sec;
452                 plot_single_temp_text(gc,sec,mkelvin);
453                 last_printed_temp = mkelvin;
454         }
455         /* it would be nice to print the end temperature, if it's different */
456         if (abs(last_temperature - last_printed_temp) > 500)
457                 plot_single_temp_text(gc, sec, last_temperature);
458 }
459
460 static void plot_temperature_profile(struct graphics_context *gc, struct plot_info *pi)
461 {
462         int i;
463         cairo_t *cr = gc->cr;
464         int last = 0;
465
466         if (!setup_temperature_limits(gc, pi))
467                 return;
468
469         set_source_rgba(gc, 0.2, 0.2, 1.0, 0.8);
470         for (i = 0; i < pi->nr; i++) {
471                 struct plot_data *entry = pi->entry + i;
472                 int mkelvin = entry->temperature;
473                 int sec = entry->sec;
474                 if (!mkelvin) {
475                         if (!last)
476                                 continue;
477                         mkelvin = last;
478                 }
479                 if (last)
480                         line_to(gc, sec, mkelvin);
481                 else
482                         move_to(gc, sec, mkelvin);
483                 last = mkelvin;
484         }
485         cairo_stroke(cr);
486 }
487
488 /* gets both the actual start and end pressure as well as the scaling factors */
489 static int get_cylinder_pressure_range(struct graphics_context *gc, struct plot_info *pi)
490 {
491         gc->leftx = 0;
492         gc->rightx = get_maxtime(pi);
493
494         gc->bottomy = 0; gc->topy = pi->maxpressure * 1.5;
495         return pi->maxpressure != 0;
496 }
497
498 static void plot_pressure_helper(struct graphics_context *gc, struct plot_info *pi, int type)
499 {
500         int i;
501         int lift_pen = FALSE;
502
503         for (i = 0; i < pi->nr; i++) {
504                 int mbar;
505                 struct plot_data *entry = pi->entry + i;
506
507                 mbar = entry->pressure[type];
508                 if (!entry->same_cylinder)
509                         lift_pen = TRUE;
510                 if (!mbar) {
511                         lift_pen = TRUE;
512                         continue;
513                 }
514                 if (lift_pen) {
515                         if (i > 0 && entry->same_cylinder) {
516                                 /* if we have a previous event from the same tank,
517                                  * draw at least a short line .
518                                  * This uses the implementation detail that the
519                                  * type is either 0 or 1 */
520                                 int prev_pr;
521                                 prev_pr = (entry-1)->pressure[type] ? : (entry-1)->pressure[1 - type];
522                                 move_to(gc, (entry-1)->sec, prev_pr);
523                                 line_to(gc, entry->sec, mbar);
524                         } else
525                                 move_to(gc, entry->sec, mbar);
526                         lift_pen = FALSE;
527                 }
528                 else
529                         line_to(gc, entry->sec, mbar);
530         }
531         cairo_stroke(gc->cr);
532
533 }
534
535 static void plot_cylinder_pressure(struct graphics_context *gc, struct plot_info *pi)
536 {
537         if (!get_cylinder_pressure_range(gc, pi))
538                 return;
539
540         /* first plot the pressure readings we have from the dive computer */
541         set_source_rgba(gc, 0.2, 1.0, 0.2, 0.80);
542         plot_pressure_helper(gc, pi, SENSOR_PR);
543
544         /* then, in a different color, the interpolated values */
545         set_source_rgba(gc, 1.0, 1.0, 0.2, 0.80);
546         plot_pressure_helper(gc, pi, INTERPOLATED_PR);
547 }
548
549 static int mbar_to_PSI(int mbar)
550 {
551         pressure_t p = {mbar};
552         return to_PSI(p);
553 }
554
555 static void plot_pressure_value(struct graphics_context *gc, int mbar, int sec,
556                                 int xalign, int yalign)
557 {
558         int pressure;
559         const char *unit;
560
561         switch (output_units.pressure) {
562         case PASCAL:
563                 pressure = mbar * 100;
564                 unit = "pascal";
565                 break;
566         case BAR:
567                 pressure = (mbar + 500) / 1000;
568                 unit = "bar";
569                 break;
570         case PSI:
571                 pressure = mbar_to_PSI(mbar);
572                 unit = "psi";
573                 break;
574         }
575         text_render_options_t tro = {10, 0.2, 1.0, 0.2, xalign, yalign};
576         plot_text(gc, &tro, sec, mbar, "%d %s", pressure, unit);
577 }
578
579 static void plot_cylinder_pressure_text(struct graphics_context *gc, struct plot_info *pi)
580 {
581         int i;
582         int mbar, cyl;
583         int seen_cyl[MAX_CYLINDERS] = { FALSE, };
584         int last_pressure[MAX_CYLINDERS] = { 0, };
585         int last_time[MAX_CYLINDERS] = { 0, };
586         struct plot_data *entry;
587
588         if (!get_cylinder_pressure_range(gc, pi))
589                 return;
590
591         /* only loop over the actual events from the dive computer */
592         for (i = 2; i < pi->nr - 2; i++) {
593                 entry = pi->entry + i;
594
595                 if (!entry->same_cylinder) {
596                         cyl = entry->cylinderindex;
597                         if (!seen_cyl[cyl]) {
598                                 mbar = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
599                                 plot_pressure_value(gc, mbar, entry->sec, LEFT, BOTTOM);
600                                 seen_cyl[cyl] = TRUE;
601                         }
602                         if (i > 2) {
603                                 /* remember the last pressure and time of
604                                  * the previous cylinder */
605                                 cyl = (entry - 1)->cylinderindex;
606                                 last_pressure[cyl] =
607                                         SENSOR_PRESSURE(entry - 1) ? : INTERPOLATED_PRESSURE(entry - 1);
608                                 last_time[cyl] = (entry - 1)->sec;
609                         }
610                 }
611         }
612         cyl = entry->cylinderindex;
613         last_pressure[cyl] = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
614         last_time[cyl] = entry->sec;
615
616         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
617                 if (last_time[cyl]) {
618                         plot_pressure_value(gc, last_pressure[cyl], last_time[cyl], CENTER, TOP);
619                 }
620         }
621 }
622
623 static void analyze_plot_info_minmax_minute(struct plot_data *entry, struct plot_data *first, struct plot_data *last, int index)
624 {
625         struct plot_data *p = entry;
626         int time = entry->sec;
627         int seconds = 90*(index+1);
628         struct plot_data *min, *max;
629         int avg, nr;
630
631         /* Go back 'seconds' in time */
632         while (p > first) {
633                 if (p[-1].sec < time - seconds)
634                         break;
635                 p--;
636         }
637
638         /* Then go forward until we hit an entry past the time */
639         min = max = p;
640         avg = p->depth;
641         nr = 1;
642         while (++p < last) {
643                 int depth = p->depth;
644                 if (p->sec > time + seconds)
645                         break;
646                 avg += depth;
647                 nr ++;
648                 if (depth < min->depth)
649                         min = p;
650                 if (depth > max->depth)
651                         max = p;
652         }
653         entry->min[index] = min;
654         entry->max[index] = max;
655         entry->avg[index] = (avg + nr/2) / nr;
656 }
657
658 static void analyze_plot_info_minmax(struct plot_data *entry, struct plot_data *first, struct plot_data *last)
659 {
660         analyze_plot_info_minmax_minute(entry, first, last, 0);
661         analyze_plot_info_minmax_minute(entry, first, last, 1);
662         analyze_plot_info_minmax_minute(entry, first, last, 2);
663 }
664
665 static velocity_t velocity(int speed)
666 {
667         velocity_t v;
668
669         if (speed < -304) /* ascent faster than -60ft/min */
670                 v = CRAZY;
671         else if (speed < -152) /* above -30ft/min */
672                 v = FAST;
673         else if (speed < -76) /* -15ft/min */
674                 v = MODERATE;
675         else if (speed < -25) /* -5ft/min */
676                 v = SLOW;
677         else if (speed < 25) /* very hard to find data, but it appears that the recommendations
678                                 for descent are usually about 2x ascent rate; still, we want 
679                                 stable to mean stable */
680                 v = STABLE;
681         else if (speed < 152) /* between 5 and 30ft/min is considered slow */
682                 v = SLOW;
683         else if (speed < 304) /* up to 60ft/min is moderate */
684                 v = MODERATE;
685         else if (speed < 507) /* up to 100ft/min is fast */
686                 v = FAST;
687         else /* more than that is just crazy - you'll blow your ears out */
688                 v = CRAZY;
689
690         return v;
691 }
692 static struct plot_info *analyze_plot_info(struct plot_info *pi)
693 {
694         int i;
695         int nr = pi->nr;
696
697         /* Do pressure min/max based on the non-surface data */
698         for (i = 0; i < nr; i++) {
699                 struct plot_data *entry = pi->entry+i;
700                 int pressure = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
701                 int temperature = entry->temperature;
702
703                 if (pressure) {
704                         if (!pi->minpressure || pressure < pi->minpressure)
705                                 pi->minpressure = pressure;
706                         if (pressure > pi->maxpressure)
707                                 pi->maxpressure = pressure;
708                 }
709
710                 if (temperature) {
711                         if (!pi->mintemp || temperature < pi->mintemp)
712                                 pi->mintemp = temperature;
713                         if (temperature > pi->maxtemp)
714                                 pi->maxtemp = temperature;
715                 }
716         }
717
718         /* Smoothing function: 5-point triangular smooth */
719         for (i = 2; i < nr; i++) {
720                 struct plot_data *entry = pi->entry+i;
721                 int depth;
722
723                 if (i < nr-2) {
724                         depth = entry[-2].depth + 2*entry[-1].depth + 3*entry[0].depth + 2*entry[1].depth + entry[2].depth;
725                         entry->smoothed = (depth+4) / 9;
726                 }
727                 /* vertical velocity in mm/sec */
728                 /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */
729                 if (entry[0].sec - entry[-1].sec) {
730                         entry->velocity = velocity((entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec));
731                         /* if our samples are short and we aren't too FAST*/
732                         if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) {
733                                 int past = -2;
734                                 while (i+past > 0 && entry[0].sec - entry[past].sec < 15)
735                                         past--;
736                                 entry->velocity = velocity((entry[0].depth - entry[past].depth) / 
737                                                         (entry[0].sec - entry[past].sec));
738                         }
739                 } else
740                         entry->velocity = STABLE;
741         }
742
743         /* One-, two- and three-minute minmax data */
744         for (i = 0; i < nr; i++) {
745                 struct plot_data *entry = pi->entry +i;
746                 analyze_plot_info_minmax(entry, pi->entry, pi->entry+nr);
747         }
748         
749         return pi;
750 }
751
752 /*
753  * simple structure to track the beginning and end tank pressure as
754  * well as the integral of depth over time spent while we have no
755  * pressure reading from the tank */
756 typedef struct pr_track_struct pr_track_t;
757 struct pr_track_struct {
758         int start;
759         int end;
760         int t_start;
761         int t_end;
762         double pressure_time;
763         pr_track_t *next;
764 };
765
766 static pr_track_t *pr_track_alloc(int start, int t_start) {
767         pr_track_t *pt = malloc(sizeof(pr_track_t));
768         pt->start = start;
769         pt->t_start = t_start;
770         pt->end = 0;
771         pt->t_end = 0;
772         pt->pressure_time = 0.0;
773         pt->next = NULL;
774         return pt;
775 }
776
777 /* poor man's linked list */
778 static pr_track_t *list_last(pr_track_t *list)
779 {
780         pr_track_t *tail = list;
781         if (!tail)
782                 return NULL;
783         while (tail->next) {
784                 tail = tail->next;
785         }
786         return tail;
787 }
788
789 static pr_track_t *list_add(pr_track_t *list, pr_track_t *element)
790 {
791         pr_track_t *tail = list_last(list);
792         if (!tail)
793                 return element;
794         tail->next = element;
795         return list;
796 }
797
798 static void list_free(pr_track_t *list)
799 {
800         if (!list)
801                 return;
802         list_free(list->next);
803         free(list);
804 }
805
806 static void fill_missing_tank_pressures(struct dive *dive, struct plot_info *pi,
807                                         pr_track_t **track_pr)
808 {
809         pr_track_t *list = NULL;
810         pr_track_t *nlist = NULL;
811         double pt, magic;
812         int cyl, i;
813         struct plot_data *entry;
814         int cur_pr[MAX_CYLINDERS];
815
816         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
817                 cur_pr[cyl] = track_pr[cyl]->start;
818         }
819         for (i = 0; i < dive->samples; i++) {
820                 entry = pi->entry + i + 2;
821                 if (SENSOR_PRESSURE(entry)) {
822                         cur_pr[entry->cylinderindex] = SENSOR_PRESSURE(entry);
823                 } else {
824                         if(!list || list->t_end < entry->sec) {
825                                 nlist = track_pr[entry->cylinderindex];
826                                 list = NULL;
827                                 while (nlist && nlist->t_start <= entry->sec) {
828                                         list = nlist;
829                                         nlist = list->next;
830                                 }
831                                 /* there may be multiple segments - so
832                                  * let's assemble the length */
833                                 nlist = list;
834                                 pt = list->pressure_time;
835                                 while (!nlist->end) {
836                                         nlist = nlist->next;
837                                         if (!nlist) {
838                                                 /* oops - we have no end pressure,
839                                                  * so this means this is a tank without
840                                                  * gas consumption information */
841                                                 break;
842                                         }
843                                         pt += nlist->pressure_time;
844                                 }
845                                 if (!nlist) {
846                                         /* just continue without calculating
847                                          * interpolated values */
848                                         list = NULL;
849                                         continue;
850                                 }
851                                 magic = (nlist->end - cur_pr[entry->cylinderindex]) / pt;                               }
852                         if (pt != 0.0) {
853                                 double cur_pt = (entry->sec - (entry-1)->sec) *
854                                         (1 + entry->depth / 10000.0);
855                                 INTERPOLATED_PRESSURE(entry) =
856                                         cur_pr[entry->cylinderindex] + cur_pt * magic;
857                                 cur_pr[entry->cylinderindex] = INTERPOLATED_PRESSURE(entry);
858                         }
859                 }
860         }
861 }
862
863 /*
864  * Create a plot-info with smoothing and ranged min/max
865  *
866  * This also makes sure that we have extra empty events on both
867  * sides, so that you can do end-points without having to worry
868  * about it.
869  */
870 static struct plot_info *create_plot_info(struct dive *dive)
871 {
872         int cylinderindex = -1;
873         int lastdepth, lastindex;
874         int i, nr = dive->samples + 4, sec, cyl;
875         size_t alloc_size = plot_info_size(nr);
876         struct plot_info *pi;
877         pr_track_t *track_pr[MAX_CYLINDERS] = {NULL, };
878         pr_track_t *pr_track, *current;
879         gboolean missing_pr = FALSE;
880         struct plot_data *entry;
881
882         pi = malloc(alloc_size);
883         if (!pi)
884                 return pi;
885         memset(pi, 0, alloc_size);
886         pi->nr = nr;
887         sec = 0;
888         lastindex = 0;
889         lastdepth = -1;
890         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) /* initialize the start pressures */
891                 track_pr[cyl] = pr_track_alloc(dive->cylinder[cyl].start.mbar, -1);
892         current = track_pr[dive->sample[0].cylinderindex];
893         for (i = 0; i < dive->samples; i++) {
894                 int depth;
895                 struct sample *sample = dive->sample+i;
896
897                 entry = pi->entry + i + 2;
898                 sec = entry->sec = sample->time.seconds;
899                 depth = entry->depth = sample->depth.mm;
900                 entry->same_cylinder = sample->cylinderindex == cylinderindex;
901                 entry->cylinderindex = cylinderindex = sample->cylinderindex;
902                 SENSOR_PRESSURE(entry) = sample->cylinderpressure.mbar;
903                 /* track the segments per cylinder and their pressure/time integral */
904                 if (!entry->same_cylinder) {
905                         current->end = SENSOR_PRESSURE(entry-1);
906                         current->t_end = (entry-1)->sec;
907                         current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
908                         track_pr[cylinderindex] = list_add(track_pr[cylinderindex], current);
909                 } else { /* same cylinder */
910                         if ((!SENSOR_PRESSURE(entry) && SENSOR_PRESSURE(entry-1)) ||
911                                 (SENSOR_PRESSURE(entry) && !SENSOR_PRESSURE(entry-1))) {
912                                 /* transmitter changed its working status */
913                                 current->end = SENSOR_PRESSURE(entry-1);
914                                 current->t_end = (entry-1)->sec;
915                                 current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
916                                 track_pr[cylinderindex] =
917                                         list_add(track_pr[cylinderindex], current);
918                         }
919                 }
920                 /* finally, do the discrete integration to get the SAC rate equivalent */
921                 current->pressure_time += (entry->sec - (entry-1)->sec) *
922                                                 (1 + entry->depth / 10000.0);
923                 missing_pr |= !SENSOR_PRESSURE(entry);
924                 entry->temperature = sample->temperature.mkelvin;
925
926                 if (depth || lastdepth)
927                         lastindex = i+2;
928
929                 lastdepth = depth;
930                 if (depth > pi->maxdepth)
931                         pi->maxdepth = depth;
932         }
933         current->t_end = entry->sec;
934         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) { /* initialize the end pressures */
935                 int pr = dive->cylinder[cyl].end.mbar;
936                 if (pr && track_pr[cyl]) {
937                         pr_track = list_last(track_pr[cyl]);
938                         pr_track->end = pr;
939                 }
940         }
941         if (lastdepth)
942                 lastindex = i + 2;
943         /* Fill in the last two entries with empty values but valid times */
944         i = dive->samples + 2;
945         pi->entry[i].sec = sec + 20;
946         pi->entry[i+1].sec = sec + 40;
947         pi->nr = lastindex+1;
948         pi->maxtime = pi->entry[lastindex].sec;
949
950         pi->endpressure = pi->minpressure = dive->cylinder[0].end.mbar;
951         pi->maxpressure = dive->cylinder[0].start.mbar;
952
953         pi->meandepth = dive->meandepth.mm;
954
955         if (missing_pr) {
956                 fill_missing_tank_pressures(dive, pi, track_pr);
957         }
958         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++)
959                 list_free(track_pr[cyl]);
960         return analyze_plot_info(pi);
961 }
962
963 void plot(struct graphics_context *gc, cairo_rectangle_int_t *drawing_area, struct dive *dive)
964 {
965         struct plot_info *pi = create_plot_info(dive);
966
967         cairo_translate(gc->cr, drawing_area->x, drawing_area->y);
968         cairo_set_line_width(gc->cr, 2);
969         cairo_set_line_cap(gc->cr, CAIRO_LINE_CAP_ROUND);
970         cairo_set_line_join(gc->cr, CAIRO_LINE_JOIN_ROUND);
971
972         /*
973          * We can use "cairo_translate()" because that doesn't
974          * scale line width etc. But the actual scaling we need
975          * do set up ourselves..
976          *
977          * Snif. What a pity.
978          */
979         gc->maxx = (drawing_area->width - 2*drawing_area->x);
980         gc->maxy = (drawing_area->height - 2*drawing_area->y);
981
982         /* Temperature profile */
983         plot_temperature_profile(gc, pi);
984
985         /* Cylinder pressure plot */
986         plot_cylinder_pressure(gc, pi);
987
988         /* Depth profile */
989         plot_depth_profile(gc, pi);
990         plot_events(gc, pi, dive);
991
992         /* Text on top of all graphs.. */
993         plot_temperature_text(gc, pi);
994         plot_depth_text(gc, pi);
995         plot_cylinder_pressure_text(gc, pi);
996
997         /* Bounding box last */
998         gc->leftx = 0; gc->rightx = 1.0;
999         gc->topy = 0; gc->bottomy = 1.0;
1000
1001         set_source_rgb(gc, 1, 1, 1);
1002         move_to(gc, 0, 0);
1003         line_to(gc, 0, 1);
1004         line_to(gc, 1, 1);
1005         line_to(gc, 1, 0);
1006         cairo_close_path(gc->cr);
1007         cairo_stroke(gc->cr);
1008
1009         free(pi);
1010 }