source: git/src/gfxcore.cc @ 938fee8

stereo
Last change on this file since 938fee8 was 938fee8, checked in by Olly Betts <olly@…>, 6 years ago

Fix to work with stereo buffers

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