source: git/src/gfxcore.cc @ 398956b

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernlogwalls-datawalls-data-hanging-as-warning
Last change on this file since 398956b was 0642381, checked in by Olly Betts <olly@…>, 6 years ago

Highlight surveys on survey tree mouseover

This is cleaner than running a search to highlight them, and means
we can restore "double-click survey in tree to zoom".

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