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