source: git/src/gfxcore.cc @ bf7baeb

RELEASE/1.2debug-cidebug-ci-sanitiserswalls-data
Last change on this file since bf7baeb was 8719711, checked in by Olly Betts <olly@…>, 5 years ago

Support PROJ 5.x

PROJ 6.x won't work yet. See https://trac.survex.com/ticket/102 for
details.

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