source: git/src/gfxcore.cc @ cd48e7c

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since cd48e7c was cd48e7c, checked in by Olly Betts <olly@…>, 9 years ago

src/gfxcore.cc: Make terrain white with 30% alpha rather than light
grey and opaque.

  • Property mode set to 100644
File size: 98.5 KB
Line 
1//
2//  gfxcore.cc
3//
4//  Core drawing code for Aven.
5//
6//  Copyright (C) 2000-2003,2005,2006 Mark R. Shinwell
7//  Copyright (C) 2001-2003,2004,2005,2006,2007,2010,2011,2012,2014,2015 Olly Betts
8//  Copyright (C) 2005 Martin Green
9//
10//  This program is free software; you can redistribute it and/or modify
11//  it under the terms of the GNU General Public License as published by
12//  the Free Software Foundation; either version 2 of the License, or
13//  (at your option) any later version.
14//
15//  This program is distributed in the hope that it will be useful,
16//  but WITHOUT ANY WARRANTY; without even the implied warranty of
17//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18//  GNU General Public License for more details.
19//
20//  You should have received a copy of the GNU General Public License
21//  along with this program; if not, write to the Free Software
22//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23//
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include <assert.h>
30#include <float.h>
31
32#include "aven.h"
33#include "date.h"
34#include "gfxcore.h"
35#include "mainfrm.h"
36#include "message.h"
37#include "useful.h"
38#include "printwx.h"
39#include "guicontrol.h"
40#include "moviemaker.h"
41
42#include <wx/confbase.h>
43#include <wx/image.h>
44
45#include <proj_api.h>
46#include <sys/mman.h>
47
48#define MAX(a, b) ((a) > (b) ? (a) : (b))
49#define MAX3(a, b, c) ((a) > (b) ? MAX(a, c) : MAX(b, c))
50
51// Values for m_SwitchingTo
52#define PLAN 1
53#define ELEVATION 2
54#define NORTH 3
55#define EAST 4
56#define SOUTH 5
57#define WEST 6
58
59// Any error value higher than this is clamped to this.
60#define MAX_ERROR 12.0
61
62// Any length greater than pow(10, LOG_LEN_MAX) will be clamped to this.
63const Double LOG_LEN_MAX = 1.5;
64
65// How many bins per letter height to use when working out non-overlapping
66// labels.
67const unsigned int QUANTISE_FACTOR = 2;
68
69#include "avenpal.h"
70
71static const int INDICATOR_BOX_SIZE = 60;
72static const int INDICATOR_GAP = 2;
73static const int INDICATOR_MARGIN = 5;
74static const int INDICATOR_OFFSET_X = 15;
75static const int INDICATOR_OFFSET_Y = 15;
76static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
77static const int KEY_OFFSET_X = 10;
78static const int KEY_OFFSET_Y = 10;
79static const int KEY_EXTRA_LEFT_MARGIN = 2;
80static const int KEY_BLOCK_WIDTH = 20;
81static const int KEY_BLOCK_HEIGHT = 16;
82static const int TICK_LENGTH = 4;
83static const int SCALE_BAR_OFFSET_X = 15;
84static const int SCALE_BAR_OFFSET_Y = 12;
85static const int SCALE_BAR_HEIGHT = 12;
86
87static const gla_colour TEXT_COLOUR = col_GREEN;
88static const gla_colour HERE_COLOUR = col_WHITE;
89static const gla_colour NAME_COLOUR = col_GREEN;
90static const gla_colour SEL_COLOUR = col_WHITE;
91
92// Number of entries across and down the hit-test grid:
93#define HITTEST_SIZE 20
94
95// How close the pointer needs to be to a station to be considered:
96#define MEASURE_THRESHOLD 7
97
98// vector for lighting angle
99static const Vector3 light(.577, .577, .577);
100
101BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
102    EVT_PAINT(GfxCore::OnPaint)
103    EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
104    EVT_LEFT_UP(GfxCore::OnLButtonUp)
105    EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
106    EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
107    EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
108    EVT_RIGHT_UP(GfxCore::OnRButtonUp)
109    EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
110    EVT_MOTION(GfxCore::OnMouseMove)
111    EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
112    EVT_SIZE(GfxCore::OnSize)
113    EVT_IDLE(GfxCore::OnIdle)
114    EVT_CHAR(GfxCore::OnKeyPress)
115END_EVENT_TABLE()
116
117GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
118    GLACanvas(parent_win, 100),
119    m_Scale(0.0),
120    m_ScaleBarWidth(0),
121    m_Control(control),
122    m_LabelGrid(NULL),
123    m_Parent(parent),
124    m_DoneFirstShow(false),
125    m_TiltAngle(0.0),
126    m_PanAngle(0.0),
127    m_Rotating(false),
128    m_RotationStep(0.0),
129    m_SwitchingTo(0),
130    m_Crosses(false),
131    m_Legs(true),
132    m_Splays(SPLAYS_SHOW_FADED),
133    m_Names(false),
134    m_Scalebar(true),
135    m_ColourKey(true),
136    m_OverlappingNames(false),
137    m_Compass(true),
138    m_Clino(true),
139    m_Tubes(false),
140    m_ColourBy(COLOUR_BY_DEPTH),
141    m_HaveData(false),
142    m_HaveTerrain(true),
143    m_MouseOutsideCompass(false),
144    m_MouseOutsideElev(false),
145    m_Surface(false),
146    m_Entrances(false),
147    m_FixedPts(false),
148    m_ExportedPts(false),
149    m_Grid(false),
150    m_BoundingBox(false),
151    m_Terrain(false),
152    m_Degrees(false),
153    m_Metric(false),
154    m_Percent(false),
155    m_HitTestDebug(false),
156    m_PointGrid(NULL),
157    m_HitTestGridValid(false),
158    m_here(NULL),
159    m_there(NULL),
160    presentation_mode(0),
161    pres_reverse(false),
162    pres_speed(0.0),
163    movie(NULL),
164    current_cursor(GfxCore::CURSOR_DEFAULT),
165    sqrd_measure_threshold(sqrd(MEASURE_THRESHOLD))
166{
167    AddQuad = &GfxCore::AddQuadrilateralDepth;
168    AddPoly = &GfxCore::AddPolylineDepth;
169    wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
170    wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
171    wxConfigBase::Get()->Read(wxT("percent"), &m_Percent, false);
172
173    for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
174        m_Pens[pen].SetColour(REDS[pen] / 255.0,
175                              GREENS[pen] / 255.0,
176                              BLUES[pen] / 255.0);
177    }
178
179    timer.Start();
180}
181
182GfxCore::~GfxCore()
183{
184    TryToFreeArrays();
185
186    delete[] m_PointGrid;
187}
188
189void GfxCore::TryToFreeArrays()
190{
191    // Free up any memory allocated for arrays.
192    delete[] m_LabelGrid;
193    m_LabelGrid = NULL;
194}
195
196//
197//  Initialisation methods
198//
199
200void GfxCore::Initialise(bool same_file)
201{
202    // Initialise the view from the parent holding the survey data.
203
204    TryToFreeArrays();
205
206    m_DoneFirstShow = false;
207
208    m_HitTestGridValid = false;
209    m_here = NULL;
210    m_there = NULL;
211
212    m_MouseOutsideCompass = m_MouseOutsideElev = false;
213
214    if (!same_file) {
215        // Apply default parameters unless reloading the same file.
216        DefaultParameters();
217
218        // Set the initial scale.
219        SetScale(1.0);
220    }
221
222    m_HaveData = true;
223
224    // Clear any cached OpenGL lists which depend on the data.
225    InvalidateList(LIST_SCALE_BAR);
226    InvalidateList(LIST_DEPTH_KEY);
227    InvalidateList(LIST_DATE_KEY);
228    InvalidateList(LIST_ERROR_KEY);
229    InvalidateList(LIST_GRADIENT_KEY);
230    InvalidateList(LIST_LENGTH_KEY);
231    InvalidateList(LIST_UNDERGROUND_LEGS);
232    InvalidateList(LIST_TUBES);
233    InvalidateList(LIST_SURFACE_LEGS);
234    InvalidateList(LIST_BLOBS);
235    InvalidateList(LIST_CROSSES);
236    InvalidateList(LIST_GRID);
237    InvalidateList(LIST_SHADOW);
238    InvalidateList(LIST_TERRAIN);
239
240    ForceRefresh();
241}
242
243void GfxCore::FirstShow()
244{
245    GLACanvas::FirstShow();
246
247    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
248    list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
249    while (pos != m_Parent->GetLabelsNCEnd()) {
250        LabelInfo* label = *pos++;
251        // Calculate and set the label width for use when plotting
252        // none-overlapping labels.
253        int ext_x;
254        GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
255        label->set_width(unsigned(ext_x) / quantise + 1);
256    }
257
258    // Set diameter of the viewing volume.
259    SetVolumeDiameter(sqrt(sqrd(m_Parent->GetXExtent()) +
260                           sqrd(m_Parent->GetYExtent()) +
261                           sqrd(m_Parent->GetZExtent())));
262
263    m_DoneFirstShow = true;
264}
265
266//
267//  Recalculating methods
268//
269
270void GfxCore::SetScale(Double scale)
271{
272    if (scale < 0.05) {
273        scale = 0.05;
274    } else if (scale > GetVolumeDiameter()) {
275        scale = GetVolumeDiameter();
276    }
277
278    m_Scale = scale;
279    m_HitTestGridValid = false;
280    if (m_here && m_here == &temp_here) SetHere();
281
282    GLACanvas::SetScale(scale);
283}
284
285bool GfxCore::HasUndergroundLegs() const
286{
287    return m_Parent->HasUndergroundLegs();
288}
289
290bool GfxCore::HasSplays() const
291{
292    return m_Parent->HasSplays();
293}
294
295bool GfxCore::HasSurfaceLegs() const
296{
297    return m_Parent->HasSurfaceLegs();
298}
299
300bool GfxCore::HasTubes() const
301{
302    return m_Parent->HasTubes();
303}
304
305void GfxCore::UpdateBlobs()
306{
307    InvalidateList(LIST_BLOBS);
308}
309
310//
311//  Event handlers
312//
313
314void GfxCore::OnLeaveWindow(wxMouseEvent&) {
315    SetHere();
316    ClearCoords();
317}
318
319void GfxCore::OnIdle(wxIdleEvent& event)
320{
321    // Handle an idle event.
322    if (Animating()) {
323        Animate();
324        // If still animating, we want more idle events.
325        if (Animating())
326            event.RequestMore();
327    }
328}
329
330void GfxCore::OnPaint(wxPaintEvent&)
331{
332    // Redraw the window.
333
334    // Get a graphics context.
335    wxPaintDC dc(this);
336
337    if (m_HaveData) {
338        // Make sure we're initialised.
339        bool first_time = !m_DoneFirstShow;
340        if (first_time) {
341            FirstShow();
342        }
343
344        StartDrawing();
345
346        // Clear the background.
347        Clear();
348
349        // Set up model transformation matrix.
350        SetDataTransform();
351
352        if (m_Legs || m_Tubes) {
353            if (m_Tubes) {
354                EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
355                DrawList(LIST_TUBES);
356                DisableSmoothPolygons();
357            }
358
359            // Draw the underground legs.  Do this last so that anti-aliasing
360            // works over polygons.
361            SetColour(col_GREEN);
362            DrawList(LIST_UNDERGROUND_LEGS);
363        }
364
365        if (m_Surface) {
366            // Draw the surface legs.
367            DrawList(LIST_SURFACE_LEGS);
368        }
369
370        if (m_BoundingBox) {
371            DrawShadowedBoundingBox();
372        }
373        if (m_Grid) {
374            // Draw the grid.
375            DrawList(LIST_GRID);
376        }
377
378        DrawList(LIST_BLOBS);
379
380        if (m_Crosses) {
381            DrawList(LIST_CROSSES);
382        }
383
384        if (m_Terrain) {
385            DrawList(LIST_TERRAIN);
386        }
387
388        SetIndicatorTransform();
389
390        // Draw station names.
391        if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
392            SetColour(NAME_COLOUR);
393
394            if (m_OverlappingNames) {
395                SimpleDrawNames();
396            } else {
397                NattyDrawNames();
398            }
399        }
400
401        if (m_HitTestDebug) {
402            // Show the hit test grid bucket sizes...
403            SetColour(m_HitTestGridValid ? col_LIGHT_GREY : col_DARK_GREY);
404            if (m_PointGrid) {
405                for (int i = 0; i != HITTEST_SIZE; ++i) {
406                    int x = (GetXSize() + 1) * i / HITTEST_SIZE + 2;
407                    for (int j = 0; j != HITTEST_SIZE; ++j) {
408                        int square = i + j * HITTEST_SIZE;
409                        unsigned long bucket_size = m_PointGrid[square].size();
410                        if (bucket_size) {
411                            int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
412                            DrawIndicatorText(x, y, wxString::Format(wxT("%lu"), bucket_size));
413                        }
414                    }
415                }
416            }
417
418            EnableDashedLines();
419            BeginLines();
420            for (int i = 0; i != HITTEST_SIZE; ++i) {
421                int x = (GetXSize() + 1) * i / HITTEST_SIZE;
422                PlaceIndicatorVertex(x, 0);
423                PlaceIndicatorVertex(x, GetYSize());
424            }
425            for (int j = 0; j != HITTEST_SIZE; ++j) {
426                int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
427                PlaceIndicatorVertex(0, y);
428                PlaceIndicatorVertex(GetXSize(), y);
429            }
430            EndLines();
431            DisableDashedLines();
432        }
433
434        // Draw indicators.
435        //
436        // There's no advantage in generating an OpenGL list for the
437        // indicators since they change with almost every redraw (and
438        // sometimes several times between redraws).  This way we avoid
439        // the need to track when to update the indicator OpenGL list,
440        // and also avoid indicator update bugs when we don't quite get this
441        // right...
442        DrawIndicators();
443
444        if (zoombox.active()) {
445            SetColour(SEL_COLOUR);
446            EnableDashedLines();
447            BeginPolyline();
448            glaCoord Y = GetYSize();
449            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
450            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y2);
451            PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y2);
452            PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y1);
453            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
454            EndPolyline();
455            DisableDashedLines();
456        } else if (MeasuringLineActive()) {
457            // Draw "here" and "there".
458            double hx, hy;
459            SetColour(HERE_COLOUR);
460            if (m_here) {
461                double dummy;
462                Transform(*m_here, &hx, &hy, &dummy);
463                if (m_here != &temp_here) DrawRing(hx, hy);
464            }
465            if (m_there) {
466                double tx, ty;
467                double dummy;
468                Transform(*m_there, &tx, &ty, &dummy);
469                if (m_here) {
470                    BeginLines();
471                    PlaceIndicatorVertex(hx, hy);
472                    PlaceIndicatorVertex(tx, ty);
473                    EndLines();
474                }
475                BeginBlobs();
476                DrawBlob(tx, ty);
477                EndBlobs();
478            }
479        }
480
481        FinishDrawing();
482    } else {
483        dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
484        dc.Clear();
485    }
486}
487
488void GfxCore::DrawBoundingBox()
489{
490    const Vector3 v = 0.5 * m_Parent->GetExtent();
491
492    SetColour(col_BLUE);
493    EnableDashedLines();
494    BeginPolyline();
495    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
496    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
497    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
498    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
499    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
500    EndPolyline();
501    BeginPolyline();
502    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
503    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
504    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
505    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
506    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
507    EndPolyline();
508    BeginLines();
509    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
510    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
511    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
512    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
513    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
514    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
515    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
516    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
517    EndLines();
518    DisableDashedLines();
519}
520
521void GfxCore::DrawShadowedBoundingBox()
522{
523    const Vector3 v = 0.5 * m_Parent->GetExtent();
524
525    DrawBoundingBox();
526
527    PolygonOffset(true);
528    SetColour(col_DARK_GREY);
529    BeginQuadrilaterals();
530    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
531    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
532    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
533    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
534    EndQuadrilaterals();
535    PolygonOffset(false);
536
537    DrawList(LIST_SHADOW);
538}
539
540void GfxCore::DrawGrid()
541{
542    // Draw the grid.
543    SetColour(col_RED);
544
545    // Calculate the extent of the survey, in metres across the screen plane.
546    Double m_across_screen = SurveyUnitsAcrossViewport();
547    // Calculate the length of the scale bar in metres.
548    //--move this elsewhere
549    Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
550    Double t = m_across_screen * 0.75 / size_snap;
551    if (t >= 5.0) {
552        size_snap *= 5.0;
553    }
554    else if (t >= 2.0) {
555        size_snap *= 2.0;
556    }
557
558    Double grid_size = size_snap * 0.1;
559    Double edge = grid_size * 2.0;
560    Double grid_z = -m_Parent->GetZExtent() * 0.5 - grid_size;
561    Double left = -m_Parent->GetXExtent() * 0.5 - edge;
562    Double right = m_Parent->GetXExtent() * 0.5 + edge;
563    Double bottom = -m_Parent->GetYExtent() * 0.5 - edge;
564    Double top = m_Parent->GetYExtent() * 0.5 + edge;
565    int count_x = (int) ceil((right - left) / grid_size);
566    int count_y = (int) ceil((top - bottom) / grid_size);
567    Double actual_right = left + count_x*grid_size;
568    Double actual_top = bottom + count_y*grid_size;
569
570    BeginLines();
571
572    for (int xc = 0; xc <= count_x; xc++) {
573        Double x = left + xc*grid_size;
574
575        PlaceVertex(x, bottom, grid_z);
576        PlaceVertex(x, actual_top, grid_z);
577    }
578
579    for (int yc = 0; yc <= count_y; yc++) {
580        Double y = bottom + yc*grid_size;
581        PlaceVertex(left, y, grid_z);
582        PlaceVertex(actual_right, y, grid_z);
583    }
584
585    EndLines();
586}
587
588int GfxCore::GetClinoOffset() const
589{
590    int result = INDICATOR_OFFSET_X;
591    if (m_Compass) {
592        result += 6 + GetCompassWidth() + INDICATOR_GAP;
593    }
594    return result;
595}
596
597void GfxCore::DrawTick(int angle_cw)
598{
599    const Double theta = rad(angle_cw);
600    const wxCoord length1 = INDICATOR_RADIUS;
601    const wxCoord length0 = length1 + TICK_LENGTH;
602    wxCoord x0 = wxCoord(length0 * sin(theta));
603    wxCoord y0 = wxCoord(length0 * cos(theta));
604    wxCoord x1 = wxCoord(length1 * sin(theta));
605    wxCoord y1 = wxCoord(length1 * cos(theta));
606
607    PlaceIndicatorVertex(x0, y0);
608    PlaceIndicatorVertex(x1, y1);
609}
610
611void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
612    Vector3 p1(0, INDICATOR_RADIUS, 0);
613    Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
614    Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
615    Vector3 pc(0, 0, 0);
616
617    DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
618    DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
619}
620
621void GfxCore::DrawCompass() {
622    // Ticks.
623    BeginLines();
624    for (int angle = 315; angle > 0; angle -= 45) {
625        DrawTick(angle);
626    }
627    SetColour(col_GREEN);
628    DrawTick(0);
629    EndLines();
630
631    // Compass background.
632    DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
633
634    // Compass arrow.
635    DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
636}
637
638// Draw the non-rotating background to the clino.
639void GfxCore::DrawClinoBack() {
640    BeginLines();
641    for (int angle = 0; angle <= 180; angle += 90) {
642        DrawTick(angle);
643    }
644
645    SetColour(col_GREY);
646    PlaceIndicatorVertex(0, INDICATOR_RADIUS);
647    PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
648    PlaceIndicatorVertex(0, 0);
649    PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
650
651    EndLines();
652}
653
654void GfxCore::DrawClino() {
655    // Ticks.
656    SetColour(col_GREEN);
657    BeginLines();
658    DrawTick(0);
659    EndLines();
660
661    // Clino background.
662    DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
663
664    // Elevation arrow.
665    DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
666}
667
668void GfxCore::Draw2dIndicators()
669{
670    // Draw the compass and elevation indicators.
671
672    const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
673
674    const int comp_centre_x = GetCompassXPosition();
675
676    if (m_Compass && !m_Parent->IsExtendedElevation()) {
677        // If the user is dragging the compass with the pointer outside the
678        // compass, we snap to 45 degree multiples, and the ticks go white.
679        SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
680        DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
681    }
682
683    const int elev_centre_x = GetClinoXPosition();
684
685    if (m_Clino) {
686        // If the user is dragging the clino with the pointer outside the
687        // clino, we snap to 90 degree multiples, and the ticks go white.
688        SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
689        DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
690        DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
691    }
692
693    SetColour(TEXT_COLOUR);
694
695    static int triple_zero_width = 0;
696    static int height = 0;
697    if (!triple_zero_width) {
698        GetTextExtent(wxT("000"), &triple_zero_width, &height);
699    }
700    const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
701
702    if (m_Compass && !m_Parent->IsExtendedElevation()) {
703        wxString str;
704        int value;
705        int brg_unit;
706        if (m_Degrees) {
707            value = int(m_PanAngle);
708            /* TRANSLATORS: degree symbol - probably should be translated to
709             * itself. */
710            brg_unit = /*°*/344;
711        } else {
712            value = int(m_PanAngle * 200.0 / 180.0);
713            /* TRANSLATORS: symbol for grad (400 grad = 360 degrees = full
714             * circle). */
715            brg_unit = /*ᵍ*/76;
716        }
717        str.Printf(wxT("%03d"), value);
718        str += wmsg(brg_unit);
719        DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
720
721        // TRANSLATORS: Used in aven above the compass indicator at the lower
722        // right of the display, with a bearing below "Facing".  This indicates the
723        // direction the viewer is "facing" in.
724        //
725        // Try to keep this translation short - ideally at most 10 characters -
726        // as otherwise the compass and clino will be moved further apart to
727        // make room. */
728        str = wmsg(/*Facing*/203);
729        int w;
730        GetTextExtent(str, &w, NULL);
731        DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
732    }
733
734    if (m_Clino) {
735        if (m_TiltAngle == -90.0) {
736            // TRANSLATORS: Label used for "clino" in Aven when the view is
737            // from directly above.
738            //
739            // Try to keep this translation short - ideally at most 10
740            // characters - as otherwise the compass and clino will be moved
741            // further apart to make room. */
742            wxString str = wmsg(/*Plan*/432);
743            static int width = 0;
744            if (!width) {
745                GetTextExtent(str, &width, NULL);
746            }
747            int x = elev_centre_x - width / 2;
748            DrawIndicatorText(x, y_off + height / 2, str);
749        } else if (m_TiltAngle == 90.0) {
750            // TRANSLATORS: Label used for "clino" in Aven when the view is
751            // from directly below.
752            //
753            // Try to keep this translation short - ideally at most 10
754            // characters - as otherwise the compass and clino will be moved
755            // further apart to make room. */
756            wxString str = wmsg(/*Kiwi Plan*/433);
757            static int width = 0;
758            if (!width) {
759                GetTextExtent(str, &width, NULL);
760            }
761            int x = elev_centre_x - width / 2;
762            DrawIndicatorText(x, y_off + height / 2, str);
763        } else {
764            int angle;
765            wxString str;
766            int width;
767            int unit;
768            if (m_Percent) {
769                static int zero_width = 0;
770                if (!zero_width) {
771                    GetTextExtent(wxT("0"), &zero_width, NULL);
772                }
773                width = zero_width;
774                if (m_TiltAngle > 89.99) {
775                    angle = 1000000;
776                } else if (m_TiltAngle < -89.99) {
777                    angle = -1000000;
778                } else {
779                    angle = int(100 * tan(rad(m_TiltAngle)));
780                }
781                if (angle > 99999 || angle < -99999) {
782                    str = angle > 0 ? wxT("+") : wxT("-");
783                    /* TRANSLATORS: infinity symbol - used for the percentage gradient on
784                     * vertical angles. */
785                    str += wmsg(/*∞*/431);
786                } else {
787                    str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("0");
788                }
789                /* TRANSLATORS: symbol for percentage gradient (100% = 45
790                 * degrees = 50 grad). */
791                unit = /*%*/96;
792            } else if (m_Degrees) {
793                static int zero_zero_width = 0;
794                if (!zero_zero_width) {
795                    GetTextExtent(wxT("00"), &zero_zero_width, NULL);
796                }
797                width = zero_zero_width;
798                angle = int(m_TiltAngle);
799                str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
800                unit = /*°*/344;
801            } else {
802                width = triple_zero_width;
803                angle = int(m_TiltAngle * 200.0 / 180.0);
804                str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
805                unit = /*ᵍ*/76;
806            }
807
808            int sign_offset = 0;
809            if (unit == /*%*/96) {
810                // Right align % since the width changes so much.
811                GetTextExtent(str, &sign_offset, NULL);
812                sign_offset -= width;
813            } else if (angle < 0) {
814                // Adjust horizontal position so the left of the first digit is
815                // always in the same place.
816                static int minus_width = 0;
817                if (!minus_width) {
818                    GetTextExtent(wxT("-"), &minus_width, NULL);
819                }
820                sign_offset = minus_width;
821            } else if (angle > 0) {
822                // Adjust horizontal position so the left of the first digit is
823                // always in the same place.
824                static int plus_width = 0;
825                if (!plus_width) {
826                    GetTextExtent(wxT("+"), &plus_width, NULL);
827                }
828                sign_offset = plus_width;
829            }
830
831            str += wmsg(unit);
832            DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
833
834            // TRANSLATORS: Label used for "clino" in Aven when the view is
835            // neither from directly above nor from directly below.  It is
836            // also used in the dialog for editing a marked position in a
837            // presentation.
838            //
839            // Try to keep this translation short - ideally at most 10
840            // characters - as otherwise the compass and clino will be moved
841            // further apart to make room. */
842            str = wmsg(/*Elevation*/118);
843            static int elevation_width = 0;
844            if (!elevation_width) {
845                GetTextExtent(str, &elevation_width, NULL);
846            }
847            int x = elev_centre_x - elevation_width / 2;
848            DrawIndicatorText(x, y_off + height, str);
849        }
850    }
851}
852
853void GfxCore::NattyDrawNames()
854{
855    // Draw station names, without overlapping.
856
857    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
858    const unsigned int quantised_x = GetXSize() / quantise;
859    const unsigned int quantised_y = GetYSize() / quantise;
860    const size_t buffer_size = quantised_x * quantised_y;
861
862    if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
863
864    memset((void*) m_LabelGrid, 0, buffer_size);
865
866    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
867    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
868        if (!((m_Surface && (*label)->IsSurface()) ||
869              (m_Legs && (*label)->IsUnderground()) ||
870              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
871            // if this station isn't to be displayed, skip to the next
872            // (last case is for stns with no legs attached)
873            continue;
874        }
875
876        double x, y, z;
877
878        Transform(**label, &x, &y, &z);
879        // Check if the label is behind us (in perspective view).
880        if (z <= 0.0 || z >= 1.0) continue;
881
882        // Apply a small shift so that translating the view doesn't make which
883        // labels are displayed change as the resulting twinkling effect is
884        // distracting.
885        double tx, ty, tz;
886        Transform(Vector3(), &tx, &ty, &tz);
887        tx -= floor(tx / quantise) * quantise;
888        ty -= floor(ty / quantise) * quantise;
889
890        tx = x - tx;
891        if (tx < 0) continue;
892
893        ty = y - ty;
894        if (ty < 0) continue;
895
896        unsigned int iy = unsigned(ty) / quantise;
897        if (iy >= quantised_y) continue;
898        unsigned int width = (*label)->get_width();
899        unsigned int ix = unsigned(tx) / quantise;
900        if (ix + width >= quantised_x) continue;
901
902        char * test = m_LabelGrid + ix + iy * quantised_x;
903        if (memchr(test, 1, width)) continue;
904
905        x += 3;
906        y -= GetFontSize() / 2;
907        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
908
909        if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
910        test -= quantised_x * iy;
911        iy += 4;
912        while (--iy && test < m_LabelGrid + buffer_size) {
913            memset(test, 1, width);
914            test += quantised_x;
915        }
916    }
917}
918
919void GfxCore::SimpleDrawNames()
920{
921    // Draw all station names, without worrying about overlaps
922    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
923    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
924        if (!((m_Surface && (*label)->IsSurface()) ||
925              (m_Legs && (*label)->IsUnderground()) ||
926              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
927            // if this station isn't to be displayed, skip to the next
928            // (last case is for stns with no legs attached)
929            continue;
930        }
931
932        double x, y, z;
933        Transform(**label, &x, &y, &z);
934
935        // Check if the label is behind us (in perspective view).
936        if (z <= 0) continue;
937
938        x += 3;
939        y -= GetFontSize() / 2;
940        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
941    }
942}
943
944void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
945{
946    int total_block_height =
947        KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
948    if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
949    if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
950
951    const int bottom = -total_block_height;
952
953    int size = 0;
954    if (!other.empty()) GetTextExtent(other, &size, NULL);
955    int band;
956    for (band = 0; band < num_bands; ++band) {
957        int x;
958        GetTextExtent(key_legends[band], &x, NULL);
959        if (x > size) size = x;
960    }
961
962    int left = -KEY_BLOCK_WIDTH - size;
963
964    key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
965    key_lowerleft[m_ColourBy].y = bottom;
966
967    int y = bottom;
968    if (!units.empty()) y += KEY_BLOCK_HEIGHT;
969
970    if (!other.empty()) {
971        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
972                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
973        SetColour(col_BLACK);
974        BeginPolyline();
975        PlaceIndicatorVertex(left, y);
976        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
977        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y + KEY_BLOCK_HEIGHT);
978        PlaceIndicatorVertex(left, y + KEY_BLOCK_HEIGHT);
979        PlaceIndicatorVertex(left, y);
980        EndPolyline();
981        y += KEY_BLOCK_HEIGHT * 2;
982    }
983
984    int start = y;
985    if (num_bands == 1) {
986        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
987                            KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
988        y += KEY_BLOCK_HEIGHT;
989    } else {
990        for (band = 0; band < num_bands - 1; ++band) {
991            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
992                                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
993            y += KEY_BLOCK_HEIGHT;
994        }
995    }
996
997    SetColour(col_BLACK);
998    BeginPolyline();
999    PlaceIndicatorVertex(left, y);
1000    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1001    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
1002    PlaceIndicatorVertex(left, start);
1003    PlaceIndicatorVertex(left, y);
1004    EndPolyline();
1005
1006    SetColour(TEXT_COLOUR);
1007
1008    y = bottom;
1009    if (!units.empty()) {
1010        GetTextExtent(units, &size, NULL);
1011        DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
1012        y += KEY_BLOCK_HEIGHT;
1013    }
1014    y -= GetFontSize() / 2;
1015    left += KEY_BLOCK_WIDTH + 5;
1016
1017    if (!other.empty()) {
1018        y += KEY_BLOCK_HEIGHT / 2;
1019        DrawIndicatorText(left, y, other);
1020        y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
1021    }
1022
1023    if (num_bands == 1) {
1024        y += KEY_BLOCK_HEIGHT / 2;
1025        DrawIndicatorText(left, y, key_legends[0]);
1026    } else {
1027        for (band = 0; band < num_bands; ++band) {
1028            DrawIndicatorText(left, y, key_legends[band]);
1029            y += KEY_BLOCK_HEIGHT;
1030        }
1031    }
1032}
1033
1034void GfxCore::DrawDepthKey()
1035{
1036    Double z_ext = m_Parent->GetDepthExtent();
1037    int num_bands = 1;
1038    int sf = 0;
1039    if (z_ext > 0.0) {
1040        num_bands = GetNumColourBands();
1041        Double z_range = z_ext;
1042        if (!m_Metric) z_range /= METRES_PER_FOOT;
1043        sf = max(0, 1 - (int)floor(log10(z_range)));
1044    }
1045
1046    Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
1047    for (int band = 0; band < num_bands; ++band) {
1048        Double z = z_min;
1049        if (band)
1050            z += z_ext * band / (num_bands - 1);
1051
1052        if (!m_Metric)
1053            z /= METRES_PER_FOOT;
1054
1055        key_legends[band].Printf(wxT("%.*f"), sf, z);
1056    }
1057
1058    DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1059}
1060
1061void GfxCore::DrawDateKey()
1062{
1063    int num_bands;
1064    if (!HasDateInformation()) {
1065        num_bands = 0;
1066    } else {
1067        int date_ext = m_Parent->GetDateExtent();
1068        if (date_ext == 0) {
1069            num_bands = 1;
1070        } else {
1071            num_bands = GetNumColourBands();
1072        }
1073        for (int band = 0; band < num_bands; ++band) {
1074            int y, m, d;
1075            int days = m_Parent->GetDateMin();
1076            if (band)
1077                days += date_ext * band / (num_bands - 1);
1078            ymd_from_days_since_1900(days, &y, &m, &d);
1079            key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
1080        }
1081    }
1082
1083    wxString other;
1084    if (!m_Parent->HasCompleteDateInfo()) {
1085        /* TRANSLATORS: Used in the "colour key" for "colour by date" if there
1086         * are surveys without date information.  Try to keep this fairly short.
1087         */
1088        other = wmsg(/*Undated*/221);
1089    }
1090
1091    DrawColourKey(num_bands, other, wxString());
1092}
1093
1094void GfxCore::DrawErrorKey()
1095{
1096    int num_bands;
1097    if (HasErrorInformation()) {
1098        // Use fixed colours for each error factor so it's directly visually
1099        // comparable between surveys.
1100        num_bands = GetNumColourBands();
1101        for (int band = 0; band < num_bands; ++band) {
1102            double E = MAX_ERROR * band / (num_bands - 1);
1103            key_legends[band].Printf(wxT("%.2f"), E);
1104        }
1105    } else {
1106        num_bands = 0;
1107    }
1108
1109    // Always show the "Not in loop" legend for now (FIXME).
1110    /* TRANSLATORS: Used in the "colour key" for "colour by error" for surveys
1111     * which aren’t part of a loop and so have no error information. Try to keep
1112     * this fairly short. */
1113    DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
1114}
1115
1116void GfxCore::DrawGradientKey()
1117{
1118    int num_bands;
1119    // Use fixed colours for each gradient so it's directly visually comparable
1120    // between surveys.
1121    num_bands = GetNumColourBands();
1122    wxString units = wmsg(m_Degrees ? /*°*/344 : /*ᵍ*/76);
1123    for (int band = 0; band < num_bands; ++band) {
1124        double gradient = double(band) / (num_bands - 1);
1125        if (m_Degrees) {
1126            gradient *= 90.0;
1127        } else {
1128            gradient *= 100.0;
1129        }
1130        key_legends[band].Printf(wxT("%.f%s"), gradient, units);
1131    }
1132
1133    DrawColourKey(num_bands, wxString(), wxString());
1134}
1135
1136void GfxCore::DrawLengthKey()
1137{
1138    int num_bands;
1139    // Use fixed colours for each length so it's directly visually comparable
1140    // between surveys.
1141    num_bands = GetNumColourBands();
1142    for (int band = 0; band < num_bands; ++band) {
1143        double len = pow(10, LOG_LEN_MAX * band / (num_bands - 1));
1144        if (!m_Metric) {
1145            len /= METRES_PER_FOOT;
1146        }
1147        key_legends[band].Printf(wxT("%.1f"), len);
1148    }
1149
1150    DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1151}
1152
1153void GfxCore::DrawScaleBar()
1154{
1155    // Draw the scalebar.
1156    if (GetPerspective()) return;
1157
1158    // Calculate how many metres of survey are currently displayed across the
1159    // screen.
1160    Double across_screen = SurveyUnitsAcrossViewport();
1161
1162    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
1163    if (f > 0.75) {
1164        f = 0.75;
1165    } else if (f < 0.5) {
1166        // Stop it getting squeezed to nothing.
1167        // FIXME: In this case we should probably move the compass and clino up
1168        // to make room rather than letting stuff overlap.
1169        f = 0.5;
1170    }
1171
1172    // Convert to imperial measurements if required.
1173    Double multiplier = 1.0;
1174    if (!m_Metric) {
1175        across_screen /= METRES_PER_FOOT;
1176        multiplier = METRES_PER_FOOT;
1177        if (across_screen >= 5280.0 / f) {
1178            across_screen /= 5280.0;
1179            multiplier *= 5280.0;
1180        }
1181    }
1182
1183    // Calculate the length of the scale bar.
1184    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1185    Double t = across_screen * f / size_snap;
1186    if (t >= 5.0) {
1187        size_snap *= 5.0;
1188    } else if (t >= 2.0) {
1189        size_snap *= 2.0;
1190    }
1191
1192    if (!m_Metric) size_snap *= multiplier;
1193
1194    // Actual size of the thing in pixels:
1195    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1196    m_ScaleBarWidth = size;
1197
1198    // Draw it...
1199    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1200    int interval = size / 10;
1201
1202    gla_colour col = col_WHITE;
1203    for (int ix = 0; ix < 10; ix++) {
1204        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1205
1206        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1207
1208        col = (col == col_WHITE) ? col_GREY : col_WHITE;
1209    }
1210
1211    // Add labels.
1212    wxString str;
1213    int units;
1214    if (m_Metric) {
1215        Double km = size_snap * 1e-3;
1216        if (km >= 1.0) {
1217            size_snap = km;
1218            /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1219             * used e.g.  "5km".
1220             *
1221             * If there should be a space between the number and this, include
1222             * one in the translation. */
1223            units = /*km*/423;
1224        } else if (size_snap >= 1.0) {
1225            /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1226             * e.g. "10m".
1227             *
1228             * If there should be a space between the number and this, include
1229             * one in the translation. */
1230            units = /*m*/424;
1231        } else {
1232            size_snap *= 1e2;
1233            /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1234             * used e.g.  "50cm".
1235             *
1236             * If there should be a space between the number and this, include
1237             * one in the translation. */
1238            units = /*cm*/425;
1239        }
1240    } else {
1241        size_snap /= METRES_PER_FOOT;
1242        Double miles = size_snap / 5280.0;
1243        if (miles >= 1.0) {
1244            size_snap = miles;
1245            if (size_snap >= 2.0) {
1246                /* TRANSLATORS: abbreviation for "miles" (unit of length,
1247                 * plural), used e.g.  "2 miles".
1248                 *
1249                 * If there should be a space between the number and this,
1250                 * include one in the translation. */
1251                units = /* miles*/426;
1252            } else {
1253                /* TRANSLATORS: abbreviation for "mile" (unit of length,
1254                 * singular), used e.g.  "1 mile".
1255                 *
1256                 * If there should be a space between the number and this,
1257                 * include one in the translation. */
1258                units = /* mile*/427;
1259            }
1260        } else if (size_snap >= 1.0) {
1261            /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1262             * as "10ft".
1263             *
1264             * If there should be a space between the number and this, include
1265             * one in the translation. */
1266            units = /*ft*/428;
1267        } else {
1268            size_snap *= 12.0;
1269            /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1270             * e.g. as "6in".
1271             *
1272             * If there should be a space between the number and this, include
1273             * one in the translation. */
1274            units = /*in*/429;
1275        }
1276    }
1277    if (size_snap >= 1.0) {
1278        str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1279    } else {
1280        int sf = -(int)floor(log10(size_snap));
1281        str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1282    }
1283
1284    int text_width, text_height;
1285    GetTextExtent(str, &text_width, &text_height);
1286    const int text_y = end_y - text_height + 1;
1287    SetColour(TEXT_COLOUR);
1288    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1289    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1290}
1291
1292bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1293{
1294    if (Animating()) return false;
1295
1296    if (point.x < 0 || point.x >= GetXSize() ||
1297        point.y < 0 || point.y >= GetYSize()) {
1298        return false;
1299    }
1300
1301    SetDataTransform();
1302
1303    if (!m_HitTestGridValid) CreateHitTestGrid();
1304
1305    int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1306    int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
1307
1308    LabelInfo *best = NULL;
1309    int dist_sqrd = sqrd_measure_threshold;
1310    int square = grid_x + grid_y * HITTEST_SIZE;
1311    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1312
1313    while (iter != m_PointGrid[square].end()) {
1314        LabelInfo *pt = *iter++;
1315
1316        double cx, cy, cz;
1317
1318        Transform(*pt, &cx, &cy, &cz);
1319
1320        cy = GetYSize() - cy;
1321
1322        int dx = point.x - int(cx);
1323        int ds = dx * dx;
1324        if (ds >= dist_sqrd) continue;
1325        int dy = point.y - int(cy);
1326
1327        ds += dy * dy;
1328        if (ds >= dist_sqrd) continue;
1329
1330        dist_sqrd = ds;
1331        best = pt;
1332
1333        if (ds == 0) break;
1334    }
1335
1336    if (best) {
1337        m_Parent->ShowInfo(best, m_there);
1338        if (centre) {
1339            // FIXME: allow Ctrl-Click to not set there or something?
1340            CentreOn(*best);
1341            WarpPointer(GetXSize() / 2, GetYSize() / 2);
1342            SetThere(best);
1343            m_Parent->SelectTreeItem(best);
1344        }
1345    } else {
1346        // Left-clicking not on a survey cancels the measuring line.
1347        if (centre) {
1348            ClearTreeSelection();
1349        } else {
1350            m_Parent->ShowInfo(best, m_there);
1351            double x, y, z;
1352            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1353            temp_here.assign(Vector3(x, y, z));
1354            SetHere(&temp_here);
1355        }
1356    }
1357
1358    return best;
1359}
1360
1361void GfxCore::OnSize(wxSizeEvent& event)
1362{
1363    // Handle a change in window size.
1364    wxSize size = event.GetSize();
1365
1366    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1367        // Before things are fully initialised, we sometimes get a bogus
1368        // resize message...
1369        // FIXME have changes in MainFrm cured this?  It still happens with
1370        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1371        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1372        // is resized such that the GfxCore window isn't visible.
1373        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1374        return;
1375    }
1376
1377    event.Skip();
1378
1379    if (m_DoneFirstShow) {
1380        TryToFreeArrays();
1381
1382        m_HitTestGridValid = false;
1383
1384        ForceRefresh();
1385    }
1386}
1387
1388void GfxCore::DefaultParameters()
1389{
1390    // Set default viewing parameters.
1391
1392    m_Surface = false;
1393    if (!m_Parent->HasUndergroundLegs()) {
1394        if (m_Parent->HasSurfaceLegs()) {
1395            // If there are surface legs, but no underground legs, turn
1396            // surface surveys on.
1397            m_Surface = true;
1398        } else {
1399            // If there are no legs (e.g. after loading a .pos file), turn
1400            // crosses on.
1401            m_Crosses = true;
1402        }
1403    }
1404
1405    m_PanAngle = 0.0;
1406    if (m_Parent->IsExtendedElevation()) {
1407        m_TiltAngle = 0.0;
1408    } else {
1409        m_TiltAngle = -90.0;
1410    }
1411
1412    SetRotation(m_PanAngle, m_TiltAngle);
1413    SetTranslation(Vector3());
1414
1415    m_RotationStep = 30.0;
1416    m_Rotating = false;
1417    m_SwitchingTo = 0;
1418    m_Entrances = false;
1419    m_FixedPts = false;
1420    m_ExportedPts = false;
1421    m_Grid = false;
1422    m_BoundingBox = false;
1423    m_Tubes = false;
1424    if (GetPerspective()) TogglePerspective();
1425}
1426
1427void GfxCore::Defaults()
1428{
1429    // Restore default scale, rotation and translation parameters.
1430    DefaultParameters();
1431    SetScale(1.0);
1432
1433    // Invalidate all the cached lists.
1434    GLACanvas::FirstShow();
1435
1436    ForceRefresh();
1437}
1438
1439void GfxCore::Animate()
1440{
1441    // Don't show pointer coordinates while animating.
1442    // FIXME : only do this when we *START* animating!  Use a static copy
1443    // of the value of "Animating()" last time we were here to track this?
1444    // MainFrm now checks if we're trying to clear already cleared labels
1445    // and just returns, but it might be simpler to check here!
1446    ClearCoords();
1447    m_Parent->ShowInfo();
1448
1449    long t;
1450    if (movie) {
1451        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1452        if (!movie->AddFrame()) {
1453            wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1454            delete movie;
1455            movie = NULL;
1456            presentation_mode = 0;
1457            return;
1458        }
1459        t = 1000 / 25; // 25 frames per second
1460    } else {
1461        static long t_prev = 0;
1462        t = timer.Time();
1463        // Avoid redrawing twice in the same frame.
1464        long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1465        if (delta_t < 1000 / MAX_FRAMERATE)
1466            return;
1467        t_prev = t;
1468        if (presentation_mode == PLAYING && pres_speed != 0.0)
1469            t = delta_t;
1470    }
1471
1472    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1473        // FIXME: It would probably be better to work relative to the time we
1474        // passed the last mark, but that's complicated by the speed
1475        // potentially changing (or even the direction of playback reversing)
1476        // at any point during playback.
1477        Double tick = t * 0.001 * fabs(pres_speed);
1478        while (tick >= next_mark_time) {
1479            tick -= next_mark_time;
1480            this_mark_total = 0;
1481            PresentationMark prev_mark = next_mark;
1482            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1483            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1484            if (pres_reverse)
1485                next_mark = m_Parent->GetPresMark(MARK_PREV);
1486            else
1487                next_mark = m_Parent->GetPresMark(MARK_NEXT);
1488            if (!next_mark.is_valid()) {
1489                SetView(prev_mark);
1490                presentation_mode = 0;
1491                if (movie && !movie->Close()) {
1492                    wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1493                }
1494                delete movie;
1495                movie = NULL;
1496                break;
1497            }
1498
1499            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1500            if (tmp > 0) {
1501                next_mark_time = tmp;
1502            } else {
1503                double d = (next_mark - prev_mark).magnitude();
1504                // FIXME: should ignore component of d which is unseen in
1505                // non-perspective mode?
1506                next_mark_time = sqrd(d / 30.0);
1507                double a = next_mark.angle - prev_mark.angle;
1508                if (a > 180.0) {
1509                    next_mark.angle -= 360.0;
1510                    a = 360.0 - a;
1511                } else if (a < -180.0) {
1512                    next_mark.angle += 360.0;
1513                    a += 360.0;
1514                } else {
1515                    a = fabs(a);
1516                }
1517                next_mark_time += sqrd(a / 60.0);
1518                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1519                next_mark_time += sqrd(ta / 60.0);
1520                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1521                next_mark_time += sqrd(s / 2.0);
1522                next_mark_time = sqrt(next_mark_time);
1523                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1524                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1525                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1526                if (tmp < 0) next_mark_time /= -tmp;
1527            }
1528        }
1529
1530        if (presentation_mode) {
1531            // Advance position towards next_mark
1532            double p = tick / next_mark_time;
1533            double q = 1 - p;
1534            PresentationMark here = GetView();
1535            if (next_mark.angle < 0) {
1536                if (here.angle >= next_mark.angle + 360.0)
1537                    here.angle -= 360.0;
1538            } else if (next_mark.angle >= 360.0) {
1539                if (here.angle <= next_mark.angle - 360.0)
1540                    here.angle += 360.0;
1541            }
1542            here.assign(q * here + p * next_mark);
1543            here.angle = q * here.angle + p * next_mark.angle;
1544            if (here.angle < 0) here.angle += 360.0;
1545            else if (here.angle >= 360.0) here.angle -= 360.0;
1546            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1547            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1548            SetView(here);
1549            this_mark_total += tick;
1550            next_mark_time -= tick;
1551        }
1552
1553        ForceRefresh();
1554        return;
1555    }
1556
1557    // When rotating...
1558    if (m_Rotating) {
1559        Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1560        TurnCave(step);
1561    }
1562
1563    if (m_SwitchingTo == PLAN) {
1564        // When switching to plan view...
1565        Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1566        TiltCave(step);
1567        if (m_TiltAngle == -90.0) {
1568            m_SwitchingTo = 0;
1569        }
1570    } else if (m_SwitchingTo == ELEVATION) {
1571        // When switching to elevation view...
1572        Double step;
1573        if (m_TiltAngle > 0.0) {
1574            step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1575        } else {
1576            step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1577        }
1578        if (fabs(step) >= fabs(m_TiltAngle)) {
1579            m_SwitchingTo = 0;
1580            step = -m_TiltAngle;
1581        }
1582        TiltCave(step);
1583    } else if (m_SwitchingTo) {
1584        // Rotate the shortest way around to the destination angle.  If we're
1585        // 180 off, we favour turning anticlockwise, as auto-rotation does by
1586        // default.
1587        Double target = (m_SwitchingTo - NORTH) * 90;
1588        Double diff = target - m_PanAngle;
1589        diff = fmod(diff, 360);
1590        if (diff <= -180)
1591            diff += 360;
1592        else if (diff > 180)
1593            diff -= 360;
1594        if (m_RotationStep < 0 && diff == 180.0)
1595            diff = -180.0;
1596        Double step = base_pan - m_PanAngle;
1597        Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1598        if (diff > 0) {
1599            step += delta;
1600        } else {
1601            step -= delta;
1602        }
1603        step = fmod(step, 360);
1604        if (step <= -180)
1605            step += 360;
1606        else if (step > 180)
1607            step -= 360;
1608        if (fabs(step) >= fabs(diff)) {
1609            m_SwitchingTo = 0;
1610            step = diff;
1611        }
1612        TurnCave(step);
1613    }
1614
1615    ForceRefresh();
1616}
1617
1618// How much to allow around the box - this is because of the ring shape
1619// at one end of the line.
1620static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1621#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1622void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
1623{
1624#ifdef __WXMSW__
1625    (void)a;
1626    (void)b;
1627    (void)c;
1628    // FIXME: We get odd redraw artifacts if we just update the line, and
1629    // redrawing the whole scene doesn't actually seem to be measurably
1630    // slower.  That may not be true with software rendering though...
1631    ForceRefresh();
1632#else
1633    // Best of all might be to copy the window contents before we draw the
1634    // line, then replace each time we redraw.
1635
1636    // Calculate the minimum rectangle which includes the old and new
1637    // measuring lines to minimise the redraw time
1638    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1639    double X, Y, Z;
1640    if (a) {
1641        if (!Transform(*a, &X, &Y, &Z)) {
1642            printf("oops\n");
1643        } else {
1644            int x = int(X);
1645            int y = GetYSize() - 1 - int(Y);
1646            l = x;
1647            r = x;
1648            u = y;
1649            d = y;
1650        }
1651    }
1652    if (b) {
1653        if (!Transform(*b, &X, &Y, &Z)) {
1654            printf("oops\n");
1655        } else {
1656            int x = int(X);
1657            int y = GetYSize() - 1 - int(Y);
1658            l = min(l, x);
1659            r = max(r, x);
1660            u = max(u, y);
1661            d = min(d, y);
1662        }
1663    }
1664    if (c) {
1665        if (!Transform(*c, &X, &Y, &Z)) {
1666            printf("oops\n");
1667        } else {
1668            int x = int(X);
1669            int y = GetYSize() - 1 - int(Y);
1670            l = min(l, x);
1671            r = max(r, x);
1672            u = max(u, y);
1673            d = min(d, y);
1674        }
1675    }
1676    l -= MARGIN;
1677    r += MARGIN;
1678    u += MARGIN;
1679    d -= MARGIN;
1680    RefreshRect(wxRect(l, d, r - l, u - d), false);
1681#endif
1682}
1683
1684void GfxCore::SetHereFromTree(const LabelInfo * p)
1685{
1686    SetHere(p);
1687    m_Parent->ShowInfo(m_here, m_there);
1688}
1689
1690void GfxCore::SetHere()
1691{
1692    if (!m_here) return;
1693    bool line_active = MeasuringLineActive();
1694    const LabelInfo * old = m_here;
1695    m_here = NULL;
1696    if (line_active || MeasuringLineActive())
1697        RefreshLine(old, m_there, m_here);
1698}
1699
1700void GfxCore::SetHere(const LabelInfo *p)
1701{
1702    bool line_active = MeasuringLineActive();
1703    const LabelInfo * old = m_here;
1704    m_here = p;
1705    if (line_active || MeasuringLineActive())
1706        RefreshLine(old, m_there, m_here);
1707}
1708
1709void GfxCore::SetThere()
1710{
1711    if (!m_there) return;
1712    const LabelInfo * old = m_there;
1713    m_there = NULL;
1714    RefreshLine(m_here, old, m_there);
1715}
1716
1717void GfxCore::SetThere(const LabelInfo * p)
1718{
1719    const LabelInfo * old = m_there;
1720    m_there = p;
1721    RefreshLine(m_here, old, m_there);
1722}
1723
1724void GfxCore::CreateHitTestGrid()
1725{
1726    if (!m_PointGrid) {
1727        // Initialise hit-test grid.
1728        m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1729    } else {
1730        // Clear hit-test grid.
1731        for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1732            m_PointGrid[i].clear();
1733        }
1734    }
1735
1736    // Fill the grid.
1737    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1738    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1739    while (pos != end) {
1740        LabelInfo* label = *pos++;
1741
1742        if (!((m_Surface && label->IsSurface()) ||
1743              (m_Legs && label->IsUnderground()) ||
1744              (!label->IsSurface() && !label->IsUnderground()))) {
1745            // if this station isn't to be displayed, skip to the next
1746            // (last case is for stns with no legs attached)
1747            continue;
1748        }
1749
1750        // Calculate screen coordinates.
1751        double cx, cy, cz;
1752        Transform(*label, &cx, &cy, &cz);
1753        if (cx < 0 || cx >= GetXSize()) continue;
1754        if (cy < 0 || cy >= GetYSize()) continue;
1755
1756        cy = GetYSize() - cy;
1757
1758        // On-screen, so add to hit-test grid...
1759        int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1760        int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
1761
1762        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1763    }
1764
1765    m_HitTestGridValid = true;
1766}
1767
1768//
1769//  Methods for controlling the orientation of the survey
1770//
1771
1772void GfxCore::TurnCave(Double angle)
1773{
1774    // Turn the cave around its z-axis by a given angle.
1775
1776    m_PanAngle += angle;
1777    // Wrap to range [0, 360):
1778    m_PanAngle = fmod(m_PanAngle, 360.0);
1779    if (m_PanAngle < 0.0) {
1780        m_PanAngle += 360.0;
1781    }
1782
1783    m_HitTestGridValid = false;
1784    if (m_here && m_here == &temp_here) SetHere();
1785
1786    SetRotation(m_PanAngle, m_TiltAngle);
1787}
1788
1789void GfxCore::TurnCaveTo(Double angle)
1790{
1791    if (m_Rotating) {
1792        // If we're rotating, jump to the specified angle.
1793        TurnCave(angle - m_PanAngle);
1794        SetPanBase();
1795        return;
1796    }
1797
1798    int new_switching_to = ((int)angle) / 90 + NORTH;
1799    if (new_switching_to == m_SwitchingTo) {
1800        // A second order to switch takes us there right away
1801        TurnCave(angle - m_PanAngle);
1802        m_SwitchingTo = 0;
1803        ForceRefresh();
1804    } else {
1805        SetPanBase();
1806        m_SwitchingTo = new_switching_to;
1807    }
1808}
1809
1810void GfxCore::TiltCave(Double tilt_angle)
1811{
1812    // Tilt the cave by a given angle.
1813    if (m_TiltAngle + tilt_angle > 90.0) {
1814        m_TiltAngle = 90.0;
1815    } else if (m_TiltAngle + tilt_angle < -90.0) {
1816        m_TiltAngle = -90.0;
1817    } else {
1818        m_TiltAngle += tilt_angle;
1819    }
1820
1821    m_HitTestGridValid = false;
1822    if (m_here && m_here == &temp_here) SetHere();
1823
1824    SetRotation(m_PanAngle, m_TiltAngle);
1825}
1826
1827void GfxCore::TranslateCave(int dx, int dy)
1828{
1829    AddTranslationScreenCoordinates(dx, dy);
1830    m_HitTestGridValid = false;
1831
1832    if (m_here && m_here == &temp_here) SetHere();
1833
1834    ForceRefresh();
1835}
1836
1837void GfxCore::DragFinished()
1838{
1839    m_MouseOutsideCompass = m_MouseOutsideElev = false;
1840    ForceRefresh();
1841}
1842
1843void GfxCore::ClearCoords()
1844{
1845    m_Parent->ClearCoords();
1846}
1847
1848void GfxCore::SetCoords(wxPoint point)
1849{
1850    // We can't work out 2D coordinates from a perspective view, and it
1851    // doesn't really make sense to show coordinates while we're animating.
1852    if (GetPerspective() || Animating()) return;
1853
1854    // Update the coordinate or altitude display, given the (x, y) position in
1855    // window coordinates.  The relevant display is updated depending on
1856    // whether we're in plan or elevation view.
1857
1858    double cx, cy, cz;
1859
1860    SetDataTransform();
1861    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
1862
1863    if (ShowingPlan()) {
1864        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1865                            cy + m_Parent->GetOffset().GetY(),
1866                            m_there);
1867    } else if (ShowingElevation()) {
1868        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
1869                              m_there);
1870    } else {
1871        m_Parent->ClearCoords();
1872    }
1873}
1874
1875int GfxCore::GetCompassWidth() const
1876{
1877    static int result = 0;
1878    if (result == 0) {
1879        result = INDICATOR_BOX_SIZE;
1880        int width;
1881        const wxString & msg = wmsg(/*Facing*/203);
1882        GetTextExtent(msg, &width, NULL);
1883        if (width > result) result = width;
1884    }
1885    return result;
1886}
1887
1888int GfxCore::GetClinoWidth() const
1889{
1890    static int result = 0;
1891    if (result == 0) {
1892        result = INDICATOR_BOX_SIZE;
1893        int width;
1894        const wxString & msg1 = wmsg(/*Plan*/432);
1895        GetTextExtent(msg1, &width, NULL);
1896        if (width > result) result = width;
1897        const wxString & msg2 = wmsg(/*Kiwi Plan*/433);
1898        GetTextExtent(msg2, &width, NULL);
1899        if (width > result) result = width;
1900        const wxString & msg3 = wmsg(/*Elevation*/118);
1901        GetTextExtent(msg3, &width, NULL);
1902        if (width > result) result = width;
1903    }
1904    return result;
1905}
1906
1907int GfxCore::GetCompassXPosition() const
1908{
1909    // Return the x-coordinate of the centre of the compass in window
1910    // coordinates.
1911    return GetXSize() - INDICATOR_OFFSET_X - GetCompassWidth() / 2;
1912}
1913
1914int GfxCore::GetClinoXPosition() const
1915{
1916    // Return the x-coordinate of the centre of the compass in window
1917    // coordinates.
1918    return GetXSize() - GetClinoOffset() - GetClinoWidth() / 2;
1919}
1920
1921int GfxCore::GetIndicatorYPosition() const
1922{
1923    // Return the y-coordinate of the centre of the indicators in window
1924    // coordinates.
1925    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1926}
1927
1928int GfxCore::GetIndicatorRadius() const
1929{
1930    // Return the radius of each indicator.
1931    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1932}
1933
1934bool GfxCore::PointWithinCompass(wxPoint point) const
1935{
1936    // Determine whether a point (in window coordinates) lies within the
1937    // compass.
1938    if (!ShowingCompass()) return false;
1939
1940    glaCoord dx = point.x - GetCompassXPosition();
1941    glaCoord dy = point.y - GetIndicatorYPosition();
1942    glaCoord radius = GetIndicatorRadius();
1943
1944    return (dx * dx + dy * dy <= radius * radius);
1945}
1946
1947bool GfxCore::PointWithinClino(wxPoint point) const
1948{
1949    // Determine whether a point (in window coordinates) lies within the clino.
1950    if (!ShowingClino()) return false;
1951
1952    glaCoord dx = point.x - GetClinoXPosition();
1953    glaCoord dy = point.y - GetIndicatorYPosition();
1954    glaCoord radius = GetIndicatorRadius();
1955
1956    return (dx * dx + dy * dy <= radius * radius);
1957}
1958
1959bool GfxCore::PointWithinScaleBar(wxPoint point) const
1960{
1961    // Determine whether a point (in window coordinates) lies within the scale
1962    // bar.
1963    if (!ShowingScaleBar()) return false;
1964
1965    return (point.x >= SCALE_BAR_OFFSET_X &&
1966            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
1967            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1968            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
1969}
1970
1971bool GfxCore::PointWithinColourKey(wxPoint point) const
1972{
1973    // Determine whether a point (in window coordinates) lies within the key.
1974    point.x -= GetXSize() - KEY_OFFSET_X;
1975    point.y = KEY_OFFSET_Y - point.y;
1976    return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
1977            point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
1978}
1979
1980void GfxCore::SetCompassFromPoint(wxPoint point)
1981{
1982    // Given a point in window coordinates, set the heading of the survey.  If
1983    // the point is outside the compass, it snaps to 45 degree intervals;
1984    // otherwise it operates as normal.
1985
1986    wxCoord dx = point.x - GetCompassXPosition();
1987    wxCoord dy = point.y - GetIndicatorYPosition();
1988    wxCoord radius = GetIndicatorRadius();
1989
1990    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
1991    if (dx * dx + dy * dy <= radius * radius) {
1992        TurnCave(angle - m_PanAngle);
1993        m_MouseOutsideCompass = false;
1994    } else {
1995        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
1996        m_MouseOutsideCompass = true;
1997    }
1998
1999    ForceRefresh();
2000}
2001
2002void GfxCore::SetClinoFromPoint(wxPoint point)
2003{
2004    // Given a point in window coordinates, set the elevation of the survey.
2005    // If the point is outside the clino, it snaps to 90 degree intervals;
2006    // otherwise it operates as normal.
2007
2008    glaCoord dx = point.x - GetClinoXPosition();
2009    glaCoord dy = point.y - GetIndicatorYPosition();
2010    glaCoord radius = GetIndicatorRadius();
2011
2012    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
2013        TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
2014        m_MouseOutsideElev = false;
2015    } else if (dy >= INDICATOR_MARGIN) {
2016        TiltCave(-90.0 - m_TiltAngle);
2017        m_MouseOutsideElev = true;
2018    } else if (dy <= -INDICATOR_MARGIN) {
2019        TiltCave(90.0 - m_TiltAngle);
2020        m_MouseOutsideElev = true;
2021    } else {
2022        TiltCave(-m_TiltAngle);
2023        m_MouseOutsideElev = true;
2024    }
2025
2026    ForceRefresh();
2027}
2028
2029void GfxCore::SetScaleBarFromOffset(wxCoord dx)
2030{
2031    // Set the scale of the survey, given an offset as to how much the mouse has
2032    // been dragged over the scalebar since the last scale change.
2033
2034    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
2035    ForceRefresh();
2036}
2037
2038void GfxCore::RedrawIndicators()
2039{
2040    // Redraw the compass and clino indicators.
2041
2042    int total_width = GetCompassWidth() + INDICATOR_GAP + GetClinoWidth();
2043    RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - total_width,
2044                       GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
2045                       total_width,
2046                       INDICATOR_BOX_SIZE), false);
2047}
2048
2049void GfxCore::StartRotation()
2050{
2051    // Start the survey rotating.
2052
2053    if (m_SwitchingTo >= NORTH)
2054        m_SwitchingTo = 0;
2055    m_Rotating = true;
2056    SetPanBase();
2057}
2058
2059void GfxCore::ToggleRotation()
2060{
2061    // Toggle the survey rotation on/off.
2062
2063    if (m_Rotating) {
2064        StopRotation();
2065    } else {
2066        StartRotation();
2067    }
2068}
2069
2070void GfxCore::StopRotation()
2071{
2072    // Stop the survey rotating.
2073
2074    m_Rotating = false;
2075    ForceRefresh();
2076}
2077
2078bool GfxCore::IsExtendedElevation() const
2079{
2080    return m_Parent->IsExtendedElevation();
2081}
2082
2083void GfxCore::ReverseRotation()
2084{
2085    // Reverse the direction of rotation.
2086
2087    m_RotationStep = -m_RotationStep;
2088    if (m_Rotating)
2089        SetPanBase();
2090}
2091
2092void GfxCore::RotateSlower(bool accel)
2093{
2094    // Decrease the speed of rotation, optionally by an increased amount.
2095    if (fabs(m_RotationStep) == 1.0)
2096        return;
2097
2098    m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2099
2100    if (fabs(m_RotationStep) < 1.0) {
2101        m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
2102    }
2103    if (m_Rotating)
2104        SetPanBase();
2105}
2106
2107void GfxCore::RotateFaster(bool accel)
2108{
2109    // Increase the speed of rotation, optionally by an increased amount.
2110    if (fabs(m_RotationStep) == 180.0)
2111        return;
2112
2113    m_RotationStep *= accel ? 1.44 : 1.2;
2114    if (fabs(m_RotationStep) > 180.0) {
2115        m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
2116    }
2117    if (m_Rotating)
2118        SetPanBase();
2119}
2120
2121void GfxCore::SwitchToElevation()
2122{
2123    // Perform an animated switch to elevation view.
2124
2125    if (m_SwitchingTo != ELEVATION) {
2126        SetTiltBase();
2127        m_SwitchingTo = ELEVATION;
2128    } else {
2129        // A second order to switch takes us there right away
2130        TiltCave(-m_TiltAngle);
2131        m_SwitchingTo = 0;
2132        ForceRefresh();
2133    }
2134}
2135
2136void GfxCore::SwitchToPlan()
2137{
2138    // Perform an animated switch to plan view.
2139
2140    if (m_SwitchingTo != PLAN) {
2141        SetTiltBase();
2142        m_SwitchingTo = PLAN;
2143    } else {
2144        // A second order to switch takes us there right away
2145        TiltCave(-90.0 - m_TiltAngle);
2146        m_SwitchingTo = 0;
2147        ForceRefresh();
2148    }
2149}
2150
2151void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2152{
2153
2154    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
2155    Double scale = HUGE_VAL;
2156    const Vector3 ext = m_Parent->GetExtent();
2157    if (xmax > xmin) {
2158        Double s = ext.GetX() / (xmax - xmin);
2159        if (s < scale) scale = s;
2160    }
2161    if (ymax > ymin) {
2162        Double s = ext.GetY() / (ymax - ymin);
2163        if (s < scale) scale = s;
2164    }
2165    if (!ShowingPlan() && zmax > zmin) {
2166        Double s = ext.GetZ() / (zmax - zmin);
2167        if (s < scale) scale = s;
2168    }
2169    if (scale != HUGE_VAL) SetScale(scale);
2170    ForceRefresh();
2171}
2172
2173bool GfxCore::CanRaiseViewpoint() const
2174{
2175    // Determine if the survey can be viewed from a higher angle of elevation.
2176
2177    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
2178}
2179
2180bool GfxCore::CanLowerViewpoint() const
2181{
2182    // Determine if the survey can be viewed from a lower angle of elevation.
2183
2184    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
2185}
2186
2187bool GfxCore::HasDepth() const
2188{
2189    return m_Parent->GetDepthExtent() == 0.0;
2190}
2191
2192bool GfxCore::HasErrorInformation() const
2193{
2194    return m_Parent->HasErrorInformation();
2195}
2196
2197bool GfxCore::HasDateInformation() const
2198{
2199    return m_Parent->GetDateMin() >= 0;
2200}
2201
2202bool GfxCore::ShowingPlan() const
2203{
2204    // Determine if the survey is in plan view.
2205
2206    return (m_TiltAngle == -90.0);
2207}
2208
2209bool GfxCore::ShowingElevation() const
2210{
2211    // Determine if the survey is in elevation view.
2212
2213    return (m_TiltAngle == 0.0);
2214}
2215
2216bool GfxCore::ShowingMeasuringLine() const
2217{
2218    // Determine if the measuring line is being shown.  Only check if "there"
2219    // is valid, since that means the measuring line anchor is out.
2220
2221    return m_there;
2222}
2223
2224void GfxCore::ToggleFlag(bool* flag, int update)
2225{
2226    *flag = !*flag;
2227    if (update == UPDATE_BLOBS) {
2228        UpdateBlobs();
2229    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2230        UpdateBlobs();
2231        InvalidateList(LIST_CROSSES);
2232        m_HitTestGridValid = false;
2233    }
2234    ForceRefresh();
2235}
2236
2237int GfxCore::GetNumEntrances() const
2238{
2239    return m_Parent->GetNumEntrances();
2240}
2241
2242int GfxCore::GetNumFixedPts() const
2243{
2244    return m_Parent->GetNumFixedPts();
2245}
2246
2247int GfxCore::GetNumExportedPts() const
2248{
2249    return m_Parent->GetNumExportedPts();
2250}
2251
2252void GfxCore::ToggleFatFinger()
2253{
2254    if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2255        sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2256        wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2257    } else {
2258        sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2259        wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2260    }
2261}
2262
2263void GfxCore::ClearTreeSelection()
2264{
2265    m_Parent->ClearTreeSelection();
2266}
2267
2268void GfxCore::CentreOn(const Point &p)
2269{
2270    SetTranslation(-p);
2271    m_HitTestGridValid = false;
2272
2273    ForceRefresh();
2274}
2275
2276void GfxCore::ForceRefresh()
2277{
2278    Refresh(false);
2279}
2280
2281void GfxCore::GenerateList(unsigned int l)
2282{
2283    assert(m_HaveData);
2284
2285    switch (l) {
2286        case LIST_COMPASS:
2287            DrawCompass();
2288            break;
2289        case LIST_CLINO:
2290            DrawClino();
2291            break;
2292        case LIST_CLINO_BACK:
2293            DrawClinoBack();
2294            break;
2295        case LIST_SCALE_BAR:
2296            DrawScaleBar();
2297            break;
2298        case LIST_DEPTH_KEY:
2299            DrawDepthKey();
2300            break;
2301        case LIST_DATE_KEY:
2302            DrawDateKey();
2303            break;
2304        case LIST_ERROR_KEY:
2305            DrawErrorKey();
2306            break;
2307        case LIST_GRADIENT_KEY:
2308            DrawGradientKey();
2309            break;
2310        case LIST_LENGTH_KEY:
2311            DrawLengthKey();
2312            break;
2313        case LIST_UNDERGROUND_LEGS:
2314            GenerateDisplayList();
2315            break;
2316        case LIST_TUBES:
2317            GenerateDisplayListTubes();
2318            break;
2319        case LIST_SURFACE_LEGS:
2320            GenerateDisplayListSurface();
2321            break;
2322        case LIST_BLOBS:
2323            GenerateBlobsDisplayList();
2324            break;
2325        case LIST_CROSSES: {
2326            BeginCrosses();
2327            SetColour(col_LIGHT_GREY);
2328            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2329            while (pos != m_Parent->GetLabelsEnd()) {
2330                const LabelInfo* label = *pos++;
2331
2332                if ((m_Surface && label->IsSurface()) ||
2333                    (m_Legs && label->IsUnderground()) ||
2334                    (!label->IsSurface() && !label->IsUnderground())) {
2335                    // Check if this station should be displayed
2336                    // (last case is for stns with no legs attached)
2337                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2338                }
2339            }
2340            EndCrosses();
2341            break;
2342        }
2343        case LIST_GRID:
2344            DrawGrid();
2345            break;
2346        case LIST_SHADOW:
2347            GenerateDisplayListShadow();
2348            break;
2349        case LIST_TERRAIN: {
2350            static const short * bil = NULL;
2351            if (!bil) {
2352                size_t len = 25934402;
2353                int fd = open("/home/olly/git/survex/DEM/n47_e013_1arc_v3.bil", O_RDONLY);
2354                if (fd >= 0)
2355                    bil = (short*)mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
2356            }
2357            if (!bil) {
2358                break;
2359            }
2360            size_t width = 3601;
2361            size_t height = 3601;
2362            double o_x = 13, o_y = 48;
2363            double step_x = 0.0002777778;
2364            double step_y = 0.0002777778;
2365#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2366            static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2367            if (!pj_in) {
2368                fatalerror(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2369            }
2370            static projPJ pj_out = pj_init_plus(m_Parent->m_cs_proj.c_str());
2371            if (!pj_out) {
2372                fatalerror(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->m_cs_proj.c_str());
2373            }
2374            size_t n_x = 0;
2375            SetAlpha(0.3);
2376            SetColour(col_WHITE);
2377            const Vector3 & off = m_Parent->GetOffset();
2378            for (size_t x = 1800; x < width; ++x) {
2379                double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2380                bool in_line = false;
2381                for (size_t y = 0; y < height / 2; ++y) {
2382                    double Z = bil[x + y * width];
2383                    if (Z == -32767) {
2384                        if (in_line) {
2385                            EndPolyline();
2386                            in_line = false;
2387                        }
2388                        continue;
2389                    }
2390                    double X = X_;
2391                    double Y = (o_y - y * step_y) * DEG_TO_RAD;
2392                    pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2393                    X -= off.GetX();
2394                    Y -= off.GetY();
2395                    double dist_2 = sqrd(X) + sqrd(Y);
2396                    if (dist_2 < sqrd(8000.0)) {
2397                        Z -= off.GetZ();
2398                        if (!in_line) {
2399                            in_line = true;
2400                            BeginPolyline();
2401                        }
2402                        PlaceVertex(X, Y, Z);
2403                        ++n_x;
2404                    }
2405                }
2406                if (in_line) {
2407                    EndPolyline();
2408                }
2409            }
2410            SetAlpha(1.0);
2411            printf("%d DEM points drawn\n", n_x);
2412            break;
2413        }
2414        default:
2415            assert(false);
2416            break;
2417    }
2418}
2419
2420void GfxCore::ToggleSmoothShading()
2421{
2422    GLACanvas::ToggleSmoothShading();
2423    InvalidateList(LIST_TUBES);
2424    ForceRefresh();
2425}
2426
2427void GfxCore::GenerateDisplayList()
2428{
2429    // Generate the display list for the underground legs.
2430    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2431    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2432
2433    if (m_Splays == SPLAYS_SHOW_FADED) {
2434        SetAlpha(0.4);
2435        while (trav != tend) {
2436            if ((*trav).isSplay)
2437                (this->*AddPoly)(*trav);
2438            ++trav;
2439        }
2440        SetAlpha(1.0);
2441        trav = m_Parent->traverses_begin();
2442    }
2443
2444    while (trav != tend) {
2445        if (m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
2446            (this->*AddPoly)(*trav);
2447        ++trav;
2448    }
2449}
2450
2451void GfxCore::GenerateDisplayListTubes()
2452{
2453    // Generate the display list for the tubes.
2454    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2455    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2456    while (trav != tend) {
2457        SkinPassage(*trav);
2458        ++trav;
2459    }
2460}
2461
2462void GfxCore::GenerateDisplayListSurface()
2463{
2464    // Generate the display list for the surface legs.
2465    EnableDashedLines();
2466    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2467    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2468    while (trav != tend) {
2469        if (m_ColourBy == COLOUR_BY_ERROR) {
2470            AddPolylineError(*trav);
2471        } else {
2472            AddPolyline(*trav);
2473        }
2474        ++trav;
2475    }
2476    DisableDashedLines();
2477}
2478
2479void GfxCore::GenerateDisplayListShadow()
2480{
2481    SetColour(col_BLACK);
2482    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2483    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2484    while (trav != tend) {
2485        AddPolylineShadow(*trav);
2486        ++trav;
2487    }
2488}
2489
2490// Plot blobs.
2491void GfxCore::GenerateBlobsDisplayList()
2492{
2493    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2494          m_Parent->GetNumHighlightedPts()))
2495        return;
2496
2497    // Plot blobs.
2498    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2499    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2500    BeginBlobs();
2501    while (pos != m_Parent->GetLabelsEnd()) {
2502        const LabelInfo* label = *pos++;
2503
2504        // When more than one flag is set on a point:
2505        // search results take priority over entrance highlighting
2506        // which takes priority over fixed point
2507        // highlighting, which in turn takes priority over exported
2508        // point highlighting.
2509
2510        if (!((m_Surface && label->IsSurface()) ||
2511              (m_Legs && label->IsUnderground()) ||
2512              (!label->IsSurface() && !label->IsUnderground()))) {
2513            // if this station isn't to be displayed, skip to the next
2514            // (last case is for stns with no legs attached)
2515            continue;
2516        }
2517
2518        gla_colour col;
2519
2520        if (label->IsHighLighted()) {
2521            col = col_YELLOW;
2522        } else if (m_Entrances && label->IsEntrance()) {
2523            col = col_GREEN;
2524        } else if (m_FixedPts && label->IsFixedPt()) {
2525            col = col_RED;
2526        } else if (m_ExportedPts && label->IsExportedPt()) {
2527            col = col_TURQUOISE;
2528        } else {
2529            continue;
2530        }
2531
2532        // Stations are sorted by blob type, so colour changes are infrequent.
2533        if (col != prev_col) {
2534            SetColour(col);
2535            prev_col = col;
2536        }
2537        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2538    }
2539    EndBlobs();
2540}
2541
2542void GfxCore::DrawIndicators()
2543{
2544    // Draw colour key.
2545    if (m_ColourKey) {
2546        drawing_list key_list = LIST_LIMIT_;
2547        switch (m_ColourBy) {
2548            case COLOUR_BY_DEPTH:
2549                key_list = LIST_DEPTH_KEY; break;
2550            case COLOUR_BY_DATE:
2551                key_list = LIST_DATE_KEY; break;
2552            case COLOUR_BY_ERROR:
2553                key_list = LIST_ERROR_KEY; break;
2554            case COLOUR_BY_GRADIENT:
2555                key_list = LIST_GRADIENT_KEY; break;
2556            case COLOUR_BY_LENGTH:
2557                key_list = LIST_LENGTH_KEY; break;
2558        }
2559        if (key_list != LIST_LIMIT_) {
2560            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
2561                       GetYSize() - KEY_OFFSET_Y, 0);
2562        }
2563    }
2564
2565    // Draw compass or elevation/heading indicators.
2566    if (m_Compass || m_Clino) {
2567        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2568    }
2569
2570    // Draw scalebar.
2571    if (m_Scalebar) {
2572        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2573    }
2574}
2575
2576void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2577                                    glaTexCoord tex_x, glaTexCoord tex_y,
2578                                    Double factor)
2579{
2580    SetColour(col_WHITE, factor);
2581    PlaceVertex(v, tex_x, tex_y);
2582}
2583
2584void GfxCore::SetDepthColour(Double z, Double factor) {
2585    // Set the drawing colour based on the altitude.
2586    Double z_ext = m_Parent->GetDepthExtent();
2587
2588    z -= m_Parent->GetDepthMin();
2589    // points arising from tubes may be slightly outside the limits...
2590    if (z < 0) z = 0;
2591    if (z > z_ext) z = z_ext;
2592
2593    if (z == 0) {
2594        SetColour(GetPen(0), factor);
2595        return;
2596    }
2597
2598    assert(z_ext > 0.0);
2599    Double how_far = z / z_ext;
2600    assert(how_far >= 0.0);
2601    assert(how_far <= 1.0);
2602
2603    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2604    GLAPen pen1 = GetPen(band);
2605    if (band < GetNumColourBands() - 1) {
2606        const GLAPen& pen2 = GetPen(band + 1);
2607
2608        Double interval = z_ext / (GetNumColourBands() - 1);
2609        Double into_band = z / interval - band;
2610
2611//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2612//             z_offset, interval, band);
2613        // FIXME: why do we need to clamp here?  Is it because the walls can
2614        // extend further up/down than the centre-line?
2615        if (into_band < 0.0) into_band = 0.0;
2616        if (into_band > 1.0) into_band = 1.0;
2617        assert(into_band >= 0.0);
2618        assert(into_band <= 1.0);
2619
2620        pen1.Interpolate(pen2, into_band);
2621    }
2622    SetColour(pen1, factor);
2623}
2624
2625void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2626{
2627    SetDepthColour(v.GetZ(), factor);
2628    PlaceVertex(v);
2629}
2630
2631void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2632                                         glaTexCoord tex_x, glaTexCoord tex_y,
2633                                         Double factor)
2634{
2635    SetDepthColour(v.GetZ(), factor);
2636    PlaceVertex(v, tex_x, tex_y);
2637}
2638
2639void GfxCore::SplitLineAcrossBands(int band, int band2,
2640                                   const Vector3 &p, const Vector3 &q,
2641                                   Double factor)
2642{
2643    const int step = (band < band2) ? 1 : -1;
2644    for (int i = band; i != band2; i += step) {
2645        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2646
2647        // Find the intersection point of the line p -> q
2648        // with the plane parallel to the xy-plane with z-axis intersection z.
2649        assert(q.GetZ() - p.GetZ() != 0.0);
2650
2651        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2652//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2653
2654        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2655        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2656
2657        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2658    }
2659}
2660
2661int GfxCore::GetDepthColour(Double z) const
2662{
2663    // Return the (0-based) depth colour band index for a z-coordinate.
2664    Double z_ext = m_Parent->GetDepthExtent();
2665    z -= m_Parent->GetDepthMin();
2666    // We seem to get rounding differences causing z to sometimes be slightly
2667    // less than GetDepthMin() here, and it can certainly be true for passage
2668    // tubes, so just clamp the value to 0.
2669    if (z <= 0) return 0;
2670    // We seem to get rounding differences causing z to sometimes exceed z_ext
2671    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2672    // can certainly be true for passage tubes, so just clamp the value.
2673    if (z >= z_ext) return GetNumColourBands() - 1;
2674    return int(z / z_ext * (GetNumColourBands() - 1));
2675}
2676
2677Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2678{
2679    // Return the z-coordinate of the depth colour boundary between
2680    // two adjacent depth colour bands (specified by 0-based indices).
2681
2682    assert((a == b - 1) || (a == b + 1));
2683    if (GetNumColourBands() == 1) return 0;
2684
2685    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2686    Double z_ext = m_Parent->GetDepthExtent();
2687    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
2688}
2689
2690void GfxCore::AddPolyline(const traverse & centreline)
2691{
2692    BeginPolyline();
2693    SetColour(col_WHITE);
2694    vector<PointInfo>::const_iterator i = centreline.begin();
2695    PlaceVertex(*i);
2696    ++i;
2697    while (i != centreline.end()) {
2698        PlaceVertex(*i);
2699        ++i;
2700    }
2701    EndPolyline();
2702}
2703
2704void GfxCore::AddPolylineShadow(const traverse & centreline)
2705{
2706    BeginPolyline();
2707    const double z = -0.5 * m_Parent->GetZExtent();
2708    vector<PointInfo>::const_iterator i = centreline.begin();
2709    PlaceVertex(i->GetX(), i->GetY(), z);
2710    ++i;
2711    while (i != centreline.end()) {
2712        PlaceVertex(i->GetX(), i->GetY(), z);
2713        ++i;
2714    }
2715    EndPolyline();
2716}
2717
2718void GfxCore::AddPolylineDepth(const traverse & centreline)
2719{
2720    BeginPolyline();
2721    vector<PointInfo>::const_iterator i, prev_i;
2722    i = centreline.begin();
2723    int band0 = GetDepthColour(i->GetZ());
2724    PlaceVertexWithDepthColour(*i);
2725    prev_i = i;
2726    ++i;
2727    while (i != centreline.end()) {
2728        int band = GetDepthColour(i->GetZ());
2729        if (band != band0) {
2730            SplitLineAcrossBands(band0, band, *prev_i, *i);
2731            band0 = band;
2732        }
2733        PlaceVertexWithDepthColour(*i);
2734        prev_i = i;
2735        ++i;
2736    }
2737    EndPolyline();
2738}
2739
2740void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
2741                               const Vector3 &c, const Vector3 &d)
2742{
2743    Vector3 normal = (a - c) * (d - b);
2744    normal.normalise();
2745    Double factor = dot(normal, light) * .3 + .7;
2746    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2747    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2748    // FIXME: should plot triangles instead to avoid rendering glitches.
2749    BeginQuadrilaterals();
2750    PlaceVertexWithColour(a, 0, 0, factor);
2751    PlaceVertexWithColour(b, w, 0, factor);
2752    PlaceVertexWithColour(c, w, h, factor);
2753    PlaceVertexWithColour(d, 0, h, factor);
2754    EndQuadrilaterals();
2755}
2756
2757void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2758                                    const Vector3 &c, const Vector3 &d)
2759{
2760    Vector3 normal = (a - c) * (d - b);
2761    normal.normalise();
2762    Double factor = dot(normal, light) * .3 + .7;
2763    int a_band, b_band, c_band, d_band;
2764    a_band = GetDepthColour(a.GetZ());
2765    a_band = min(max(a_band, 0), GetNumColourBands());
2766    b_band = GetDepthColour(b.GetZ());
2767    b_band = min(max(b_band, 0), GetNumColourBands());
2768    c_band = GetDepthColour(c.GetZ());
2769    c_band = min(max(c_band, 0), GetNumColourBands());
2770    d_band = GetDepthColour(d.GetZ());
2771    d_band = min(max(d_band, 0), GetNumColourBands());
2772    // All this splitting is incorrect - we need to make a separate polygon
2773    // for each depth band...
2774    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2775    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2776    BeginPolygon();
2777////    PlaceNormal(normal);
2778    PlaceVertexWithDepthColour(a, 0, 0, factor);
2779    if (a_band != b_band) {
2780        SplitLineAcrossBands(a_band, b_band, a, b, factor);
2781    }
2782    PlaceVertexWithDepthColour(b, w, 0, factor);
2783    if (b_band != c_band) {
2784        SplitLineAcrossBands(b_band, c_band, b, c, factor);
2785    }
2786    PlaceVertexWithDepthColour(c, w, h, factor);
2787    if (c_band != d_band) {
2788        SplitLineAcrossBands(c_band, d_band, c, d, factor);
2789    }
2790    PlaceVertexWithDepthColour(d, 0, h, factor);
2791    if (d_band != a_band) {
2792        SplitLineAcrossBands(d_band, a_band, d, a, factor);
2793    }
2794    EndPolygon();
2795}
2796
2797void GfxCore::SetColourFromDate(int date, Double factor)
2798{
2799    // Set the drawing colour based on a date.
2800
2801    if (date == -1) {
2802        // Undated.
2803        SetColour(col_WHITE, factor);
2804        return;
2805    }
2806
2807    int date_offset = date - m_Parent->GetDateMin();
2808    if (date_offset == 0) {
2809        // Earliest date - handle as a special case for the single date case.
2810        SetColour(GetPen(0), factor);
2811        return;
2812    }
2813
2814    int date_ext = m_Parent->GetDateExtent();
2815    Double how_far = (Double)date_offset / date_ext;
2816    assert(how_far >= 0.0);
2817    assert(how_far <= 1.0);
2818    SetColourFrom01(how_far, factor);
2819}
2820
2821void GfxCore::AddPolylineDate(const traverse & centreline)
2822{
2823    BeginPolyline();
2824    vector<PointInfo>::const_iterator i, prev_i;
2825    i = centreline.begin();
2826    int date = i->GetDate();
2827    SetColourFromDate(date, 1.0);
2828    PlaceVertex(*i);
2829    prev_i = i;
2830    while (++i != centreline.end()) {
2831        int newdate = i->GetDate();
2832        if (newdate != date) {
2833            EndPolyline();
2834            BeginPolyline();
2835            date = newdate;
2836            SetColourFromDate(date, 1.0);
2837            PlaceVertex(*prev_i);
2838        }
2839        PlaceVertex(*i);
2840        prev_i = i;
2841    }
2842    EndPolyline();
2843}
2844
2845static int static_date_hack; // FIXME
2846
2847void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2848                                   const Vector3 &c, const Vector3 &d)
2849{
2850    Vector3 normal = (a - c) * (d - b);
2851    normal.normalise();
2852    Double factor = dot(normal, light) * .3 + .7;
2853    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2854    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2855    // FIXME: should plot triangles instead to avoid rendering glitches.
2856    BeginQuadrilaterals();
2857////    PlaceNormal(normal);
2858    SetColourFromDate(static_date_hack, factor);
2859    PlaceVertex(a, 0, 0);
2860    PlaceVertex(b, w, 0);
2861    PlaceVertex(c, w, h);
2862    PlaceVertex(d, 0, h);
2863    EndQuadrilaterals();
2864}
2865
2866static double static_E_hack; // FIXME
2867
2868void GfxCore::SetColourFromError(double E, Double factor)
2869{
2870    // Set the drawing colour based on an error value.
2871
2872    if (E < 0) {
2873        SetColour(col_WHITE, factor);
2874        return;
2875    }
2876
2877    Double how_far = E / MAX_ERROR;
2878    assert(how_far >= 0.0);
2879    if (how_far > 1.0) how_far = 1.0;
2880    SetColourFrom01(how_far, factor);
2881}
2882
2883void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2884                                    const Vector3 &c, const Vector3 &d)
2885{
2886    Vector3 normal = (a - c) * (d - b);
2887    normal.normalise();
2888    Double factor = dot(normal, light) * .3 + .7;
2889    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2890    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2891    // FIXME: should plot triangles instead to avoid rendering glitches.
2892    BeginQuadrilaterals();
2893////    PlaceNormal(normal);
2894    SetColourFromError(static_E_hack, factor);
2895    PlaceVertex(a, 0, 0);
2896    PlaceVertex(b, w, 0);
2897    PlaceVertex(c, w, h);
2898    PlaceVertex(d, 0, h);
2899    EndQuadrilaterals();
2900}
2901
2902void GfxCore::AddPolylineError(const traverse & centreline)
2903{
2904    BeginPolyline();
2905    SetColourFromError(centreline.E, 1.0);
2906    vector<PointInfo>::const_iterator i;
2907    for(i = centreline.begin(); i != centreline.end(); ++i) {
2908        PlaceVertex(*i);
2909    }
2910    EndPolyline();
2911}
2912
2913// gradient is in *radians*.
2914void GfxCore::SetColourFromGradient(double gradient, Double factor)
2915{
2916    // Set the drawing colour based on the gradient of the leg.
2917
2918    const Double GRADIENT_MAX = M_PI_2;
2919    gradient = fabs(gradient);
2920    Double how_far = gradient / GRADIENT_MAX;
2921    SetColourFrom01(how_far, factor);
2922}
2923
2924void GfxCore::AddPolylineGradient(const traverse & centreline)
2925{
2926    vector<PointInfo>::const_iterator i, prev_i;
2927    i = centreline.begin();
2928    prev_i = i;
2929    while (++i != centreline.end()) {
2930        BeginPolyline();
2931        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
2932        PlaceVertex(*prev_i);
2933        PlaceVertex(*i);
2934        prev_i = i;
2935        EndPolyline();
2936    }
2937}
2938
2939static double static_gradient_hack; // FIXME
2940
2941void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
2942                                       const Vector3 &c, const Vector3 &d)
2943{
2944    Vector3 normal = (a - c) * (d - b);
2945    normal.normalise();
2946    Double factor = dot(normal, light) * .3 + .7;
2947    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2948    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2949    // FIXME: should plot triangles instead to avoid rendering glitches.
2950    BeginQuadrilaterals();
2951////    PlaceNormal(normal);
2952    SetColourFromGradient(static_gradient_hack, factor);
2953    PlaceVertex(a, 0, 0);
2954    PlaceVertex(b, w, 0);
2955    PlaceVertex(c, w, h);
2956    PlaceVertex(d, 0, h);
2957    EndQuadrilaterals();
2958}
2959
2960void GfxCore::SetColourFromLength(double length, Double factor)
2961{
2962    // Set the drawing colour based on log(length_of_leg).
2963
2964    Double log_len = log10(length);
2965    Double how_far = log_len / LOG_LEN_MAX;
2966    how_far = max(how_far, 0.0);
2967    how_far = min(how_far, 1.0);
2968    SetColourFrom01(how_far, factor);
2969}
2970
2971void GfxCore::SetColourFrom01(double how_far, Double factor)
2972{
2973    double b;
2974    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
2975    int band(b);
2976    GLAPen pen1 = GetPen(band);
2977    // With 24bit colour, interpolating by less than this can have no effect.
2978    if (into_band >= 1.0 / 512.0) {
2979        const GLAPen& pen2 = GetPen(band + 1);
2980        pen1.Interpolate(pen2, into_band);
2981    }
2982    SetColour(pen1, factor);
2983}
2984
2985void GfxCore::AddPolylineLength(const traverse & centreline)
2986{
2987    vector<PointInfo>::const_iterator i, prev_i;
2988    i = centreline.begin();
2989    prev_i = i;
2990    while (++i != centreline.end()) {
2991        BeginPolyline();
2992        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
2993        PlaceVertex(*prev_i);
2994        PlaceVertex(*i);
2995        prev_i = i;
2996        EndPolyline();
2997    }
2998}
2999
3000static double static_length_hack; // FIXME
3001
3002void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3003                                     const Vector3 &c, const Vector3 &d)
3004{
3005    Vector3 normal = (a - c) * (d - b);
3006    normal.normalise();
3007    Double factor = dot(normal, light) * .3 + .7;
3008    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3009    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3010    // FIXME: should plot triangles instead to avoid rendering glitches.
3011    BeginQuadrilaterals();
3012////    PlaceNormal(normal);
3013    SetColourFromLength(static_length_hack, factor);
3014    PlaceVertex(a, 0, 0);
3015    PlaceVertex(b, w, 0);
3016    PlaceVertex(c, w, h);
3017    PlaceVertex(d, 0, h);
3018    EndQuadrilaterals();
3019}
3020
3021void
3022GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3023{
3024    assert(centreline.size() > 1);
3025    Vector3 U[4];
3026    XSect prev_pt_v;
3027    Vector3 last_right(1.0, 0.0, 0.0);
3028
3029//  FIXME: it's not simple to set the colour of a tube based on error...
3030//    static_E_hack = something...
3031    vector<XSect>::iterator i = centreline.begin();
3032    vector<XSect>::size_type segment = 0;
3033    while (i != centreline.end()) {
3034        // get the coordinates of this vertex
3035        XSect & pt_v = *i++;
3036
3037        double z_pitch_adjust = 0.0;
3038        bool cover_end = false;
3039
3040        Vector3 right, up;
3041
3042        const Vector3 up_v(0.0, 0.0, 1.0);
3043
3044        if (segment == 0) {
3045            assert(i != centreline.end());
3046            // first segment
3047
3048            // get the coordinates of the next vertex
3049            const XSect & next_pt_v = *i;
3050
3051            // calculate vector from this pt to the next one
3052            Vector3 leg_v = next_pt_v - pt_v;
3053
3054            // obtain a vector in the LRUD plane
3055            right = leg_v * up_v;
3056            if (right.magnitude() == 0) {
3057                right = last_right;
3058                // Obtain a second vector in the LRUD plane,
3059                // perpendicular to the first.
3060                //up = right * leg_v;
3061                up = up_v;
3062            } else {
3063                last_right = right;
3064                up = up_v;
3065            }
3066
3067            cover_end = true;
3068            static_date_hack = next_pt_v.GetDate();
3069        } else if (segment + 1 == centreline.size()) {
3070            // last segment
3071
3072            // Calculate vector from the previous pt to this one.
3073            Vector3 leg_v = pt_v - prev_pt_v;
3074
3075            // Obtain a horizontal vector in the LRUD plane.
3076            right = leg_v * up_v;
3077            if (right.magnitude() == 0) {
3078                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3079                // Obtain a second vector in the LRUD plane,
3080                // perpendicular to the first.
3081                //up = right * leg_v;
3082                up = up_v;
3083            } else {
3084                last_right = right;
3085                up = up_v;
3086            }
3087
3088            cover_end = true;
3089            static_date_hack = pt_v.GetDate();
3090        } else {
3091            assert(i != centreline.end());
3092            // Intermediate segment.
3093
3094            // Get the coordinates of the next vertex.
3095            const XSect & next_pt_v = *i;
3096
3097            // Calculate vectors from this vertex to the
3098            // next vertex, and from the previous vertex to
3099            // this one.
3100            Vector3 leg1_v = pt_v - prev_pt_v;
3101            Vector3 leg2_v = next_pt_v - pt_v;
3102
3103            // Obtain horizontal vectors perpendicular to
3104            // both legs, then normalise and average to get
3105            // a horizontal bisector.
3106            Vector3 r1 = leg1_v * up_v;
3107            Vector3 r2 = leg2_v * up_v;
3108            r1.normalise();
3109            r2.normalise();
3110            right = r1 + r2;
3111            if (right.magnitude() == 0) {
3112                // This is the "mid-pitch" case...
3113                right = last_right;
3114            }
3115            if (r1.magnitude() == 0) {
3116                Vector3 n = leg1_v;
3117                n.normalise();
3118                z_pitch_adjust = n.GetZ();
3119                //up = Vector3(0, 0, leg1_v.GetZ());
3120                //up = right * up;
3121                up = up_v;
3122
3123                // Rotate pitch section to minimise the
3124                // "tortional stress" - FIXME: use
3125                // triangles instead of rectangles?
3126                int shift = 0;
3127                Double maxdotp = 0;
3128
3129                // Scale to unit vectors in the LRUD plane.
3130                right.normalise();
3131                up.normalise();
3132                Vector3 vec = up - right;
3133                for (int orient = 0; orient <= 3; ++orient) {
3134                    Vector3 tmp = U[orient] - prev_pt_v;
3135                    tmp.normalise();
3136                    Double dotp = dot(vec, tmp);
3137                    if (dotp > maxdotp) {
3138                        maxdotp = dotp;
3139                        shift = orient;
3140                    }
3141                }
3142                if (shift) {
3143                    if (shift != 2) {
3144                        Vector3 temp(U[0]);
3145                        U[0] = U[shift];
3146                        U[shift] = U[2];
3147                        U[2] = U[shift ^ 2];
3148                        U[shift ^ 2] = temp;
3149                    } else {
3150                        swap(U[0], U[2]);
3151                        swap(U[1], U[3]);
3152                    }
3153                }
3154#if 0
3155                // Check that the above code actually permuted
3156                // the vertices correctly.
3157                shift = 0;
3158                maxdotp = 0;
3159                for (int j = 0; j <= 3; ++j) {
3160                    Vector3 tmp = U[j] - prev_pt_v;
3161                    tmp.normalise();
3162                    Double dotp = dot(vec, tmp);
3163                    if (dotp > maxdotp) {
3164                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3165                        shift = j;
3166                    }
3167                }
3168                if (shift) {
3169                    printf("New shift = %d!\n", shift);
3170                    shift = 0;
3171                    maxdotp = 0;
3172                    for (int j = 0; j <= 3; ++j) {
3173                        Vector3 tmp = U[j] - prev_pt_v;
3174                        tmp.normalise();
3175                        Double dotp = dot(vec, tmp);
3176                        printf("    %d : %.8f\n", j, dotp);
3177                    }
3178                }
3179#endif
3180            } else if (r2.magnitude() == 0) {
3181                Vector3 n = leg2_v;
3182                n.normalise();
3183                z_pitch_adjust = n.GetZ();
3184                //up = Vector3(0, 0, leg2_v.GetZ());
3185                //up = right * up;
3186                up = up_v;
3187            } else {
3188                up = up_v;
3189            }
3190            last_right = right;
3191            static_date_hack = pt_v.GetDate();
3192        }
3193
3194        // Scale to unit vectors in the LRUD plane.
3195        right.normalise();
3196        up.normalise();
3197
3198        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
3199
3200        Double l = fabs(pt_v.GetL());
3201        Double r = fabs(pt_v.GetR());
3202        Double u = fabs(pt_v.GetU());
3203        Double d = fabs(pt_v.GetD());
3204
3205        // Produce coordinates of the corners of the LRUD "plane".
3206        Vector3 v[4];
3207        v[0] = pt_v - right * l + up * u;
3208        v[1] = pt_v + right * r + up * u;
3209        v[2] = pt_v + right * r - up * d;
3210        v[3] = pt_v - right * l - up * d;
3211
3212        if (draw) {
3213            const Vector3 & delta = pt_v - prev_pt_v;
3214            static_length_hack = delta.magnitude();
3215            static_gradient_hack = delta.gradient();
3216            if (segment > 0) {
3217                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3218                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3219                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3220                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3221            }
3222
3223            if (cover_end) {
3224                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3225            }
3226        }
3227
3228        prev_pt_v = pt_v;
3229        U[0] = v[0];
3230        U[1] = v[1];
3231        U[2] = v[2];
3232        U[3] = v[3];
3233
3234        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3235
3236        ++segment;
3237    }
3238}
3239
3240void GfxCore::FullScreenMode()
3241{
3242    m_Parent->ViewFullScreen();
3243}
3244
3245bool GfxCore::IsFullScreen() const
3246{
3247    return m_Parent->IsFullScreen();
3248}
3249
3250bool GfxCore::FullScreenModeShowingMenus() const
3251{
3252    return m_Parent->FullScreenModeShowingMenus();
3253}
3254
3255void GfxCore::FullScreenModeShowMenus(bool show)
3256{
3257    m_Parent->FullScreenModeShowMenus(show);
3258}
3259
3260void
3261GfxCore::MoveViewer(double forward, double up, double right)
3262{
3263    double cT = cos(rad(m_TiltAngle));
3264    double sT = sin(rad(m_TiltAngle));
3265    double cP = cos(rad(m_PanAngle));
3266    double sP = sin(rad(m_PanAngle));
3267    Vector3 v_forward(cT * sP, cT * cP, sT);
3268    Vector3 v_up(sT * sP, sT * cP, -cT);
3269    Vector3 v_right(-cP, sP, 0);
3270    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3271    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3272    assert(fabs(dot(v_right, v_up)) < 1e-6);
3273    Vector3 move = v_forward * forward + v_up * up + v_right * right;
3274    AddTranslation(-move);
3275    // Show current position.
3276    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3277    ForceRefresh();
3278}
3279
3280PresentationMark GfxCore::GetView() const
3281{
3282    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3283                            m_PanAngle, -m_TiltAngle, m_Scale);
3284}
3285
3286void GfxCore::SetView(const PresentationMark & p)
3287{
3288    m_SwitchingTo = 0;
3289    SetTranslation(p - m_Parent->GetOffset());
3290    m_PanAngle = p.angle;
3291    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3292    SetRotation(m_PanAngle, m_TiltAngle);
3293    SetScale(p.scale);
3294    ForceRefresh();
3295}
3296
3297void GfxCore::PlayPres(double speed, bool change_speed) {
3298    if (!change_speed || presentation_mode == 0) {
3299        if (speed == 0.0) {
3300            presentation_mode = 0;
3301            return;
3302        }
3303        presentation_mode = PLAYING;
3304        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3305        SetView(next_mark);
3306        next_mark_time = 0; // There already!
3307        this_mark_total = 0;
3308        pres_reverse = (speed < 0);
3309    }
3310
3311    if (change_speed) pres_speed = speed;
3312
3313    if (speed != 0.0) {
3314        bool new_pres_reverse = (speed < 0);
3315        if (new_pres_reverse != pres_reverse) {
3316            pres_reverse = new_pres_reverse;
3317            if (pres_reverse) {
3318                next_mark = m_Parent->GetPresMark(MARK_PREV);
3319            } else {
3320                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3321            }
3322            swap(this_mark_total, next_mark_time);
3323        }
3324    }
3325}
3326
3327void GfxCore::SetColourBy(int colour_by) {
3328    m_ColourBy = colour_by;
3329    switch (colour_by) {
3330        case COLOUR_BY_DEPTH:
3331            AddQuad = &GfxCore::AddQuadrilateralDepth;
3332            AddPoly = &GfxCore::AddPolylineDepth;
3333            break;
3334        case COLOUR_BY_DATE:
3335            AddQuad = &GfxCore::AddQuadrilateralDate;
3336            AddPoly = &GfxCore::AddPolylineDate;
3337            break;
3338        case COLOUR_BY_ERROR:
3339            AddQuad = &GfxCore::AddQuadrilateralError;
3340            AddPoly = &GfxCore::AddPolylineError;
3341            break;
3342        case COLOUR_BY_GRADIENT:
3343            AddQuad = &GfxCore::AddQuadrilateralGradient;
3344            AddPoly = &GfxCore::AddPolylineGradient;
3345            break;
3346        case COLOUR_BY_LENGTH:
3347            AddQuad = &GfxCore::AddQuadrilateralLength;
3348            AddPoly = &GfxCore::AddPolylineLength;
3349            break;
3350        default: // case COLOUR_BY_NONE:
3351            AddQuad = &GfxCore::AddQuadrilateral;
3352            AddPoly = &GfxCore::AddPolyline;
3353            break;
3354    }
3355
3356    InvalidateList(LIST_UNDERGROUND_LEGS);
3357    InvalidateList(LIST_SURFACE_LEGS);
3358    InvalidateList(LIST_TUBES);
3359
3360    ForceRefresh();
3361}
3362
3363bool GfxCore::ExportMovie(const wxString & fnm)
3364{
3365    int width;
3366    int height;
3367    GetSize(&width, &height);
3368    // Round up to next multiple of 2 (required by ffmpeg).
3369    width += (width & 1);
3370    height += (height & 1);
3371
3372    movie = new MovieMaker();
3373
3374    // FIXME: This should really use fn_str() - currently we probably can't
3375    // save to a Unicode path on wxmsw.
3376    if (!movie->Open(fnm.mb_str(), width, height)) {
3377        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3378        delete movie;
3379        movie = NULL;
3380        return false;
3381    }
3382
3383    PlayPres(1);
3384    return true;
3385}
3386
3387void
3388GfxCore::OnPrint(const wxString &filename, const wxString &title,
3389                 const wxString &datestamp, time_t datestamp_numeric,
3390                 const wxString &cs_proj,
3391                 bool close_after_print)
3392{
3393    svxPrintDlg * p;
3394    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3395                        datestamp, datestamp_numeric,
3396                        m_PanAngle, m_TiltAngle,
3397                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3398                        m_Entrances, m_FixedPts, m_ExportedPts,
3399                        true, close_after_print);
3400    p->Show(true);
3401}
3402
3403void
3404GfxCore::OnExport(const wxString &filename, const wxString &title,
3405                  const wxString &datestamp, time_t datestamp_numeric,
3406                  const wxString &cs_proj)
3407{
3408    // Fill in "right_bearing" for each cross-section.
3409    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3410    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3411    while (trav != tend) {
3412        SkinPassage(*trav, false);
3413        ++trav;
3414    }
3415
3416    svxPrintDlg * p;
3417    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3418                        datestamp, datestamp_numeric,
3419                        m_PanAngle, m_TiltAngle,
3420                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3421                        m_Entrances, m_FixedPts, m_ExportedPts,
3422                        false);
3423    p->Show(true);
3424}
3425
3426static wxCursor
3427make_cursor(const unsigned char * bits, const unsigned char * mask,
3428            int hotx, int hoty)
3429{
3430#if defined __WXMSW__ || defined __WXMAC__
3431# ifdef __WXMAC__
3432    // The default Mac cursor is black with a white edge, so
3433    // invert our custom cursors to match.
3434    char b[128];
3435    for (int i = 0; i < 128; ++i)
3436        b[i] = bits[i] ^ 0xff;
3437# else
3438    const char * b = reinterpret_cast<const char *>(bits);
3439# endif
3440    wxBitmap cursor_bitmap(b, 32, 32);
3441    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3442    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3443    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3444    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3445    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3446    return wxCursor(cursor_image);
3447#else
3448    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3449                    (const char *)mask, wxBLACK, wxWHITE);
3450#endif
3451}
3452
3453const
3454#include "hand.xbm"
3455const
3456#include "handmask.xbm"
3457
3458const
3459#include "brotate.xbm"
3460const
3461#include "brotatemask.xbm"
3462
3463const
3464#include "vrotate.xbm"
3465const
3466#include "vrotatemask.xbm"
3467
3468const
3469#include "rotate.xbm"
3470const
3471#include "rotatemask.xbm"
3472
3473const
3474#include "rotatezoom.xbm"
3475const
3476#include "rotatezoommask.xbm"
3477
3478void
3479GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
3480{
3481    // Check if we're already showing that cursor.
3482    if (current_cursor == new_cursor) return;
3483
3484    current_cursor = new_cursor;
3485    switch (current_cursor) {
3486        case GfxCore::CURSOR_DEFAULT:
3487            GLACanvas::SetCursor(wxNullCursor);
3488            break;
3489        case GfxCore::CURSOR_POINTING_HAND:
3490            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3491            break;
3492        case GfxCore::CURSOR_DRAGGING_HAND:
3493            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3494            break;
3495        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3496            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3497            break;
3498        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3499            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3500            break;
3501        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3502            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3503            break;
3504        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3505            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3506            break;
3507        case GfxCore::CURSOR_ZOOM:
3508            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3509            break;
3510        case GfxCore::CURSOR_ZOOM_ROTATE:
3511            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3512            break;
3513    }
3514}
3515
3516bool GfxCore::MeasuringLineActive() const
3517{
3518    if (Animating()) return false;
3519    return HereIsReal() || m_there;
3520}
3521
3522bool GfxCore::HandleRClick(wxPoint point)
3523{
3524    if (PointWithinCompass(point)) {
3525        // Pop up menu.
3526        wxMenu menu;
3527        /* TRANSLATORS: View *looking* North */
3528        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3529        /* TRANSLATORS: View *looking* East */
3530        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3531        /* TRANSLATORS: View *looking* South */
3532        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3533        /* TRANSLATORS: View *looking* West */
3534        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3535        menu.AppendSeparator();
3536        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
3537        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
3538        /* TRANSLATORS: tickable menu item in View menu.
3539         *
3540         * Degrees are the angular measurement where there are 360 in a full
3541         * circle. */
3542        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3543        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3544        PopupMenu(&menu);
3545        return true;
3546    }
3547
3548    if (PointWithinClino(point)) {
3549        // Pop up menu.
3550        wxMenu menu;
3551        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3552        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3553        menu.AppendSeparator();
3554        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
3555        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3556        /* TRANSLATORS: tickable menu item in View menu.
3557         *
3558         * Degrees are the angular measurement where there are 360 in a full
3559         * circle. */
3560        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3561        /* TRANSLATORS: tickable menu item in View menu.
3562         *
3563         * Show the tilt of the survey as a percentage gradient (100% = 45
3564         * degrees = 50 grad). */
3565        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
3566        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3567        PopupMenu(&menu);
3568        return true;
3569    }
3570
3571    if (PointWithinScaleBar(point)) {
3572        // Pop up menu.
3573        wxMenu menu;
3574        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
3575        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3576        /* TRANSLATORS: tickable menu item in View menu.
3577         *
3578         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3579         */
3580        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3581        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3582        PopupMenu(&menu);
3583        return true;
3584    }
3585
3586    if (PointWithinColourKey(point)) {
3587        // Pop up menu.
3588        wxMenu menu;
3589        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3590        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3591        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
3592        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_GRADIENT, wmsg(/*Colour by Grad&ient*/85));
3593        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
3594        menu.AppendSeparator();
3595        /* TRANSLATORS: Menu item which turns off the colour key.
3596         * The "Colour Key" is the thing in aven showing which colour
3597         * corresponds to which depth, date, survey closure error, etc. */
3598        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3599        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
3600            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3601        else if (m_ColourBy == COLOUR_BY_GRADIENT)
3602            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3603        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3604        PopupMenu(&menu);
3605        return true;
3606    }
3607
3608    return false;
3609}
3610
3611void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3612{
3613    if (centred) {
3614        p1.x = p2.x + (p1.x - p2.x) * 2;
3615        p1.y = p2.y + (p1.y - p2.y) * 2;
3616    }
3617    if (aspect) {
3618#if 0 // FIXME: This needs more work.
3619        int sx = GetXSize();
3620        int sy = GetYSize();
3621        int dx = p1.x - p2.x;
3622        int dy = p1.y - p2.y;
3623        int dy_new = dx * sy / sx;
3624        if (abs(dy_new) >= abs(dy)) {
3625            p1.y += (dy_new - dy) / 2;
3626            p2.y -= (dy_new - dy) / 2;
3627        } else {
3628            int dx_new = dy * sx / sy;
3629            p1.x += (dx_new - dx) / 2;
3630            p2.x -= (dx_new - dx) / 2;
3631        }
3632#endif
3633    }
3634    zoombox.set(p1, p2);
3635    ForceRefresh();
3636}
3637
3638void GfxCore::ZoomBoxGo()
3639{
3640    if (!zoombox.active()) return;
3641
3642    int width = GetXSize();
3643    int height = GetYSize();
3644
3645    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
3646                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
3647    int box_w = abs(zoombox.x1 - zoombox.x2);
3648    int box_h = abs(zoombox.y1 - zoombox.y2);
3649
3650    double factor = min(double(width) / box_w, double(height) / box_h);
3651
3652    zoombox.unset();
3653
3654    SetScale(GetScale() * factor);
3655}
Note: See TracBrowser for help on using the repository browser.