]> git.tdb.fi Git - ext/subsurface.git/blob - profile.c
Merge branch 'add-info-stats-page' of git://github.com/dirkhh/subsurface
[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 struct ev_select {
170         char *ev_name;
171         gboolean plot_ev;
172 };
173 static struct ev_select *ev_namelist;
174 static int evn_allocated;
175 static int evn_used;
176
177 void evn_foreach(void (*callback)(const char *, int *, void *), void *data)
178 {
179         int i;
180
181         for (i = 0; i < evn_used; i++) {
182                 callback(ev_namelist[i].ev_name, &ev_namelist[i].plot_ev, data);
183         }
184 }
185
186 void remember_event(const char *eventname)
187 {
188         int i=0, len;
189
190         if (!eventname || (len = strlen(eventname)) == 0)
191                 return;
192         while (i < evn_used) {
193                 if (!strncmp(eventname,ev_namelist[i].ev_name,len))
194                         return;
195                 i++;
196         }
197         if (evn_used == evn_allocated) {
198                 evn_allocated += 10;
199                 ev_namelist = realloc(ev_namelist, evn_allocated * sizeof(struct ev_select));
200                 if (! ev_namelist)
201                         /* we are screwed, but let's just bail out */
202                         return;
203         }
204         ev_namelist[evn_used].ev_name = strdup(eventname);
205         ev_namelist[evn_used].plot_ev = TRUE;
206         evn_used++;
207 }
208
209 static void plot_one_event(struct graphics_context *gc, struct plot_info *pi, struct event *event, const text_render_options_t *tro)
210 {
211         int i, depth = 0;
212         int x,y;
213
214         /* is plotting this event disabled? */
215         if (event->name) {
216                 for (i = 0; i < evn_used; i++) {
217                         if (! strcmp(event->name, ev_namelist[i].ev_name)) {
218                                 if (ev_namelist[i].plot_ev)
219                                         break;
220                                 else
221                                         return;
222                         }
223                 }
224         }
225         for (i = 0; i < pi->nr; i++) {
226                 struct plot_data *data = pi->entry + i;
227                 if (event->time.seconds < data->sec)
228                         break;
229                 depth = data->depth;
230         }
231         /* draw a little tirangular marker and attach tooltip */
232         x = SCALEX(gc, event->time.seconds);
233         y = SCALEY(gc, depth);
234         set_source_rgba(gc, 1.0, 1.0, 0.1, 0.8);
235         cairo_move_to(gc->cr, x-15, y+6);
236         cairo_line_to(gc->cr, x-3  , y+6);
237         cairo_line_to(gc->cr, x-9, y-6);
238         cairo_line_to(gc->cr, x-15, y+6);
239         cairo_stroke_preserve(gc->cr);
240         cairo_fill(gc->cr);
241         set_source_rgba(gc, 0.0, 0.0, 0.0, 0.8);
242         cairo_move_to(gc->cr, x-9, y-3);
243         cairo_line_to(gc->cr, x-9, y+1);
244         cairo_move_to(gc->cr, x-9, y+4);
245         cairo_line_to(gc->cr, x-9, y+4);
246         cairo_stroke(gc->cr);
247         attach_tooltip(x-15, y-6, 12, 12, event->name);
248 }
249
250 static void plot_events(struct graphics_context *gc, struct plot_info *pi, struct dive *dive)
251 {
252         static const text_render_options_t tro = {14, 1.0, 0.2, 0.2, CENTER, TOP};
253         struct event *event = dive->events;
254
255         if (gc->printer)
256                 return;
257
258         while (event) {
259                 plot_one_event(gc, pi, event, &tro);
260                 event = event->next;
261         }
262 }
263
264 static void render_depth_sample(struct graphics_context *gc, struct plot_data *entry, const text_render_options_t *tro)
265 {
266         int sec = entry->sec, decimals;
267         double d;
268
269         d = get_depth_units(entry->depth, &decimals, NULL);
270
271         plot_text(gc, tro, sec, entry->depth, "%.*f", decimals, d);
272 }
273
274 static void plot_text_samples(struct graphics_context *gc, struct plot_info *pi)
275 {
276         static const text_render_options_t deep = {14, 1.0, 0.2, 0.2, CENTER, TOP};
277         static const text_render_options_t shallow = {14, 1.0, 0.2, 0.2, CENTER, BOTTOM};
278         int i;
279
280         for (i = 0; i < pi->nr; i++) {
281                 struct plot_data *entry = pi->entry + i;
282
283                 if (entry->depth < 2000)
284                         continue;
285
286                 if (entry == entry->max[2])
287                         render_depth_sample(gc, entry, &deep);
288
289                 if (entry == entry->min[2])
290                         render_depth_sample(gc, entry, &shallow);
291         }
292 }
293
294 static void plot_depth_text(struct graphics_context *gc, struct plot_info *pi)
295 {
296         int maxtime, maxdepth;
297
298         /* Get plot scaling limits */
299         maxtime = get_maxtime(pi);
300         maxdepth = get_maxdepth(pi);
301
302         gc->leftx = 0; gc->rightx = maxtime;
303         gc->topy = 0; gc->bottomy = maxdepth;
304
305         plot_text_samples(gc, pi);
306 }
307
308 static void plot_smoothed_profile(struct graphics_context *gc, struct plot_info *pi)
309 {
310         int i;
311         struct plot_data *entry = pi->entry;
312
313         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
314         move_to(gc, entry->sec, entry->smoothed);
315         for (i = 1; i < pi->nr; i++) {
316                 entry++;
317                 line_to(gc, entry->sec, entry->smoothed);
318         }
319         cairo_stroke(gc->cr);
320 }
321
322 static void plot_minmax_profile_minute(struct graphics_context *gc, struct plot_info *pi,
323                                 int index, double a)
324 {
325         int i;
326         struct plot_data *entry = pi->entry;
327
328         set_source_rgba(gc, 1, 0.2, 1, a);
329         move_to(gc, entry->sec, entry->min[index]->depth);
330         for (i = 1; i < pi->nr; i++) {
331                 entry++;
332                 line_to(gc, entry->sec, entry->min[index]->depth);
333         }
334         for (i = 1; i < pi->nr; i++) {
335                 line_to(gc, entry->sec, entry->max[index]->depth);
336                 entry--;
337         }
338         cairo_close_path(gc->cr);
339         cairo_fill(gc->cr);
340 }
341
342 static void plot_minmax_profile(struct graphics_context *gc, struct plot_info *pi)
343 {
344         if (gc->printer)
345                 return;
346         plot_minmax_profile_minute(gc, pi, 2, 0.1);
347         plot_minmax_profile_minute(gc, pi, 1, 0.1);
348         plot_minmax_profile_minute(gc, pi, 0, 0.1);
349 }
350
351 static void plot_depth_profile(struct graphics_context *gc, struct plot_info *pi)
352 {
353         int i, incr;
354         cairo_t *cr = gc->cr;
355         int sec, depth;
356         struct plot_data *entry;
357         int maxtime, maxdepth, marker;
358         int increments[4] = { 5*60, 10*60, 15*60, 30*60 };
359
360         /* Get plot scaling limits */
361         maxtime = get_maxtime(pi);
362         maxdepth = get_maxdepth(pi);
363
364         /* Time markers: at most every 5 min, but no more than 12 markers
365          * and for convenience we do 5, 10, 15 or 30 min intervals.
366          * This allows for 6h dives - enough (I hope) for even the craziest
367          * divers - but just in case, for those 8h depth-record-breaking dives,
368          * we double the interval if this still doesn't get us to 12 or fewer
369          * time markers */
370         i = 0;
371         while (maxtime / increments[i] > 12 && i < 4)
372                 i++;
373         incr = increments[i];
374         while (maxtime / incr > 12)
375                 incr *= 2;
376
377         gc->leftx = 0; gc->rightx = maxtime;
378         gc->topy = 0; gc->bottomy = 1.0;
379         set_source_rgba(gc, 1, 1, 1, 0.5);
380         for (i = incr; i < maxtime; i += incr) {
381                 move_to(gc, i, 0);
382                 line_to(gc, i, 1);
383         }
384         cairo_stroke(cr);
385
386         /* now the text on every second time marker */
387         text_render_options_t tro = {10, 0.2, 1.0, 0.2, CENTER, TOP};
388         for (i = incr; i < maxtime; i += 2 * incr)
389                 plot_text(gc, &tro, i, 1, "%d", i/60);
390
391         /* Depth markers: every 30 ft or 10 m*/
392         gc->leftx = 0; gc->rightx = 1.0;
393         gc->topy = 0; gc->bottomy = maxdepth;
394         switch (output_units.length) {
395         case METERS: marker = 10000; break;
396         case FEET: marker = 9144; break;        /* 30 ft */
397         }
398
399         set_source_rgba(gc, 1, 1, 1, 0.5);
400         for (i = marker; i < maxdepth; i += marker) {
401                 move_to(gc, 0, i);
402                 line_to(gc, 1, i);
403         }
404         cairo_stroke(cr);
405
406         /* Show mean depth */
407         if (! gc->printer) {
408                 set_source_rgba(gc, 1, 0.2, 0.2, 0.40);
409                 move_to(gc, 0, pi->meandepth);
410                 line_to(gc, 1, pi->meandepth);
411                 cairo_stroke(cr);
412         }
413
414         gc->leftx = 0; gc->rightx = maxtime;
415
416         /*
417          * These are good for debugging text placement etc,
418          * but not for actual display..
419          */
420         if (0) {
421                 plot_smoothed_profile(gc, pi);
422                 plot_minmax_profile(gc, pi);
423         }
424
425         set_source_rgba(gc, 1, 0.2, 0.2, 0.80);
426
427         /* Do the depth profile for the neat fill */
428         gc->topy = 0; gc->bottomy = maxdepth;
429         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
430
431         entry = pi->entry;
432         move_to(gc, 0, 0);
433         for (i = 0; i < pi->nr; i++, entry++)
434                 line_to(gc, entry->sec, entry->depth);
435         cairo_close_path(gc->cr);
436         if (gc->printer) {
437                 set_source_rgba(gc, 1, 1, 1, 0.2);
438                 cairo_fill_preserve(cr);
439                 set_source_rgb(gc, 1, 1, 1);
440                 cairo_stroke(cr);
441                 return;
442         }
443         cairo_fill(gc->cr);
444
445         /* Now do it again for the velocity colors */
446         entry = pi->entry;
447         for (i = 1; i < pi->nr; i++) {
448                 entry++;
449                 sec = entry->sec;
450                 /* we want to draw the segments in different colors
451                  * representing the vertical velocity, so we need to
452                  * chop this into short segments */
453                 rgb_t color = rgb[entry->velocity];
454                 depth = entry->depth;
455                 set_source_rgb(gc, color.r, color.g, color.b);
456                 move_to(gc, entry[-1].sec, entry[-1].depth);
457                 line_to(gc, sec, depth);
458                 cairo_stroke(cr);
459         }
460 }
461
462 static int setup_temperature_limits(struct graphics_context *gc, struct plot_info *pi)
463 {
464         int maxtime, mintemp, maxtemp, delta;
465
466         /* Get plot scaling limits */
467         maxtime = get_maxtime(pi);
468         mintemp = pi->mintemp;
469         maxtemp = pi->maxtemp;
470
471         gc->leftx = 0; gc->rightx = maxtime;
472         /* Show temperatures in roughly the lower third, but make sure the scale
473            is at least somewhat reasonable */
474         delta = maxtemp - mintemp;
475         if (delta > 3000) { /* more than 3K in fluctuation */
476                 gc->topy = maxtemp + delta*2;
477                 gc->bottomy = mintemp - delta/2;
478         } else {
479                 gc->topy = maxtemp + 1500 + delta*2;
480                 gc->bottomy = mintemp - delta/2;
481         }
482
483         return maxtemp > mintemp;
484 }
485
486 static void plot_single_temp_text(struct graphics_context *gc, int sec, int mkelvin)
487 {
488         double deg;
489         const char *unit;
490         static const text_render_options_t tro = {12, 0.2, 0.2, 1.0, LEFT, TOP};
491
492         deg = get_temp_units(mkelvin, &unit);
493
494         plot_text(gc, &tro, sec, mkelvin, "%d%s", (int)(deg + 0.5), unit);
495 }
496
497 static void plot_temperature_text(struct graphics_context *gc, struct plot_info *pi)
498 {
499         int i;
500         int last = 0, sec = 0;
501         int last_temperature = 0, last_printed_temp = 0;
502
503         if (!setup_temperature_limits(gc, pi))
504                 return;
505
506         for (i = 0; i < pi->nr; i++) {
507                 struct plot_data *entry = pi->entry+i;
508                 int mkelvin = entry->temperature;
509
510                 if (!mkelvin)
511                         continue;
512                 last_temperature = mkelvin;
513                 sec = entry->sec;
514                 if (sec < last + 300)
515                         continue;
516                 last = sec;
517                 plot_single_temp_text(gc,sec,mkelvin);
518                 last_printed_temp = mkelvin;
519         }
520         /* it would be nice to print the end temperature, if it's different */
521         if (abs(last_temperature - last_printed_temp) > 500)
522                 plot_single_temp_text(gc, sec, last_temperature);
523 }
524
525 static void plot_temperature_profile(struct graphics_context *gc, struct plot_info *pi)
526 {
527         int i;
528         cairo_t *cr = gc->cr;
529         int last = 0;
530
531         if (!setup_temperature_limits(gc, pi))
532                 return;
533
534         set_source_rgba(gc, 0.2, 0.2, 1.0, 0.8);
535         for (i = 0; i < pi->nr; i++) {
536                 struct plot_data *entry = pi->entry + i;
537                 int mkelvin = entry->temperature;
538                 int sec = entry->sec;
539                 if (!mkelvin) {
540                         if (!last)
541                                 continue;
542                         mkelvin = last;
543                 }
544                 if (last)
545                         line_to(gc, sec, mkelvin);
546                 else
547                         move_to(gc, sec, mkelvin);
548                 last = mkelvin;
549         }
550         cairo_stroke(cr);
551 }
552
553 /* gets both the actual start and end pressure as well as the scaling factors */
554 static int get_cylinder_pressure_range(struct graphics_context *gc, struct plot_info *pi)
555 {
556         gc->leftx = 0;
557         gc->rightx = get_maxtime(pi);
558
559         gc->bottomy = 0; gc->topy = pi->maxpressure * 1.5;
560         return pi->maxpressure != 0;
561 }
562
563 static void plot_pressure_helper(struct graphics_context *gc, struct plot_info *pi, int type)
564 {
565         int i;
566         int lift_pen = FALSE;
567
568         for (i = 0; i < pi->nr; i++) {
569                 int mbar;
570                 struct plot_data *entry = pi->entry + i;
571
572                 mbar = entry->pressure[type];
573                 if (!entry->same_cylinder)
574                         lift_pen = TRUE;
575                 if (!mbar) {
576                         lift_pen = TRUE;
577                         continue;
578                 }
579                 if (lift_pen) {
580                         if (i > 0 && entry->same_cylinder) {
581                                 /* if we have a previous event from the same tank,
582                                  * draw at least a short line .
583                                  * This uses the implementation detail that the
584                                  * type is either 0 or 1 */
585                                 int prev_pr;
586                                 prev_pr = (entry-1)->pressure[type] ? : (entry-1)->pressure[1 - type];
587                                 move_to(gc, (entry-1)->sec, prev_pr);
588                                 line_to(gc, entry->sec, mbar);
589                         } else
590                                 move_to(gc, entry->sec, mbar);
591                         lift_pen = FALSE;
592                 }
593                 else
594                         line_to(gc, entry->sec, mbar);
595         }
596         cairo_stroke(gc->cr);
597
598 }
599
600 static void plot_cylinder_pressure(struct graphics_context *gc, struct plot_info *pi)
601 {
602         if (!get_cylinder_pressure_range(gc, pi))
603                 return;
604
605         /* first plot the pressure readings we have from the dive computer */
606         set_source_rgba(gc, 0.2, 1.0, 0.2, 0.80);
607         plot_pressure_helper(gc, pi, SENSOR_PR);
608
609         /* then, in a different color, the interpolated values */
610         set_source_rgba(gc, 1.0, 1.0, 0.2, 0.80);
611         plot_pressure_helper(gc, pi, INTERPOLATED_PR);
612 }
613
614 static void plot_pressure_value(struct graphics_context *gc, int mbar, int sec,
615                                 int xalign, int yalign)
616 {
617         int pressure;
618         const char *unit;
619
620         pressure = get_pressure_units(mbar, &unit);
621         text_render_options_t tro = {10, 0.2, 1.0, 0.2, xalign, yalign};
622         plot_text(gc, &tro, sec, mbar, "%d %s", pressure, unit);
623 }
624
625 static void plot_cylinder_pressure_text(struct graphics_context *gc, struct plot_info *pi)
626 {
627         int i;
628         int mbar, cyl;
629         int seen_cyl[MAX_CYLINDERS] = { FALSE, };
630         int last_pressure[MAX_CYLINDERS] = { 0, };
631         int last_time[MAX_CYLINDERS] = { 0, };
632         struct plot_data *entry;
633
634         if (!get_cylinder_pressure_range(gc, pi))
635                 return;
636
637         /* only loop over the actual events from the dive computer */
638         for (i = 2; i < pi->nr; i++) {
639                 entry = pi->entry + i;
640
641                 if (!entry->same_cylinder) {
642                         cyl = entry->cylinderindex;
643                         if (!seen_cyl[cyl]) {
644                                 mbar = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
645                                 plot_pressure_value(gc, mbar, entry->sec, LEFT, BOTTOM);
646                                 seen_cyl[cyl] = TRUE;
647                         }
648                         if (i > 2) {
649                                 /* remember the last pressure and time of
650                                  * the previous cylinder */
651                                 cyl = (entry - 1)->cylinderindex;
652                                 last_pressure[cyl] =
653                                         SENSOR_PRESSURE(entry - 1) ? : INTERPOLATED_PRESSURE(entry - 1);
654                                 last_time[cyl] = (entry - 1)->sec;
655                         }
656                 }
657         }
658         cyl = entry->cylinderindex;
659         last_pressure[cyl] = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
660         last_time[cyl] = entry->sec;
661
662         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
663                 if (last_time[cyl]) {
664                         plot_pressure_value(gc, last_pressure[cyl], last_time[cyl], CENTER, TOP);
665                 }
666         }
667 }
668
669 static void analyze_plot_info_minmax_minute(struct plot_data *entry, struct plot_data *first, struct plot_data *last, int index)
670 {
671         struct plot_data *p = entry;
672         int time = entry->sec;
673         int seconds = 90*(index+1);
674         struct plot_data *min, *max;
675         int avg, nr;
676
677         /* Go back 'seconds' in time */
678         while (p > first) {
679                 if (p[-1].sec < time - seconds)
680                         break;
681                 p--;
682         }
683
684         /* Then go forward until we hit an entry past the time */
685         min = max = p;
686         avg = p->depth;
687         nr = 1;
688         while (++p < last) {
689                 int depth = p->depth;
690                 if (p->sec > time + seconds)
691                         break;
692                 avg += depth;
693                 nr ++;
694                 if (depth < min->depth)
695                         min = p;
696                 if (depth > max->depth)
697                         max = p;
698         }
699         entry->min[index] = min;
700         entry->max[index] = max;
701         entry->avg[index] = (avg + nr/2) / nr;
702 }
703
704 static void analyze_plot_info_minmax(struct plot_data *entry, struct plot_data *first, struct plot_data *last)
705 {
706         analyze_plot_info_minmax_minute(entry, first, last, 0);
707         analyze_plot_info_minmax_minute(entry, first, last, 1);
708         analyze_plot_info_minmax_minute(entry, first, last, 2);
709 }
710
711 static velocity_t velocity(int speed)
712 {
713         velocity_t v;
714
715         if (speed < -304) /* ascent faster than -60ft/min */
716                 v = CRAZY;
717         else if (speed < -152) /* above -30ft/min */
718                 v = FAST;
719         else if (speed < -76) /* -15ft/min */
720                 v = MODERATE;
721         else if (speed < -25) /* -5ft/min */
722                 v = SLOW;
723         else if (speed < 25) /* very hard to find data, but it appears that the recommendations
724                                 for descent are usually about 2x ascent rate; still, we want 
725                                 stable to mean stable */
726                 v = STABLE;
727         else if (speed < 152) /* between 5 and 30ft/min is considered slow */
728                 v = SLOW;
729         else if (speed < 304) /* up to 60ft/min is moderate */
730                 v = MODERATE;
731         else if (speed < 507) /* up to 100ft/min is fast */
732                 v = FAST;
733         else /* more than that is just crazy - you'll blow your ears out */
734                 v = CRAZY;
735
736         return v;
737 }
738 static struct plot_info *analyze_plot_info(struct plot_info *pi)
739 {
740         int i;
741         int nr = pi->nr;
742
743         /* Do pressure min/max based on the non-surface data */
744         for (i = 0; i < nr; i++) {
745                 struct plot_data *entry = pi->entry+i;
746                 int pressure = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
747                 int temperature = entry->temperature;
748
749                 if (pressure) {
750                         if (!pi->minpressure || pressure < pi->minpressure)
751                                 pi->minpressure = pressure;
752                         if (pressure > pi->maxpressure)
753                                 pi->maxpressure = pressure;
754                 }
755
756                 if (temperature) {
757                         if (!pi->mintemp || temperature < pi->mintemp)
758                                 pi->mintemp = temperature;
759                         if (temperature > pi->maxtemp)
760                                 pi->maxtemp = temperature;
761                 }
762         }
763
764         /* Smoothing function: 5-point triangular smooth */
765         for (i = 2; i < nr; i++) {
766                 struct plot_data *entry = pi->entry+i;
767                 int depth;
768
769                 if (i < nr-2) {
770                         depth = entry[-2].depth + 2*entry[-1].depth + 3*entry[0].depth + 2*entry[1].depth + entry[2].depth;
771                         entry->smoothed = (depth+4) / 9;
772                 }
773                 /* vertical velocity in mm/sec */
774                 /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */
775                 if (entry[0].sec - entry[-1].sec) {
776                         entry->velocity = velocity((entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec));
777                         /* if our samples are short and we aren't too FAST*/
778                         if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) {
779                                 int past = -2;
780                                 while (i+past > 0 && entry[0].sec - entry[past].sec < 15)
781                                         past--;
782                                 entry->velocity = velocity((entry[0].depth - entry[past].depth) / 
783                                                         (entry[0].sec - entry[past].sec));
784                         }
785                 } else
786                         entry->velocity = STABLE;
787         }
788
789         /* One-, two- and three-minute minmax data */
790         for (i = 0; i < nr; i++) {
791                 struct plot_data *entry = pi->entry +i;
792                 analyze_plot_info_minmax(entry, pi->entry, pi->entry+nr);
793         }
794         
795         return pi;
796 }
797
798 /*
799  * simple structure to track the beginning and end tank pressure as
800  * well as the integral of depth over time spent while we have no
801  * pressure reading from the tank */
802 typedef struct pr_track_struct pr_track_t;
803 struct pr_track_struct {
804         int start;
805         int end;
806         int t_start;
807         int t_end;
808         double pressure_time;
809         pr_track_t *next;
810 };
811
812 static pr_track_t *pr_track_alloc(int start, int t_start) {
813         pr_track_t *pt = malloc(sizeof(pr_track_t));
814         pt->start = start;
815         pt->t_start = t_start;
816         pt->end = 0;
817         pt->t_end = 0;
818         pt->pressure_time = 0.0;
819         pt->next = NULL;
820         return pt;
821 }
822
823 /* poor man's linked list */
824 static pr_track_t *list_last(pr_track_t *list)
825 {
826         pr_track_t *tail = list;
827         if (!tail)
828                 return NULL;
829         while (tail->next) {
830                 tail = tail->next;
831         }
832         return tail;
833 }
834
835 static pr_track_t *list_add(pr_track_t *list, pr_track_t *element)
836 {
837         pr_track_t *tail = list_last(list);
838         if (!tail)
839                 return element;
840         tail->next = element;
841         return list;
842 }
843
844 static void list_free(pr_track_t *list)
845 {
846         if (!list)
847                 return;
848         list_free(list->next);
849         free(list);
850 }
851
852 static void fill_missing_tank_pressures(struct dive *dive, struct plot_info *pi,
853                                         pr_track_t **track_pr)
854 {
855         pr_track_t *list = NULL;
856         pr_track_t *nlist = NULL;
857         double pt, magic;
858         int cyl, i;
859         struct plot_data *entry;
860         int cur_pr[MAX_CYLINDERS];
861
862         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
863                 cur_pr[cyl] = track_pr[cyl]->start;
864         }
865
866         /* The first two are "fillers" */
867         for (i = 2; i < pi->nr; i++) {
868                 entry = pi->entry + i;
869                 if (SENSOR_PRESSURE(entry)) {
870                         cur_pr[entry->cylinderindex] = SENSOR_PRESSURE(entry);
871                 } else {
872                         if(!list || list->t_end < entry->sec) {
873                                 nlist = track_pr[entry->cylinderindex];
874                                 list = NULL;
875                                 while (nlist && nlist->t_start <= entry->sec) {
876                                         list = nlist;
877                                         nlist = list->next;
878                                 }
879                                 /* there may be multiple segments - so
880                                  * let's assemble the length */
881                                 nlist = list;
882                                 pt = list->pressure_time;
883                                 while (!nlist->end) {
884                                         nlist = nlist->next;
885                                         if (!nlist) {
886                                                 /* oops - we have no end pressure,
887                                                  * so this means this is a tank without
888                                                  * gas consumption information */
889                                                 break;
890                                         }
891                                         pt += nlist->pressure_time;
892                                 }
893                                 if (!nlist) {
894                                         /* just continue without calculating
895                                          * interpolated values */
896                                         list = NULL;
897                                         continue;
898                                 }
899                                 magic = (nlist->end - cur_pr[entry->cylinderindex]) / pt;                               }
900                         if (pt != 0.0) {
901                                 double cur_pt = (entry->sec - (entry-1)->sec) *
902                                         (1 + entry->depth / 10000.0);
903                                 INTERPOLATED_PRESSURE(entry) =
904                                         cur_pr[entry->cylinderindex] + cur_pt * magic;
905                                 cur_pr[entry->cylinderindex] = INTERPOLATED_PRESSURE(entry);
906                         }
907                 }
908         }
909 }
910
911 static int get_cylinder_index(struct dive *dive, struct event *ev)
912 {
913         int i;
914
915         /*
916          * Try to find a cylinder that matches the O2 percentage
917          * in the gas change event 'value' field.
918          *
919          * Crazy suunto gas change events. We really should do
920          * this in libdivecomputer or something.
921          */
922         for (i = 0; i < MAX_CYLINDERS; i++) {
923                 cylinder_t *cyl = dive->cylinder+i;
924                 int o2 = (cyl->gasmix.o2.permille + 5) / 10;
925                 if (o2 == ev->value)
926                         return i;
927         }
928
929         return 0;
930 }
931
932 static struct event *get_next_gaschange(struct event *event)
933 {
934         while (event) {
935                 if (!strcmp(event->name, "gaschange"))
936                         return event;
937                 event = event->next;
938         }
939         return event;
940 }
941
942 static int set_cylinder_index(struct plot_info *pi, int i, int cylinderindex, unsigned int end)
943 {
944         while (i < pi->nr) {
945                 struct plot_data *entry = pi->entry+i;
946                 if (entry->sec > end)
947                         break;
948                 if (entry->cylinderindex != cylinderindex) {
949                         entry->cylinderindex = cylinderindex;
950                         entry->pressure[0] = 0;
951                 }
952                 i++;
953         }
954         return i;
955 }
956
957 static void check_gas_change_events(struct dive *dive, struct plot_info *pi)
958 {
959         int i = 0, cylinderindex = 0;
960         struct event *ev = get_next_gaschange(dive->events);
961
962         if (!ev)
963                 return;
964
965         do {
966                 i = set_cylinder_index(pi, i, cylinderindex, ev->time.seconds);
967                 cylinderindex = get_cylinder_index(dive, ev);
968                 ev = get_next_gaschange(ev->next);
969         } while (ev);
970         set_cylinder_index(pi, i, cylinderindex, ~0u);
971 }
972
973 /*
974  * Create a plot-info with smoothing and ranged min/max
975  *
976  * This also makes sure that we have extra empty events on both
977  * sides, so that you can do end-points without having to worry
978  * about it.
979  */
980 static struct plot_info *create_plot_info(struct dive *dive, int nr_samples, struct sample *dive_sample)
981 {
982         int cylinderindex = -1;
983         int lastdepth, lastindex;
984         int i, nr = nr_samples + 4, sec, cyl;
985         size_t alloc_size = plot_info_size(nr);
986         struct plot_info *pi;
987         pr_track_t *track_pr[MAX_CYLINDERS] = {NULL, };
988         pr_track_t *pr_track, *current;
989         gboolean missing_pr = FALSE;
990         struct plot_data *entry = NULL;
991
992         pi = malloc(alloc_size);
993         if (!pi)
994                 return pi;
995         memset(pi, 0, alloc_size);
996         pi->nr = nr;
997         sec = 0;
998         lastindex = 0;
999         lastdepth = -1;
1000         for (i = 0; i < nr_samples; i++) {
1001                 int depth;
1002                 struct sample *sample = dive_sample+i;
1003
1004                 entry = pi->entry + i + 2;
1005                 sec = entry->sec = sample->time.seconds;
1006                 depth = entry->depth = sample->depth.mm;
1007                 entry->cylinderindex = sample->cylinderindex;
1008                 SENSOR_PRESSURE(entry) = sample->cylinderpressure.mbar;
1009                 entry->temperature = sample->temperature.mkelvin;
1010
1011                 if (depth || lastdepth)
1012                         lastindex = i+2;
1013
1014                 lastdepth = depth;
1015                 if (depth > pi->maxdepth)
1016                         pi->maxdepth = depth;
1017         }
1018
1019         check_gas_change_events(dive, pi);
1020
1021         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) /* initialize the start pressures */
1022                 track_pr[cyl] = pr_track_alloc(dive->cylinder[cyl].start.mbar, -1);
1023         current = track_pr[pi->entry[2].cylinderindex];
1024         for (i = 0; i < nr_samples; i++) {
1025                 entry = pi->entry + i + 2;
1026
1027                 entry->same_cylinder = entry->cylinderindex == cylinderindex;
1028                 cylinderindex = entry->cylinderindex;
1029
1030                 /* track the segments per cylinder and their pressure/time integral */
1031                 if (!entry->same_cylinder) {
1032                         current->end = SENSOR_PRESSURE(entry-1);
1033                         current->t_end = (entry-1)->sec;
1034                         current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1035                         track_pr[cylinderindex] = list_add(track_pr[cylinderindex], current);
1036                 } else { /* same cylinder */
1037                         if ((!SENSOR_PRESSURE(entry) && SENSOR_PRESSURE(entry-1)) ||
1038                                 (SENSOR_PRESSURE(entry) && !SENSOR_PRESSURE(entry-1))) {
1039                                 /* transmitter changed its working status */
1040                                 current->end = SENSOR_PRESSURE(entry-1);
1041                                 current->t_end = (entry-1)->sec;
1042                                 current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1043                                 track_pr[cylinderindex] =
1044                                         list_add(track_pr[cylinderindex], current);
1045                         }
1046                 }
1047                 /* finally, do the discrete integration to get the SAC rate equivalent */
1048                 current->pressure_time += (entry->sec - (entry-1)->sec) *
1049                                                 (1 + entry->depth / 10000.0);
1050                 missing_pr |= !SENSOR_PRESSURE(entry);
1051         }
1052
1053         if (entry)
1054                 current->t_end = entry->sec;
1055
1056         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) { /* initialize the end pressures */
1057                 int pr = dive->cylinder[cyl].end.mbar;
1058                 if (pr && track_pr[cyl]) {
1059                         pr_track = list_last(track_pr[cyl]);
1060                         pr_track->end = pr;
1061                 }
1062         }
1063         /* Fill in the last two entries with empty values but valid times */
1064         i = nr_samples + 2;
1065         pi->entry[i].sec = sec + 20;
1066         pi->entry[i+1].sec = sec + 40;
1067         pi->nr = lastindex+1;
1068         pi->maxtime = pi->entry[lastindex].sec;
1069
1070         pi->endpressure = pi->minpressure = dive->cylinder[0].end.mbar;
1071         pi->maxpressure = dive->cylinder[0].start.mbar;
1072
1073         pi->meandepth = dive->meandepth.mm;
1074
1075         if (missing_pr) {
1076                 fill_missing_tank_pressures(dive, pi, track_pr);
1077         }
1078         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++)
1079                 list_free(track_pr[cyl]);
1080         return analyze_plot_info(pi);
1081 }
1082
1083 void plot(struct graphics_context *gc, cairo_rectangle_int_t *drawing_area, struct dive *dive)
1084 {
1085         struct plot_info *pi;
1086         static struct sample fake[4];
1087         struct sample *sample = dive->sample;
1088         int nr = dive->samples;
1089
1090         if (!nr) {
1091                 int duration = dive->duration.seconds;
1092                 int maxdepth = dive->maxdepth.mm;
1093                 sample = fake;
1094                 fake[1].time.seconds = duration * 0.05;
1095                 fake[1].depth.mm = maxdepth;
1096                 fake[2].time.seconds = duration * 0.95;
1097                 fake[2].depth.mm = maxdepth;
1098                 fake[3].time.seconds = duration * 1.00;
1099                 nr = 4;
1100         }
1101
1102         pi = create_plot_info(dive, nr, sample);
1103
1104         cairo_translate(gc->cr, drawing_area->x, drawing_area->y);
1105         cairo_set_line_width(gc->cr, 2);
1106         cairo_set_line_cap(gc->cr, CAIRO_LINE_CAP_ROUND);
1107         cairo_set_line_join(gc->cr, CAIRO_LINE_JOIN_ROUND);
1108
1109         /*
1110          * We can use "cairo_translate()" because that doesn't
1111          * scale line width etc. But the actual scaling we need
1112          * do set up ourselves..
1113          *
1114          * Snif. What a pity.
1115          */
1116         gc->maxx = (drawing_area->width - 2*drawing_area->x);
1117         gc->maxy = (drawing_area->height - 2*drawing_area->y);
1118
1119         /* Temperature profile */
1120         plot_temperature_profile(gc, pi);
1121
1122         /* Cylinder pressure plot */
1123         plot_cylinder_pressure(gc, pi);
1124
1125         /* Depth profile */
1126         plot_depth_profile(gc, pi);
1127         plot_events(gc, pi, dive);
1128
1129         /* Text on top of all graphs.. */
1130         plot_temperature_text(gc, pi);
1131         plot_depth_text(gc, pi);
1132         plot_cylinder_pressure_text(gc, pi);
1133
1134         /* Bounding box last */
1135         gc->leftx = 0; gc->rightx = 1.0;
1136         gc->topy = 0; gc->bottomy = 1.0;
1137
1138         set_source_rgb(gc, 1, 1, 1);
1139         move_to(gc, 0, 0);
1140         line_to(gc, 0, 1);
1141         line_to(gc, 1, 1);
1142         line_to(gc, 1, 0);
1143         cairo_close_path(gc->cr);
1144         cairo_stroke(gc->cr);
1145
1146         free(pi);
1147 }