source: git/src/gfxcore.cc @ 672459c

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

Hook up multi-select in survey tree

Filtering works for everthing except exporting.

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