source: git/src/gfxcore.cc @ ea94dd64

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernlogstereowalls-datawalls-data-hanging-as-warning
Last change on this file since ea94dd64 was cc9e2c65, checked in by Olly Betts <olly@…>, 9 years ago

lib/,src/: Add "Colour by Gradient".

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