source: git/src/gfxcore.cc @ fc43dda

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

Allow colouring by horizontal or vertical error

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