source: git/src/gfxcore.cc @ 8fc6473

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

src/gfxcore.cc: Fix the orientation of the starting end of tubes.

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