source: git/src/gfxcore.cc @ 46a9883

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

survexport: Fix exporting of passages and xsects

We now run the code which decides how much to rotate each cross-section
when exporting using survexport. Previous all cross-sections were
aligned West-East. Reported by Robert Jones.

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