]> git.tdb.fi Git - ext/subsurface.git/blob - profile.c
Clean up color definitions
[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 #include "color.h"
15
16 int selected_dive = 0;
17
18 typedef enum { STABLE, SLOW, MODERATE, FAST, CRAZY } velocity_t;
19
20 /* Plot info with smoothing, velocity indication
21  * and one-, two- and three-minute minimums and maximums */
22 struct plot_info {
23         int nr;
24         int maxtime;
25         int meandepth, maxdepth;
26         int maxpressure;
27         int mintemp, maxtemp;
28         struct plot_data {
29                 unsigned int same_cylinder:1;
30                 unsigned int cylinderindex;
31                 int sec;
32                 /* pressure[0] is sensor pressure
33                  * pressure[1] is interpolated pressure */
34                 int pressure[2];
35                 int temperature;
36                 /* Depth info */
37                 int depth;
38                 int smoothed;
39                 velocity_t velocity;
40                 struct plot_data *min[3];
41                 struct plot_data *max[3];
42                 int avg[3];
43         } entry[];
44 };
45
46 #define SENSOR_PR 0
47 #define INTERPOLATED_PR 1
48 #define SENSOR_PRESSURE(_entry) (_entry)->pressure[SENSOR_PR]
49 #define INTERPOLATED_PRESSURE(_entry) (_entry)->pressure[INTERPOLATED_PR]
50 #define GET_PRESSURE(_entry) (SENSOR_PRESSURE(_entry) ? : INTERPOLATED_PRESSURE(_entry))
51
52 #define SAC_COLORS_START_IDX SAC_1
53 #define SAC_COLORS 9
54 #define VELOCITY_COLORS_START_IDX VELO_STABLE
55 #define VELOCITY_COLORS 5
56
57 typedef enum {
58         /* SAC colors. Order is important, the SAC_COLORS_START_IDX define above. */
59         SAC_1, SAC_2, SAC_3, SAC_4, SAC_5, SAC_6, SAC_7, SAC_8, SAC_9,
60
61         /* Velocity colors.  Order is still important, ref VELOCITY_COLORS_START_IDX. */
62         VELO_STABLE, VELO_SLOW, VELO_MODERATE, VELO_FAST, VELO_CRAZY,
63
64         /* Other colors */
65         TEXT_BACKGROUND, ALERT_BG, ALERT_FG, EVENTS, SAMPLE_DEEP, SAMPLE_SHALLOW,
66         SMOOTHED, MINUTE, TIME_GRID, TIME_TEXT, DEPTH_GRID, MEAN_DEPTH, DEPTH_TOP,
67         DEPTH_BOTTOM, TEMP_TEXT, TEMP_PLOT, SAC_DEFAULT, BOUNDING_BOX, PRESSURE_TEXT, BACKGROUND
68 } color_indice_t;
69
70 typedef struct {
71         /* media[0] is screen, and media[1] is printer */
72         struct rgba {
73                 double r,g,b,a;
74         } media[2];
75 } color_t;
76
77 /* [color indice] = {{screen color, printer color}} */
78 static const color_t profile_color[] = {
79         [SAC_1]           = {{FUNGREEN1, BLACK1_LOW_TRANS}},
80         [SAC_2]           = {{APPLE1, BLACK1_LOW_TRANS}},
81         [SAC_3]           = {{ATLANTIS1, BLACK1_LOW_TRANS}},
82         [SAC_4]           = {{ATLANTIS2, BLACK1_LOW_TRANS}},
83         [SAC_5]           = {{EARLSGREEN1, BLACK1_LOW_TRANS}},
84         [SAC_6]           = {{HOKEYPOKEY1, BLACK1_LOW_TRANS}},
85         [SAC_7]           = {{TUSCANY1, BLACK1_LOW_TRANS}},
86         [SAC_8]           = {{CINNABAR1, BLACK1_LOW_TRANS}},
87         [SAC_9]           = {{REDORANGE1, BLACK1_LOW_TRANS}},
88
89         [VELO_STABLE]     = {{CAMARONE1, BLACK1_LOW_TRANS}},
90         [VELO_SLOW]       = {{LIMENADE1, BLACK1_LOW_TRANS}},
91         [VELO_MODERATE]   = {{RIOGRANDE1, BLACK1_LOW_TRANS}},
92         [VELO_FAST]       = {{PIRATEGOLD1, BLACK1_LOW_TRANS}},
93         [VELO_CRAZY]      = {{RED1, BLACK1_LOW_TRANS}},
94
95         [TEXT_BACKGROUND] = {{CONCRETE1_LOWER_TRANS, WHITE1}},
96         [ALERT_BG]        = {{BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS}},
97         [ALERT_FG]        = {{BLACK1_LOW_TRANS, BLACK1_LOW_TRANS}},
98         [EVENTS]          = {{REDORANGE1, BLACK1_LOW_TRANS}},
99         [SAMPLE_DEEP]     = {{PERSIANRED1, BLACK1_LOW_TRANS}},
100         [SAMPLE_SHALLOW]  = {{PERSIANRED1, BLACK1_LOW_TRANS}},
101         [SMOOTHED]        = {{REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS}},
102         [MINUTE]          = {{MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS}},
103         [TIME_GRID]       = {{WHITE1, TUNDORA1_MED_TRANS}},
104         [TIME_TEXT]       = {{FORESTGREEN1, BLACK1_LOW_TRANS}},
105         [DEPTH_GRID]      = {{WHITE1, TUNDORA1_MED_TRANS}},
106         [MEAN_DEPTH]      = {{REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS}},
107         [DEPTH_BOTTOM]    = {{GOVERNORBAY1_MED_TRANS, TUNDORA1_MED_TRANS}},
108         [DEPTH_TOP]       = {{MERCURY1_MED_TRANS, WHITE1_MED_TRANS}},
109         [TEMP_TEXT]       = {{GOVERNORBAY2, BLACK1_LOW_TRANS}},
110         [TEMP_PLOT]       = {{ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS}},
111         [SAC_DEFAULT]     = {{WHITE1, BLACK1_LOW_TRANS}},
112         [BOUNDING_BOX]    = {{WHITE1, BLACK1_LOW_TRANS}},
113         [PRESSURE_TEXT]   = {{KILLARNEY1, BLACK1_LOW_TRANS}},
114         [BACKGROUND]      = {{SPRINGWOOD1, BLACK1_LOW_TRANS}},
115 };
116
117 #define plot_info_size(nr) (sizeof(struct plot_info) + (nr)*sizeof(struct plot_data))
118
119 /* Scale to 0,0 -> maxx,maxy */
120 #define SCALEX(gc,x)  (((x)-gc->leftx)/(gc->rightx-gc->leftx)*gc->maxx)
121 #define SCALEY(gc,y)  (((y)-gc->topy)/(gc->bottomy-gc->topy)*gc->maxy)
122 #define SCALE(gc,x,y) SCALEX(gc,x),SCALEY(gc,y)
123
124 static void move_to(struct graphics_context *gc, double x, double y)
125 {
126         cairo_move_to(gc->cr, SCALE(gc, x, y));
127 }
128
129 static void line_to(struct graphics_context *gc, double x, double y)
130 {
131         cairo_line_to(gc->cr, SCALE(gc, x, y));
132 }
133
134 static void set_source_rgba(struct graphics_context *gc, color_indice_t c)
135 {
136         const color_t *col = &profile_color[c];
137         struct rgba rgb = col->media[gc->printer];
138         double r = rgb.r;
139         double g = rgb.g;
140         double b = rgb.b;
141         double a = rgb.a;
142
143         cairo_set_source_rgba(gc->cr, r, g, b, a);
144 }
145
146 void init_profile_background(struct graphics_context *gc)
147 {
148         set_source_rgba(gc, BACKGROUND);
149 }
150
151 void pattern_add_color_stop_rgba(struct graphics_context *gc, cairo_pattern_t *pat, double o, color_indice_t c)
152 {
153         const color_t *col = &profile_color[c];
154         struct rgba rgb = col->media[gc->printer];
155         cairo_pattern_add_color_stop_rgba(pat, o, rgb.r, rgb.g, rgb.b, rgb.a);
156 }
157
158 #define ROUND_UP(x,y) ((((x)+(y)-1)/(y))*(y))
159
160 /* debugging tool - not normally used */
161 static void dump_pi (struct plot_info *pi)
162 {
163         int i;
164
165         printf("pi:{nr:%d maxtime:%d meandepth:%d maxdepth:%d \n"
166                 "    maxpressure:%d mintemp:%d maxtemp:%d\n",
167                 pi->nr, pi->maxtime, pi->meandepth, pi->maxdepth,
168                 pi->maxpressure, pi->mintemp, pi->maxtemp);
169         for (i = 0; i < pi->nr; i++)
170                 printf("    entry[%d]:{same_cylinder:%d cylinderindex:%d sec:%d pressure:{%d,%d}\n"
171                         "                temperature:%d depth:%d smoothed:%d}\n",
172                         i, pi->entry[i].same_cylinder, pi->entry[i].cylinderindex, pi->entry[i].sec,
173                         pi->entry[i].pressure[0], pi->entry[i].pressure[1],
174                         pi->entry[i].temperature, pi->entry[i].depth, pi->entry[i].smoothed);
175         printf("   }\n");
176 }
177
178 /*
179  * When showing dive profiles, we scale things to the
180  * current dive. However, we don't scale past less than
181  * 30 minutes or 90 ft, just so that small dives show
182  * up as such.
183  * we also need to add 180 seconds at the end so the min/max
184  * plots correctly
185  */
186 static int get_maxtime(struct plot_info *pi)
187 {
188         int seconds = pi->maxtime;
189         /* min 30 minutes, rounded up to 5 minutes, with at least 2.5 minutes to spare */
190         return MAX(30*60, ROUND_UP(seconds+150, 60*5));
191 }
192
193 static int get_maxdepth(struct plot_info *pi)
194 {
195         unsigned mm = pi->maxdepth;
196         /* Minimum 30m, rounded up to 10m, with at least 3m to spare */
197         return MAX(30000, ROUND_UP(mm+3000, 10000));
198 }
199
200 typedef struct {
201         int size;
202         color_indice_t color;
203         double hpos, vpos;
204 } text_render_options_t;
205
206 #define RIGHT (-1.0)
207 #define CENTER (-0.5)
208 #define LEFT (0.0)
209
210 #define TOP (1)
211 #define MIDDLE (0)
212 #define BOTTOM (-1)
213
214 static void plot_text(struct graphics_context *gc, const text_render_options_t *tro,
215                       double x, double y, const char *fmt, ...)
216 {
217         cairo_t *cr = gc->cr;
218         cairo_font_extents_t fe;
219         cairo_text_extents_t extents;
220         double dx, dy;
221         char buffer[80];
222         va_list args;
223
224         va_start(args, fmt);
225         vsnprintf(buffer, sizeof(buffer), fmt, args);
226         va_end(args);
227
228         cairo_set_font_size(cr, tro->size);
229         cairo_font_extents(cr, &fe);
230         cairo_text_extents(cr, buffer, &extents);
231         dx = tro->hpos * extents.width + extents.x_bearing;
232         dy = tro->vpos * extents.height + fe.descent;
233
234         move_to(gc, x, y);
235         cairo_rel_move_to(cr, dx, dy);
236
237         cairo_text_path(cr, buffer);
238         set_source_rgba(gc, TEXT_BACKGROUND);
239         cairo_stroke(cr);
240
241         move_to(gc, x, y);
242         cairo_rel_move_to(cr, dx, dy);
243
244         set_source_rgba(gc, tro->color);
245         cairo_show_text(cr, buffer);
246 }
247
248 struct ev_select {
249         char *ev_name;
250         gboolean plot_ev;
251 };
252 static struct ev_select *ev_namelist;
253 static int evn_allocated;
254 static int evn_used;
255
256 void evn_foreach(void (*callback)(const char *, int *, void *), void *data)
257 {
258         int i;
259
260         for (i = 0; i < evn_used; i++) {
261                 callback(ev_namelist[i].ev_name, &ev_namelist[i].plot_ev, data);
262         }
263 }
264
265 void remember_event(const char *eventname)
266 {
267         int i=0, len;
268
269         if (!eventname || (len = strlen(eventname)) == 0)
270                 return;
271         while (i < evn_used) {
272                 if (!strncmp(eventname,ev_namelist[i].ev_name,len))
273                         return;
274                 i++;
275         }
276         if (evn_used == evn_allocated) {
277                 evn_allocated += 10;
278                 ev_namelist = realloc(ev_namelist, evn_allocated * sizeof(struct ev_select));
279                 if (! ev_namelist)
280                         /* we are screwed, but let's just bail out */
281                         return;
282         }
283         ev_namelist[evn_used].ev_name = strdup(eventname);
284         ev_namelist[evn_used].plot_ev = TRUE;
285         evn_used++;
286 }
287
288 static void plot_one_event(struct graphics_context *gc, struct plot_info *pi, struct event *event, const text_render_options_t *tro)
289 {
290         int i, depth = 0;
291         int x,y;
292
293         /* is plotting this event disabled? */
294         if (event->name) {
295                 for (i = 0; i < evn_used; i++) {
296                         if (! strcmp(event->name, ev_namelist[i].ev_name)) {
297                                 if (ev_namelist[i].plot_ev)
298                                         break;
299                                 else
300                                         return;
301                         }
302                 }
303         }
304         for (i = 0; i < pi->nr; i++) {
305                 struct plot_data *data = pi->entry + i;
306                 if (event->time.seconds < data->sec)
307                         break;
308                 depth = data->depth;
309         }
310         /* draw a little tirangular marker and attach tooltip */
311         x = SCALEX(gc, event->time.seconds);
312         y = SCALEY(gc, depth);
313         set_source_rgba(gc, ALERT_BG);
314         cairo_move_to(gc->cr, x-15, y+6);
315         cairo_line_to(gc->cr, x-3  , y+6);
316         cairo_line_to(gc->cr, x-9, y-6);
317         cairo_line_to(gc->cr, x-15, y+6);
318         cairo_stroke_preserve(gc->cr);
319         cairo_fill(gc->cr);
320         set_source_rgba(gc, ALERT_FG);
321         cairo_move_to(gc->cr, x-9, y-3);
322         cairo_line_to(gc->cr, x-9, y+1);
323         cairo_move_to(gc->cr, x-9, y+4);
324         cairo_line_to(gc->cr, x-9, y+4);
325         cairo_stroke(gc->cr);
326         attach_tooltip(x-15, y-6, 12, 12, event->name);
327 }
328
329 static void plot_events(struct graphics_context *gc, struct plot_info *pi, struct dive *dive)
330 {
331         static const text_render_options_t tro = {14, EVENTS, CENTER, TOP};
332         struct event *event = dive->events;
333
334         if (gc->printer)
335                 return;
336
337         while (event) {
338                 plot_one_event(gc, pi, event, &tro);
339                 event = event->next;
340         }
341 }
342
343 static void render_depth_sample(struct graphics_context *gc, struct plot_data *entry, const text_render_options_t *tro)
344 {
345         int sec = entry->sec, decimals;
346         double d;
347
348         d = get_depth_units(entry->depth, &decimals, NULL);
349
350         plot_text(gc, tro, sec, entry->depth, "%.*f", decimals, d);
351 }
352
353 static void plot_text_samples(struct graphics_context *gc, struct plot_info *pi)
354 {
355         static const text_render_options_t deep = {14, SAMPLE_DEEP, CENTER, TOP};
356         static const text_render_options_t shallow = {14, SAMPLE_SHALLOW, CENTER, BOTTOM};
357         int i;
358         int last = -1;
359
360         for (i = 0; i < pi->nr; i++) {
361                 struct plot_data *entry = pi->entry + i;
362
363                 if (entry->depth < 2000)
364                         continue;
365
366                 if ((entry == entry->max[2]) && entry->depth != last) {
367                         render_depth_sample(gc, entry, &deep);
368                         last = entry->depth;
369                 }
370
371                 if ((entry == entry->min[2]) && entry->depth != last) {
372                         render_depth_sample(gc, entry, &shallow);
373                         last = entry->depth;
374                 }
375
376                 if (entry->depth != last)
377                         last = -1;
378         }
379 }
380
381 static void plot_depth_text(struct graphics_context *gc, struct plot_info *pi)
382 {
383         int maxtime, maxdepth;
384
385         /* Get plot scaling limits */
386         maxtime = get_maxtime(pi);
387         maxdepth = get_maxdepth(pi);
388
389         gc->leftx = 0; gc->rightx = maxtime;
390         gc->topy = 0; gc->bottomy = maxdepth;
391
392         plot_text_samples(gc, pi);
393 }
394
395 static void plot_smoothed_profile(struct graphics_context *gc, struct plot_info *pi)
396 {
397         int i;
398         struct plot_data *entry = pi->entry;
399
400         set_source_rgba(gc, SMOOTHED);
401         move_to(gc, entry->sec, entry->smoothed);
402         for (i = 1; i < pi->nr; i++) {
403                 entry++;
404                 line_to(gc, entry->sec, entry->smoothed);
405         }
406         cairo_stroke(gc->cr);
407 }
408
409 static void plot_minmax_profile_minute(struct graphics_context *gc, struct plot_info *pi,
410                                 int index)
411 {
412         int i;
413         struct plot_data *entry = pi->entry;
414
415         set_source_rgba(gc, MINUTE);
416         move_to(gc, entry->sec, entry->min[index]->depth);
417         for (i = 1; i < pi->nr; i++) {
418                 entry++;
419                 line_to(gc, entry->sec, entry->min[index]->depth);
420         }
421         for (i = 1; i < pi->nr; i++) {
422                 line_to(gc, entry->sec, entry->max[index]->depth);
423                 entry--;
424         }
425         cairo_close_path(gc->cr);
426         cairo_fill(gc->cr);
427 }
428
429 static void plot_minmax_profile(struct graphics_context *gc, struct plot_info *pi)
430 {
431         if (gc->printer)
432                 return;
433         plot_minmax_profile_minute(gc, pi, 2);
434         plot_minmax_profile_minute(gc, pi, 1);
435         plot_minmax_profile_minute(gc, pi, 0);
436 }
437
438 static void plot_depth_profile(struct graphics_context *gc, struct plot_info *pi)
439 {
440         int i, incr;
441         cairo_t *cr = gc->cr;
442         int sec, depth;
443         struct plot_data *entry;
444         int maxtime, maxdepth, marker;
445         int increments[4] = { 5*60, 10*60, 15*60, 30*60 };
446
447         /* Get plot scaling limits */
448         maxtime = get_maxtime(pi);
449         maxdepth = get_maxdepth(pi);
450
451         /* Time markers: at most every 5 min, but no more than 12 markers
452          * and for convenience we do 5, 10, 15 or 30 min intervals.
453          * This allows for 6h dives - enough (I hope) for even the craziest
454          * divers - but just in case, for those 8h depth-record-breaking dives,
455          * we double the interval if this still doesn't get us to 12 or fewer
456          * time markers */
457         i = 0;
458         while (maxtime / increments[i] > 12 && i < 4)
459                 i++;
460         incr = increments[i];
461         while (maxtime / incr > 12)
462                 incr *= 2;
463
464         gc->leftx = 0; gc->rightx = maxtime;
465         gc->topy = 0; gc->bottomy = 1.0;
466         set_source_rgba(gc, TIME_GRID);
467         cairo_set_line_width(gc->cr, 2);
468
469         for (i = incr; i < maxtime; i += incr) {
470                 move_to(gc, i, 0);
471                 line_to(gc, i, 1);
472         }
473         cairo_stroke(cr);
474
475         /* now the text on every second time marker */
476         text_render_options_t tro = {10, TIME_TEXT, CENTER, TOP};
477         for (i = incr; i < maxtime; i += 2 * incr)
478                 plot_text(gc, &tro, i, 1, "%d", i/60);
479
480         /* Depth markers: every 30 ft or 10 m*/
481         gc->leftx = 0; gc->rightx = 1.0;
482         gc->topy = 0; gc->bottomy = maxdepth;
483         switch (output_units.length) {
484         case METERS: marker = 10000; break;
485         case FEET: marker = 9144; break;        /* 30 ft */
486         }
487
488         set_source_rgba(gc, DEPTH_GRID);
489         for (i = marker; i < maxdepth; i += marker) {
490                 move_to(gc, 0, i);
491                 line_to(gc, 1, i);
492         }
493         cairo_stroke(cr);
494
495         /* Show mean depth */
496         if (! gc->printer) {
497                 set_source_rgba(gc, MEAN_DEPTH);
498                 move_to(gc, 0, pi->meandepth);
499                 line_to(gc, 1, pi->meandepth);
500                 cairo_stroke(cr);
501         }
502
503         gc->leftx = 0; gc->rightx = maxtime;
504
505         /*
506          * These are good for debugging text placement etc,
507          * but not for actual display..
508          */
509         if (0) {
510                 plot_smoothed_profile(gc, pi);
511                 plot_minmax_profile(gc, pi);
512         }
513
514         /* Do the depth profile for the neat fill */
515         gc->topy = 0; gc->bottomy = maxdepth;
516
517         cairo_pattern_t *pat;
518         pat = cairo_pattern_create_linear (0.0, 0.0,  0.0, 256.0);
519         pattern_add_color_stop_rgba (gc, pat, 1, DEPTH_BOTTOM);
520         pattern_add_color_stop_rgba (gc, pat, 0, DEPTH_TOP);
521
522         cairo_set_source(gc->cr, pat);
523         cairo_pattern_destroy(pat);
524         cairo_set_line_width(gc->cr, 2);
525
526         entry = pi->entry;
527         move_to(gc, 0, 0);
528         for (i = 0; i < pi->nr; i++, entry++)
529                 line_to(gc, entry->sec, entry->depth);
530         cairo_close_path(gc->cr);
531 /*
532         if (gc->printer) {
533                 set_source_rgba(gc, DEPTH_FILL_PRINTER);
534                 cairo_fill_preserve(cr);
535                 set_source_rgba(gc, DEPTH_STROKE_PRINTER);
536                 cairo_stroke(cr);
537                 return;
538         }
539 */      cairo_fill(gc->cr);
540
541         /* Now do it again for the velocity colors */
542         entry = pi->entry;
543         for (i = 1; i < pi->nr; i++) {
544                 entry++;
545                 sec = entry->sec;
546                 /* we want to draw the segments in different colors
547                  * representing the vertical velocity, so we need to
548                  * chop this into short segments */
549                 depth = entry->depth;
550                 set_source_rgba(gc, VELOCITY_COLORS_START_IDX + entry->velocity);
551                 move_to(gc, entry[-1].sec, entry[-1].depth);
552                 line_to(gc, sec, depth);
553                 cairo_stroke(cr);
554         }
555 }
556
557 static int setup_temperature_limits(struct graphics_context *gc, struct plot_info *pi)
558 {
559         int maxtime, mintemp, maxtemp, delta;
560
561         /* Get plot scaling limits */
562         maxtime = get_maxtime(pi);
563         mintemp = pi->mintemp;
564         maxtemp = pi->maxtemp;
565
566         gc->leftx = 0; gc->rightx = maxtime;
567         /* Show temperatures in roughly the lower third, but make sure the scale
568            is at least somewhat reasonable */
569         delta = maxtemp - mintemp;
570         if (delta > 3000) { /* more than 3K in fluctuation */
571                 gc->topy = maxtemp + delta*2;
572                 gc->bottomy = mintemp - delta/2;
573         } else {
574                 gc->topy = maxtemp + 1500 + delta*2;
575                 gc->bottomy = mintemp - delta/2;
576         }
577
578         return maxtemp > mintemp;
579 }
580
581 static void plot_single_temp_text(struct graphics_context *gc, int sec, int mkelvin)
582 {
583         double deg;
584         const char *unit;
585         static const text_render_options_t tro = {12, TEMP_TEXT, LEFT, TOP};
586
587         deg = get_temp_units(mkelvin, &unit);
588
589         plot_text(gc, &tro, sec, mkelvin, "%d%s", (int)(deg + 0.5), unit);
590 }
591
592 static void plot_temperature_text(struct graphics_context *gc, struct plot_info *pi)
593 {
594         int i;
595         int last = -300, sec = 0;
596         int last_temperature = 0, last_printed_temp = 0;
597
598         if (!setup_temperature_limits(gc, pi))
599                 return;
600
601         for (i = 0; i < pi->nr; i++) {
602                 struct plot_data *entry = pi->entry+i;
603                 int mkelvin = entry->temperature;
604
605                 if (!mkelvin)
606                         continue;
607                 last_temperature = mkelvin;
608                 sec = entry->sec;
609                 /* don't print a temperature
610                  * if it's been less than 5min and less than a 2K change OR
611                  * if it's been less than 2min OR if the change from the
612                  * last print is less than .4K (and therefore less than 1F */
613                 if (((sec < last + 300) && (abs(mkelvin - last_printed_temp) < 2000)) ||
614                         (sec < last + 120) ||
615                         (abs(mkelvin - last_printed_temp) < 400))
616                         continue;
617                 last = sec;
618                 plot_single_temp_text(gc,sec,mkelvin);
619                 last_printed_temp = mkelvin;
620         }
621         /* it would be nice to print the end temperature, if it's
622          * different or if the last temperature print has been more
623          * than a quarter of the dive back */
624         if ((abs(last_temperature - last_printed_temp) > 500) ||
625                 ((double)last / (double)sec < 0.75))
626                 plot_single_temp_text(gc, sec, last_temperature);
627 }
628
629 static void plot_temperature_profile(struct graphics_context *gc, struct plot_info *pi)
630 {
631         int i;
632         cairo_t *cr = gc->cr;
633         int last = 0;
634
635         if (!setup_temperature_limits(gc, pi))
636                 return;
637
638         cairo_set_line_width(gc->cr, 2);
639         set_source_rgba(gc, TEMP_PLOT);
640         for (i = 0; i < pi->nr; i++) {
641                 struct plot_data *entry = pi->entry + i;
642                 int mkelvin = entry->temperature;
643                 int sec = entry->sec;
644                 if (!mkelvin) {
645                         if (!last)
646                                 continue;
647                         mkelvin = last;
648                 }
649                 if (last)
650                         line_to(gc, sec, mkelvin);
651                 else
652                         move_to(gc, sec, mkelvin);
653                 last = mkelvin;
654         }
655         cairo_stroke(cr);
656 }
657
658 /* gets both the actual start and end pressure as well as the scaling factors */
659 static int get_cylinder_pressure_range(struct graphics_context *gc, struct plot_info *pi)
660 {
661         gc->leftx = 0;
662         gc->rightx = get_maxtime(pi);
663
664         gc->bottomy = 0; gc->topy = pi->maxpressure * 1.5;
665         return pi->maxpressure != 0;
666 }
667
668 /* set the color for the pressure plot according to temporary sac rate
669  * as compared to avg_sac; the calculation simply maps the delta between
670  * sac and avg_sac to indexes 0 .. (SAC_COLORS - 1) with everything
671  * more than 6000 ml/min below avg_sac mapped to 0 */
672
673 static void set_sac_color(struct graphics_context *gc, int sac, int avg_sac)
674 {
675         int sac_index = 0;
676         int delta = sac - avg_sac + 7000;
677
678         if (!gc->printer) {
679                 sac_index = delta / 2000;
680                 if (sac_index < 0)
681                         sac_index = 0;
682                 if (sac_index > SAC_COLORS - 1)
683                         sac_index = SAC_COLORS - 1;
684                 set_source_rgba(gc, SAC_COLORS_START_IDX + sac_index);
685         } else {
686                 set_source_rgba(gc, SAC_DEFAULT);
687         }
688 }
689
690 /* calculate the current SAC in ml/min and convert to int */
691 #define GET_LOCAL_SAC(_entry1, _entry2, _dive)  (int)                           \
692         ((GET_PRESSURE((_entry1)) - GET_PRESSURE((_entry2))) *                  \
693                 (_dive)->cylinder[(_entry1)->cylinderindex].type.size.mliter /  \
694                 (((_entry2)->sec - (_entry1)->sec) / 60.0) /                    \
695                 (1 + ((_entry1)->depth + (_entry2)->depth) / 20000.0) /         \
696                 1000.0)
697
698 #define SAC_WINDOW 45   /* sliding window in seconds for current SAC calculation */
699
700 static void plot_cylinder_pressure(struct graphics_context *gc, struct plot_info *pi,
701                                 struct dive *dive)
702 {
703         int i;
704         int last = -1;
705         int lift_pen = FALSE;
706         int first_plot = TRUE;
707         int sac = 0;
708         struct plot_data *last_entry = NULL;
709
710         if (!get_cylinder_pressure_range(gc, pi))
711                 return;
712
713         cairo_set_line_width(gc->cr, 2);
714
715         for (i = 0; i < pi->nr; i++) {
716                 int mbar;
717                 struct plot_data *entry = pi->entry + i;
718
719                 mbar = GET_PRESSURE(entry);
720                 if (!entry->same_cylinder) {
721                         lift_pen = TRUE;
722                         last_entry = NULL;
723                 }
724                 if (!mbar) {
725                         lift_pen = TRUE;
726                         continue;
727                 }
728                 if (!last_entry) {
729                         last = i;
730                         last_entry = entry;
731                         sac = GET_LOCAL_SAC(entry, pi->entry + i + 1, dive);
732                 } else {
733                         int j;
734                         sac = 0;
735                         for (j = last; j < i; j++)
736                                 sac += GET_LOCAL_SAC(pi->entry + j, pi->entry + j + 1, dive);
737                         sac /= (i - last);
738                         if (entry->sec - last_entry->sec >= SAC_WINDOW) {
739                                 last++;
740                                 last_entry = pi->entry + last;
741                         }
742                 }
743                 set_sac_color(gc, sac, dive->sac);
744                 if (lift_pen) {
745                         if (!first_plot && entry->same_cylinder) {
746                                 /* if we have a previous event from the same tank,
747                                  * draw at least a short line */
748                                 int prev_pr;
749                                 prev_pr = GET_PRESSURE(entry - 1);
750                                 move_to(gc, (entry-1)->sec, prev_pr);
751                                 line_to(gc, entry->sec, mbar);
752                         } else {
753                                 first_plot = FALSE;
754                                 move_to(gc, entry->sec, mbar);
755                         }
756                         lift_pen = FALSE;
757                 } else {
758                         line_to(gc, entry->sec, mbar);
759                 }
760                 cairo_stroke(gc->cr);
761                 move_to(gc, entry->sec, mbar);
762         }
763 }
764
765 static void plot_pressure_value(struct graphics_context *gc, int mbar, int sec,
766                                 int xalign, int yalign)
767 {
768         int pressure;
769         const char *unit;
770
771         pressure = get_pressure_units(mbar, &unit);
772         text_render_options_t tro = {10, PRESSURE_TEXT, xalign, yalign};
773         plot_text(gc, &tro, sec, mbar, "%d %s", pressure, unit);
774 }
775
776 static void plot_cylinder_pressure_text(struct graphics_context *gc, struct plot_info *pi)
777 {
778         int i;
779         int mbar, cyl;
780         int seen_cyl[MAX_CYLINDERS] = { FALSE, };
781         int last_pressure[MAX_CYLINDERS] = { 0, };
782         int last_time[MAX_CYLINDERS] = { 0, };
783         struct plot_data *entry;
784
785         if (!get_cylinder_pressure_range(gc, pi))
786                 return;
787
788         /* only loop over the actual events from the dive computer
789          * plus the second synthetic event at the start (to make sure
790          * we get "time=0" right)
791          * sadly with a recent change that first entry may no longer
792          * have any pressure reading - in that case just grab the
793          * pressure from the second entry */
794         if (GET_PRESSURE(pi->entry + 1) == 0 && GET_PRESSURE(pi->entry + 2) !=0)
795                 INTERPOLATED_PRESSURE(pi->entry + 1) = GET_PRESSURE(pi->entry + 2);
796         for (i = 1; i < pi->nr; i++) {
797                 entry = pi->entry + i;
798
799                 if (!entry->same_cylinder) {
800                         cyl = entry->cylinderindex;
801                         if (!seen_cyl[cyl]) {
802                                 mbar = GET_PRESSURE(entry);
803                                 plot_pressure_value(gc, mbar, entry->sec, LEFT, BOTTOM);
804                                 seen_cyl[cyl] = TRUE;
805                         }
806                         if (i > 2) {
807                                 /* remember the last pressure and time of
808                                  * the previous cylinder */
809                                 cyl = (entry - 1)->cylinderindex;
810                                 last_pressure[cyl] = GET_PRESSURE(entry - 1);
811                                 last_time[cyl] = (entry - 1)->sec;
812                         }
813                 }
814         }
815         cyl = entry->cylinderindex;
816         if (GET_PRESSURE(entry))
817                 last_pressure[cyl] = GET_PRESSURE(entry);
818         last_time[cyl] = entry->sec;
819
820         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
821                 if (last_time[cyl]) {
822                         plot_pressure_value(gc, last_pressure[cyl], last_time[cyl], CENTER, TOP);
823                 }
824         }
825 }
826
827 static void analyze_plot_info_minmax_minute(struct plot_data *entry, struct plot_data *first, struct plot_data *last, int index)
828 {
829         struct plot_data *p = entry;
830         int time = entry->sec;
831         int seconds = 90*(index+1);
832         struct plot_data *min, *max;
833         int avg, nr;
834
835         /* Go back 'seconds' in time */
836         while (p > first) {
837                 if (p[-1].sec < time - seconds)
838                         break;
839                 p--;
840         }
841
842         /* Then go forward until we hit an entry past the time */
843         min = max = p;
844         avg = p->depth;
845         nr = 1;
846         while (++p < last) {
847                 int depth = p->depth;
848                 if (p->sec > time + seconds)
849                         break;
850                 avg += depth;
851                 nr ++;
852                 if (depth < min->depth)
853                         min = p;
854                 if (depth > max->depth)
855                         max = p;
856         }
857         entry->min[index] = min;
858         entry->max[index] = max;
859         entry->avg[index] = (avg + nr/2) / nr;
860 }
861
862 static void analyze_plot_info_minmax(struct plot_data *entry, struct plot_data *first, struct plot_data *last)
863 {
864         analyze_plot_info_minmax_minute(entry, first, last, 0);
865         analyze_plot_info_minmax_minute(entry, first, last, 1);
866         analyze_plot_info_minmax_minute(entry, first, last, 2);
867 }
868
869 static velocity_t velocity(int speed)
870 {
871         velocity_t v;
872
873         if (speed < -304) /* ascent faster than -60ft/min */
874                 v = CRAZY;
875         else if (speed < -152) /* above -30ft/min */
876                 v = FAST;
877         else if (speed < -76) /* -15ft/min */
878                 v = MODERATE;
879         else if (speed < -25) /* -5ft/min */
880                 v = SLOW;
881         else if (speed < 25) /* very hard to find data, but it appears that the recommendations
882                                 for descent are usually about 2x ascent rate; still, we want 
883                                 stable to mean stable */
884                 v = STABLE;
885         else if (speed < 152) /* between 5 and 30ft/min is considered slow */
886                 v = SLOW;
887         else if (speed < 304) /* up to 60ft/min is moderate */
888                 v = MODERATE;
889         else if (speed < 507) /* up to 100ft/min is fast */
890                 v = FAST;
891         else /* more than that is just crazy - you'll blow your ears out */
892                 v = CRAZY;
893
894         return v;
895 }
896 static struct plot_info *analyze_plot_info(struct plot_info *pi)
897 {
898         int i;
899         int nr = pi->nr;
900
901         /* Do pressure min/max based on the non-surface data */
902         for (i = 0; i < nr; i++) {
903                 struct plot_data *entry = pi->entry+i;
904                 int pressure = GET_PRESSURE(entry);
905                 int temperature = entry->temperature;
906
907                 if (pressure) {
908                         if (pressure > pi->maxpressure)
909                                 pi->maxpressure = pressure;
910                 }
911
912                 if (temperature) {
913                         if (!pi->mintemp || temperature < pi->mintemp)
914                                 pi->mintemp = temperature;
915                         if (temperature > pi->maxtemp)
916                                 pi->maxtemp = temperature;
917                 }
918         }
919
920         /* Smoothing function: 5-point triangular smooth */
921         for (i = 2; i < nr; i++) {
922                 struct plot_data *entry = pi->entry+i;
923                 int depth;
924
925                 if (i < nr-2) {
926                         depth = entry[-2].depth + 2*entry[-1].depth + 3*entry[0].depth + 2*entry[1].depth + entry[2].depth;
927                         entry->smoothed = (depth+4) / 9;
928                 }
929                 /* vertical velocity in mm/sec */
930                 /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */
931                 if (entry[0].sec - entry[-1].sec) {
932                         entry->velocity = velocity((entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec));
933                         /* if our samples are short and we aren't too FAST*/
934                         if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) {
935                                 int past = -2;
936                                 while (i+past > 0 && entry[0].sec - entry[past].sec < 15)
937                                         past--;
938                                 entry->velocity = velocity((entry[0].depth - entry[past].depth) / 
939                                                         (entry[0].sec - entry[past].sec));
940                         }
941                 } else
942                         entry->velocity = STABLE;
943         }
944
945         /* One-, two- and three-minute minmax data */
946         for (i = 0; i < nr; i++) {
947                 struct plot_data *entry = pi->entry +i;
948                 analyze_plot_info_minmax(entry, pi->entry, pi->entry+nr);
949         }
950         
951         return pi;
952 }
953
954 /*
955  * simple structure to track the beginning and end tank pressure as
956  * well as the integral of depth over time spent while we have no
957  * pressure reading from the tank */
958 typedef struct pr_track_struct pr_track_t;
959 struct pr_track_struct {
960         int start;
961         int end;
962         int t_start;
963         int t_end;
964         double pressure_time;
965         pr_track_t *next;
966 };
967
968 static pr_track_t *pr_track_alloc(int start, int t_start) {
969         pr_track_t *pt = malloc(sizeof(pr_track_t));
970         pt->start = start;
971         pt->t_start = t_start;
972         pt->end = 0;
973         pt->t_end = 0;
974         pt->pressure_time = 0.0;
975         pt->next = NULL;
976         return pt;
977 }
978
979 /* poor man's linked list */
980 static pr_track_t *list_last(pr_track_t *list)
981 {
982         pr_track_t *tail = list;
983         if (!tail)
984                 return NULL;
985         while (tail->next) {
986                 tail = tail->next;
987         }
988         return tail;
989 }
990
991 static pr_track_t *list_add(pr_track_t *list, pr_track_t *element)
992 {
993         pr_track_t *tail = list_last(list);
994         if (!tail)
995                 return element;
996         tail->next = element;
997         return list;
998 }
999
1000 static void list_free(pr_track_t *list)
1001 {
1002         if (!list)
1003                 return;
1004         list_free(list->next);
1005         free(list);
1006 }
1007
1008 static void dump_pr_track(pr_track_t **track_pr)
1009 {
1010         int cyl;
1011         pr_track_t *list;
1012
1013         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1014                 list = track_pr[cyl];
1015                 while (list) {
1016                         printf("cyl%d: start %d end %d t_start %d t_end %d pt %6.3f\n", cyl,
1017                                 list->start, list->end, list->t_start, list->t_end, list->pressure_time);
1018                         list = list->next;
1019                 }
1020         }
1021 }
1022
1023 static void fill_missing_tank_pressures(struct dive *dive, struct plot_info *pi,
1024                                         pr_track_t **track_pr)
1025 {
1026         pr_track_t *list = NULL;
1027         pr_track_t *nlist = NULL;
1028         double pt, magic;
1029         int cyl, i;
1030         struct plot_data *entry;
1031         int cur_pr[MAX_CYLINDERS];
1032
1033         if (0) {
1034                 /* another great debugging tool */
1035                 dump_pr_track(track_pr);
1036         }
1037         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1038                 cur_pr[cyl] = track_pr[cyl]->start;
1039         }
1040
1041         /* The first two are "fillers", but in case we don't have a sample
1042          * at time 0 we need to process the second of them here */
1043         for (i = 1; i < pi->nr; i++) {
1044                 entry = pi->entry + i;
1045                 if (SENSOR_PRESSURE(entry)) {
1046                         cur_pr[entry->cylinderindex] = SENSOR_PRESSURE(entry);
1047                 } else {
1048                         if(!list || list->t_end < entry->sec) {
1049                                 nlist = track_pr[entry->cylinderindex];
1050                                 list = NULL;
1051                                 while (nlist && nlist->t_start <= entry->sec) {
1052                                         list = nlist;
1053                                         nlist = list->next;
1054                                 }
1055                                 /* there may be multiple segments - so
1056                                  * let's assemble the length */
1057                                 nlist = list;
1058                                 pt = list->pressure_time;
1059                                 while (!nlist->end) {
1060                                         nlist = nlist->next;
1061                                         if (!nlist) {
1062                                                 /* oops - we have no end pressure,
1063                                                  * so this means this is a tank without
1064                                                  * gas consumption information */
1065                                                 break;
1066                                         }
1067                                         pt += nlist->pressure_time;
1068                                 }
1069                                 if (!nlist) {
1070                                         /* just continue without calculating
1071                                          * interpolated values */
1072                                         INTERPOLATED_PRESSURE(entry) = cur_pr[entry->cylinderindex];
1073                                         list = NULL;
1074                                         continue;
1075                                 }
1076                                 magic = (nlist->end - cur_pr[entry->cylinderindex]) / pt;
1077                         }
1078                         if (pt != 0.0) {
1079                                 double cur_pt = (entry->sec - (entry-1)->sec) *
1080                                         (1 + (entry->depth + (entry-1)->depth) / 20000.0);
1081                                 INTERPOLATED_PRESSURE(entry) =
1082                                         cur_pr[entry->cylinderindex] + cur_pt * magic + 0.5;
1083                                 cur_pr[entry->cylinderindex] = INTERPOLATED_PRESSURE(entry);
1084                         } else
1085                                 INTERPOLATED_PRESSURE(entry) = cur_pr[entry->cylinderindex];
1086                 }
1087         }
1088 }
1089
1090 static int get_cylinder_index(struct dive *dive, struct event *ev)
1091 {
1092         int i;
1093
1094         /*
1095          * Try to find a cylinder that matches the O2 percentage
1096          * in the gas change event 'value' field.
1097          *
1098          * Crazy suunto gas change events. We really should do
1099          * this in libdivecomputer or something.
1100          */
1101         for (i = 0; i < MAX_CYLINDERS; i++) {
1102                 cylinder_t *cyl = dive->cylinder+i;
1103                 int o2 = (cyl->gasmix.o2.permille + 5) / 10;
1104                 if (o2 == ev->value)
1105                         return i;
1106         }
1107
1108         return 0;
1109 }
1110
1111 static struct event *get_next_gaschange(struct event *event)
1112 {
1113         while (event) {
1114                 if (!strcmp(event->name, "gaschange"))
1115                         return event;
1116                 event = event->next;
1117         }
1118         return event;
1119 }
1120
1121 static int set_cylinder_index(struct plot_info *pi, int i, int cylinderindex, unsigned int end)
1122 {
1123         while (i < pi->nr) {
1124                 struct plot_data *entry = pi->entry+i;
1125                 if (entry->sec > end)
1126                         break;
1127                 if (entry->cylinderindex != cylinderindex) {
1128                         entry->cylinderindex = cylinderindex;
1129                         entry->pressure[0] = 0;
1130                 }
1131                 i++;
1132         }
1133         return i;
1134 }
1135
1136 static void check_gas_change_events(struct dive *dive, struct plot_info *pi)
1137 {
1138         int i = 0, cylinderindex = 0;
1139         struct event *ev = get_next_gaschange(dive->events);
1140
1141         if (!ev)
1142                 return;
1143
1144         do {
1145                 i = set_cylinder_index(pi, i, cylinderindex, ev->time.seconds);
1146                 cylinderindex = get_cylinder_index(dive, ev);
1147                 ev = get_next_gaschange(ev->next);
1148         } while (ev);
1149         set_cylinder_index(pi, i, cylinderindex, ~0u);
1150 }
1151
1152 /* for computers that track gas changes through events */
1153 static int count_gas_change_events(struct dive *dive)
1154 {
1155         int count = 0;
1156         struct event *ev = get_next_gaschange(dive->events);
1157
1158         while (ev) {
1159                 count++;
1160                 ev = get_next_gaschange(ev->next);
1161         }
1162         return count;
1163 }
1164
1165 /*
1166  * Create a plot-info with smoothing and ranged min/max
1167  *
1168  * This also makes sure that we have extra empty events on both
1169  * sides, so that you can do end-points without having to worry
1170  * about it.
1171  */
1172 static struct plot_info *create_plot_info(struct dive *dive, int nr_samples, struct sample *dive_sample)
1173 {
1174         int cylinderindex = -1;
1175         int lastdepth, lastindex;
1176         int i, pi_idx, nr, sec, cyl;
1177         size_t alloc_size;
1178         struct plot_info *pi;
1179         pr_track_t *track_pr[MAX_CYLINDERS] = {NULL, };
1180         pr_track_t *pr_track, *current;
1181         gboolean missing_pr = FALSE;
1182         struct plot_data *entry = NULL;
1183         struct event *ev;
1184
1185         /* we want to potentially add synthetic plot_info elements for the gas changes */
1186         nr = nr_samples + 4 + 2 * count_gas_change_events(dive);
1187         alloc_size = plot_info_size(nr);
1188         pi = malloc(alloc_size);
1189         if (!pi)
1190                 return pi;
1191         memset(pi, 0, alloc_size);
1192         pi->nr = nr;
1193         pi_idx = 2; /* the two extra events at the start */
1194         /* check for gas changes before the samples start */
1195         ev = get_next_gaschange(dive->events);
1196         while (ev && ev->time.seconds < dive_sample->time.seconds) {
1197                 entry = pi->entry + pi_idx;
1198                 entry->sec = ev->time.seconds;
1199                 entry->depth = 0; /* is that always correct ? */
1200                 pi_idx++;
1201                 ev = get_next_gaschange(ev->next);
1202         }
1203         if (ev && ev->time.seconds == dive_sample->time.seconds) {
1204                 /* we already have a sample at the time of the event */
1205                 ev = get_next_gaschange(ev->next);
1206         }
1207         sec = 0;
1208         lastindex = 0;
1209         lastdepth = -1;
1210         for (i = 0; i < nr_samples; i++) {
1211                 int depth;
1212                 int delay = 0;
1213                 struct sample *sample = dive_sample+i;
1214
1215                 entry = pi->entry + i + pi_idx;
1216                 while (ev && ev->time.seconds < sample->time.seconds) {
1217                         /* insert two fake plot info structures for the end of
1218                          * the old tank and the start of the new tank */
1219                         if (ev->time.seconds == sample->time.seconds - 1) {
1220                                 entry->sec = ev->time.seconds - 1;
1221                                 (entry+1)->sec = ev->time.seconds;
1222                         } else {
1223                                 entry->sec = ev->time.seconds;
1224                                 (entry+1)->sec = ev->time.seconds + 1;
1225                         }
1226                         /* we need a fake depth - let's interpolate */
1227                         if (i) {
1228                                 entry->depth = sample->depth.mm -
1229                                         (sample->depth.mm - (sample-1)->depth.mm) / 2;
1230                         } else
1231                                 entry->depth = sample->depth.mm;
1232                         (entry+1)->depth = entry->depth;
1233                         pi_idx += 2;
1234                         entry = pi->entry + i + pi_idx;
1235                         ev = get_next_gaschange(ev->next);
1236                 }
1237                 if (ev && ev->time.seconds == sample->time.seconds) {
1238                         /* we already have a sample at the time of the event
1239                          * just add a new one for the old tank and delay the
1240                          * real even by one second (to keep time monotonous) */
1241                         entry->sec = ev->time.seconds;
1242                         entry->depth = sample->depth.mm;
1243                         pi_idx++;
1244                         entry = pi->entry + i + pi_idx;
1245                         ev = get_next_gaschange(ev->next);
1246                         delay = 1;
1247                 }
1248                 sec = entry->sec = sample->time.seconds + delay;
1249                 depth = entry->depth = sample->depth.mm;
1250                 entry->cylinderindex = sample->cylinderindex;
1251                 SENSOR_PRESSURE(entry) = sample->cylinderpressure.mbar;
1252                 entry->temperature = sample->temperature.mkelvin;
1253
1254                 if (depth || lastdepth)
1255                         lastindex = i + pi_idx;
1256
1257                 lastdepth = depth;
1258                 if (depth > pi->maxdepth)
1259                         pi->maxdepth = depth;
1260         }
1261         entry = pi->entry + i + pi_idx;
1262         /* are there still unprocessed gas changes? that would be very strange */
1263         while (ev) {
1264                 entry->sec = ev->time.seconds;
1265                 entry->depth = 0; /* why are there gas changes after the dive is over? */
1266                 pi_idx++;
1267                 entry = pi->entry + i + pi_idx;
1268                 ev = get_next_gaschange(ev->next);
1269         }
1270         nr = nr_samples + pi_idx - 2;
1271         check_gas_change_events(dive, pi);
1272
1273         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) /* initialize the start pressures */
1274                 track_pr[cyl] = pr_track_alloc(dive->cylinder[cyl].start.mbar, -1);
1275         current = track_pr[pi->entry[2].cylinderindex];
1276         for (i = 0; i < nr + 1; i++) {
1277                 entry = pi->entry + i + 1;
1278
1279                 entry->same_cylinder = entry->cylinderindex == cylinderindex;
1280                 cylinderindex = entry->cylinderindex;
1281
1282                 /* track the segments per cylinder and their pressure/time integral */
1283                 if (!entry->same_cylinder) {
1284                         current->end = SENSOR_PRESSURE(entry-1);
1285                         current->t_end = (entry-1)->sec;
1286                         current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1287                         track_pr[cylinderindex] = list_add(track_pr[cylinderindex], current);
1288                 } else { /* same cylinder */
1289                         if ((!SENSOR_PRESSURE(entry) && SENSOR_PRESSURE(entry-1)) ||
1290                                 (SENSOR_PRESSURE(entry) && !SENSOR_PRESSURE(entry-1))) {
1291                                 /* transmitter changed its working status */
1292                                 current->end = SENSOR_PRESSURE(entry-1);
1293                                 current->t_end = (entry-1)->sec;
1294                                 current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1295                                 track_pr[cylinderindex] =
1296                                         list_add(track_pr[cylinderindex], current);
1297                         }
1298                 }
1299                 /* finally, do the discrete integration to get the SAC rate equivalent */
1300                 current->pressure_time += (entry->sec - (entry-1)->sec) *
1301                         (1 + (entry->depth + (entry-1)->depth) / 20000.0);
1302                 missing_pr |= !SENSOR_PRESSURE(entry);
1303         }
1304
1305         if (entry)
1306                 current->t_end = entry->sec;
1307
1308         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) { /* initialize the end pressures */
1309                 int pr = dive->cylinder[cyl].end.mbar;
1310                 if (pr && track_pr[cyl]) {
1311                         pr_track = list_last(track_pr[cyl]);
1312                         pr_track->end = pr;
1313                 }
1314         }
1315         /* Fill in the last two entries with empty values but valid times
1316          * without creating a false cylinder change event */
1317         i = nr + 2;
1318         pi->entry[i].sec = sec + 20;
1319         pi->entry[i].same_cylinder = 1;
1320         pi->entry[i].cylinderindex = pi->entry[i-1].cylinderindex;
1321         INTERPOLATED_PRESSURE(pi->entry + i) = GET_PRESSURE(pi->entry + i - 1);
1322         pi->entry[i+1].sec = sec + 40;
1323         pi->entry[i+1].same_cylinder = 1;
1324         pi->entry[i+1].cylinderindex = pi->entry[i-1].cylinderindex;
1325         INTERPOLATED_PRESSURE(pi->entry + i + 1) = GET_PRESSURE(pi->entry + i - 1);
1326         /* the number of actual entries - some computers have lots of
1327          * depth 0 samples at the end of a dive, we want to make sure
1328          * we have exactly one of them at the end */
1329         pi->nr = lastindex+1;
1330         while (pi->nr <= i+2 && pi->entry[pi->nr-1].depth > 0)
1331                 pi->nr++;
1332         pi->maxtime = pi->entry[lastindex].sec;
1333
1334         /* Analyze_plot_info() will do the sample max pressures,
1335          * this handles the manual pressures
1336          */
1337         pi->maxpressure = 0;
1338         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1339                 unsigned int mbar = dive->cylinder[cyl].start.mbar;
1340                 if (mbar > pi->maxpressure)
1341                         pi->maxpressure = mbar;
1342         }
1343
1344         pi->meandepth = dive->meandepth.mm;
1345
1346         if (missing_pr) {
1347                 fill_missing_tank_pressures(dive, pi, track_pr);
1348         }
1349         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++)
1350                 list_free(track_pr[cyl]);
1351         if (0) /* awesome for debugging - not useful otherwise */
1352                 dump_pi(pi);
1353         return analyze_plot_info(pi);
1354 }
1355
1356 void plot(struct graphics_context *gc, cairo_rectangle_int_t *drawing_area, struct dive *dive)
1357 {
1358         struct plot_info *pi;
1359         static struct sample fake[4];
1360         struct sample *sample = dive->sample;
1361         int nr = dive->samples;
1362
1363         if (!nr) {
1364                 int duration = dive->duration.seconds;
1365                 int maxdepth = dive->maxdepth.mm;
1366                 sample = fake;
1367                 fake[1].time.seconds = duration * 0.05;
1368                 fake[1].depth.mm = maxdepth;
1369                 fake[2].time.seconds = duration * 0.95;
1370                 fake[2].depth.mm = maxdepth;
1371                 fake[3].time.seconds = duration * 1.00;
1372                 nr = 4;
1373         }
1374
1375         pi = create_plot_info(dive, nr, sample);
1376
1377         cairo_translate(gc->cr, drawing_area->x, drawing_area->y);
1378         cairo_set_line_width(gc->cr, 1);
1379         cairo_set_line_cap(gc->cr, CAIRO_LINE_CAP_ROUND);
1380         cairo_set_line_join(gc->cr, CAIRO_LINE_JOIN_ROUND);
1381
1382         /*
1383          * We can use "cairo_translate()" because that doesn't
1384          * scale line width etc. But the actual scaling we need
1385          * do set up ourselves..
1386          *
1387          * Snif. What a pity.
1388          */
1389         gc->maxx = (drawing_area->width - 2*drawing_area->x);
1390         gc->maxy = (drawing_area->height - 2*drawing_area->y);
1391
1392         /* Temperature profile */
1393         plot_temperature_profile(gc, pi);
1394
1395         /* Depth profile */
1396         plot_depth_profile(gc, pi);
1397         plot_events(gc, pi, dive);
1398
1399         /* Cylinder pressure plot */
1400         plot_cylinder_pressure(gc, pi, dive);
1401
1402         /* Text on top of all graphs.. */
1403         plot_temperature_text(gc, pi);
1404         plot_depth_text(gc, pi);
1405         plot_cylinder_pressure_text(gc, pi);
1406
1407         /* Bounding box last */
1408         gc->leftx = 0; gc->rightx = 1.0;
1409         gc->topy = 0; gc->bottomy = 1.0;
1410
1411         set_source_rgba(gc, BOUNDING_BOX);
1412         cairo_set_line_width(gc->cr, 1);
1413         move_to(gc, 0, 0);
1414         line_to(gc, 0, 1);
1415         line_to(gc, 1, 1);
1416         line_to(gc, 1, 0);
1417         cairo_close_path(gc->cr);
1418         cairo_stroke(gc->cr);
1419
1420         free(pi);
1421 }