source: git/src/gfxcore.cc @ 1a381ae

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

Fix handling of non-square DEM files

The X and Y dimensions were swapped. Reported by detrito.

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