source: git/src/gfxcore.cc @ e840570

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

Drop support for wxWidgets < 3.0

3.0.0 was released over 5 years ago and should be easily available
everywhere by now.

I'm no longer easily able to test with wxWidgets 2.8, and this allows
a significant amount of cruft to be removed.

  • Property mode set to 100644
File size: 118.8 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
[112f80c]2779    if (!is.ReadAll(dem, size)) {
2780        if (know_size) {
2781            // FIXME: On __WXMSW__ currently we fail to
2782            // read any data from files in zips.
2783            delete [] dem;
2784            dem = NULL;
2785            wxMessageBox(wxT("Failed to read terrain data"));
2786            return false;
[c2fa50c]2787        }
[112f80c]2788        size = is.LastRead();
[c2fa50c]2789    }
[112f80c]2790
2791    if (dem_width == 0 && dem_height == 0) {
2792        dem_width = dem_height = sqrt(size / 2);
2793        if (dem_width * dem_height * 2 != size) {
2794            delete [] dem;
2795            dem = NULL;
2796            wxMessageBox(wxT("HGT format data doesn't form a square"));
2797            return false;
2798        }
2799        step_x = step_y = 1.0 / dem_width;
2800    }
2801
2802    return true;
2803}
2804
2805bool GfxCore::LoadDEM(const wxString & file)
2806{
[7997096]2807    if (m_Parent->GetCSProj().empty()) {
[112f80c]2808        wxMessageBox(wxT("No coordinate system specified in survey data"));
2809        return false;
2810    }
2811
2812    delete [] dem;
2813    dem = NULL;
2814
2815    size_t size = 0;
2816    // Default is to not skip any bytes.
2817    unsigned long skipbytes = 0;
2818    // For .hgt files, default to using filesize to determine.
2819    dem_width = dem_height = 0;
2820    // ESRI say "The default byte order is the same as that of the host machine
2821    // executing the software", but that's stupid so we default to
2822    // little-endian.
2823    bigendian = false;
2824
[522fb4c]2825    wxFileInputStream fs(file);
2826    if (!fs.IsOk()) {
[112f80c]2827        wxMessageBox(wxT("Failed to open DEM file"));
2828        return false;
[6388423]2829    }
[c2fa50c]2830
[112f80c]2831    const wxString & lc_file = file.Lower();
2832    if (lc_file.EndsWith(wxT(".hgt"))) {
2833        parse_hgt_filename(lc_file);
2834        read_bil(fs, size, skipbytes);
2835    } else if (lc_file.EndsWith(wxT(".bil"))) {
2836        wxString hdr_file = file;
2837        hdr_file.replace(file.size() - 4, 4, wxT(".hdr"));
[522fb4c]2838        wxFileInputStream hdr_is(hdr_file);
2839        if (!hdr_is.IsOk()) {
[112f80c]2840            wxMessageBox(wxT("Failed to open HDR file '") + hdr_file + wxT("'"));
2841            return false;
2842        }
2843        size = parse_hdr(hdr_is, skipbytes);
2844        read_bil(fs, size, skipbytes);
2845    } else if (lc_file.EndsWith(wxT(".zip"))) {
2846        wxZipEntry * ze_data = NULL;
2847        wxZipInputStream zs(fs);
2848        wxZipEntry * ze;
2849        while ((ze = zs.GetNextEntry()) != NULL) {
2850            if (!ze->IsDir()) {
2851                const wxString & lc_name = ze->GetName().Lower();
2852                if (!ze_data && lc_name.EndsWith(wxT(".hgt"))) {
2853                    // SRTM .hgt files are raw binary data, with the filename
2854                    // encoding the coordinates.
2855                    parse_hgt_filename(lc_name);
2856                    read_bil(zs, size, skipbytes);
2857                    delete ze;
2858                    break;
2859                }
2860
2861                if (!ze_data && lc_name.EndsWith(wxT(".bil"))) {
2862                    if (size) {
2863                        read_bil(zs, size, skipbytes);
2864                        break;
2865                    }
2866                    ze_data = ze;
2867                    continue;
2868                }
2869
2870                if (lc_name.EndsWith(wxT(".hdr"))) {
2871                    size = parse_hdr(zs, skipbytes);
2872                    if (ze_data) {
2873                        if (!zs.OpenEntry(*ze_data)) {
2874                            wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2875                            break;
2876                        }
2877                        read_bil(zs, size, skipbytes);
2878                    }
2879                } else if (lc_name.EndsWith(wxT(".prj"))) {
2880                    //FIXME: check this matches the datum string we use
2881                    //Projection    GEOGRAPHIC
2882                    //Datum         WGS84
2883                    //Zunits        METERS
2884                    //Units         DD
2885                    //Spheroid      WGS84
2886                    //Xshift        0.0000000000
2887                    //Yshift        0.0000000000
2888                    //Parameters
2889                }
2890            }
2891            delete ze;
2892        }
2893        delete ze_data;
2894    }
2895
2896    if (!dem) {
2897        return false;
2898    }
[622460e]2899
2900    InvalidateList(LIST_TERRAIN);
[74869a7]2901    ForceRefresh();
[5314a0e]2902    return true;
2903}
2904
2905void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2906{
2907    Vector3 n = (b - a) * (c - a);
2908    n.normalise();
2909    Double factor = dot(n, light) * .95 + .05;
2910    SetColour(col_WHITE, factor);
2911    PlaceVertex(a);
2912    PlaceVertex(b);
2913    PlaceVertex(c);
2914    ++n_tris;
2915}
2916
[7685ae3]2917// Like wxBusyCursor, but you can cancel it early.
2918class AvenBusyCursor {
2919    bool active;
2920
2921  public:
2922    AvenBusyCursor() : active(true) {
2923        wxBeginBusyCursor();
2924    }
2925
2926    void stop() {
2927        if (active) {
2928            active = false;
2929            wxEndBusyCursor();
2930        }
2931    }
2932
2933    ~AvenBusyCursor() {
2934        stop();
2935    }
2936};
2937
[5314a0e]2938void GfxCore::DrawTerrain()
2939{
[622460e]2940    if (!dem) return;
2941
[7685ae3]2942    AvenBusyCursor hourglass;
[c26455e]2943
[6388423]2944    // Draw terrain to twice the extent, or at least 1km.
2945    double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2946#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2947    static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2948    if (!pj_in) {
[9df33bc]2949        ToggleTerrain();
[7685ae3]2950        delete [] dem;
2951        dem = NULL;
2952        hourglass.stop();
[9df33bc]2953        error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2954        return;
[6388423]2955    }
[7997096]2956    static projPJ pj_out = pj_init_plus(m_Parent->GetCSProj().c_str());
[6388423]2957    if (!pj_out) {
[9df33bc]2958        ToggleTerrain();
[7685ae3]2959        delete [] dem;
2960        dem = NULL;
2961        hourglass.stop();
[7997096]2962        error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->GetCSProj().c_str());
[9df33bc]2963        return;
[6388423]2964    }
2965    n_tris = 0;
2966    SetAlpha(0.3);
2967    BeginTriangles();
2968    const Vector3 & off = m_Parent->GetOffset();
[5314a0e]2969    vector<Vector3> prevcol(dem_height + 1);
2970    for (size_t x = 0; x < dem_width; ++x) {
[6388423]2971        double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2972        Vector3 prev;
[5314a0e]2973        for (size_t y = 0; y < dem_height; ++y) {
[9df33bc]2974            unsigned short elev = dem[x + y * dem_width];
[194503c]2975#ifdef WORDS_BIGENDIAN
[9df33bc]2976            const bool MACHINE_BIGENDIAN = true;
2977#else
2978            const bool MACHINE_BIGENDIAN = false;
2979#endif
2980            if (bigendian != MACHINE_BIGENDIAN) {
2981#if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2982                elev = __builtin_bswap16(elev);
2983#else
2984                elev = (elev >> 8) | (elev << 8);
[194503c]2985#endif
[9df33bc]2986            }
[194503c]2987            double Z = (short)elev;
[6388423]2988            Vector3 pt;
2989            if (Z == nodata_value) {
2990                pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2991            } else {
2992                double X = X_;
2993                double Y = (o_y - y * step_y) * DEG_TO_RAD;
2994                pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2995                pt = Vector3(X, Y, Z) - off;
2996                double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2997                if (dist_2 > r_sqrd) {
2998                    pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2999                }
3000            }
3001            if (x > 0 && y > 0) {
3002                const Vector3 & a = prevcol[y - 1];
3003                const Vector3 & b = prevcol[y];
3004                // If all points are valid, split the quadrilateral into
3005                // triangles along the shorter 3D diagonal, which typically
3006                // looks better:
3007                //
3008                //               ----->
3009                //     prev---a    x     prev---a
3010                //   |   |P  /|            |\  S|
3011                // y |   |  / |    or      | \  |
3012                //   V   | /  |            |  \ |
3013                //       |/  Q|            |R  \|
3014                //       b----pt           b----pt
3015                //
3016                //       FORWARD           BACKWARD
3017                enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
3018                int valid =
3019                    ((prev.GetZ() != DBL_MAX)) |
3020                    ((a.GetZ() != DBL_MAX) << 1) |
3021                    ((b.GetZ() != DBL_MAX) << 2) |
3022                    ((pt.GetZ() != DBL_MAX) << 3);
3023                static const int tris_map[16] = {
3024                    NONE, // nothing valid
3025                    NONE, // prev
3026                    NONE, // a
3027                    NONE, // a, prev
3028                    NONE, // b
3029                    NONE, // b, prev
3030                    NONE, // b, a
3031                    P, // b, a, prev
3032                    NONE, // pt
3033                    NONE, // pt, prev
3034                    NONE, // pt, a
3035                    S, // pt, a, prev
3036                    NONE, // pt, b
3037                    R, // pt, b, prev
3038                    Q, // pt, b, a
3039                    ALL, // pt, b, a, prev
3040                };
3041                int tris = tris_map[valid];
3042                if (tris == ALL) {
3043                    // All points valid.
3044                    if ((a - b).magnitude() < (prev - pt).magnitude()) {
3045                        tris = P | Q;
3046                    } else {
3047                        tris = R | S;
3048                    }
3049                }
3050                if (tris & P)
3051                    DrawTerrainTriangle(a, prev, b);
3052                if (tris & Q)
3053                    DrawTerrainTriangle(a, b, pt);
3054                if (tris & R)
3055                    DrawTerrainTriangle(pt, prev, b);
3056                if (tris & S)
3057                    DrawTerrainTriangle(a, prev, pt);
3058            }
3059            prev = prevcol[y];
3060            prevcol[y].assign(pt);
3061        }
3062    }
3063    EndTriangles();
3064    SetAlpha(1.0);
[7685ae3]3065    if (n_tris == 0) {
3066        ToggleTerrain();
3067        delete [] dem;
3068        dem = NULL;
3069        hourglass.stop();
3070        /* TRANSLATORS: Aven shows a circle of terrain covering the area
3071         * of the survey plus a bit, but the terrain data file didn't
3072         * contain any data inside that circle.
3073         */
3074        error(/*No terrain data near area of survey*/161);
3075    }
[6388423]3076}
3077
[d2fcc9b]3078// Plot blobs.
[d9b3270]3079void GfxCore::GenerateBlobsDisplayList()
3080{
[e633bb1]3081    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
3082          m_Parent->GetNumHighlightedPts()))
3083        return;
[429465a]3084
[e633bb1]3085    // Plot blobs.
[1a46879]3086    const SurveyFilter* filter = m_Parent->GetTreeFilter();
[e633bb1]3087    gla_colour prev_col = col_BLACK; // not a colour used for blobs
3088    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
3089    BeginBlobs();
3090    while (pos != m_Parent->GetLabelsEnd()) {
[429465a]3091        const LabelInfo* label = *pos++;
3092
3093        // When more than one flag is set on a point:
3094        // search results take priority over entrance highlighting
3095        // which takes priority over fixed point
3096        // highlighting, which in turn takes priority over exported
3097        // point highlighting.
3098
3099        if (!((m_Surface && label->IsSurface()) ||
3100              (m_Legs && label->IsUnderground()) ||
3101              (!label->IsSurface() && !label->IsUnderground()))) {
3102            // if this station isn't to be displayed, skip to the next
3103            // (last case is for stns with no legs attached)
3104            continue;
3105        }
[672459c]3106        if (filter && !filter->CheckVisible(label->GetText()))
3107            continue;
[429465a]3108
[e633bb1]3109        gla_colour col;
3110
[429465a]3111        if (label->IsHighLighted()) {
3112            col = col_YELLOW;
3113        } else if (m_Entrances && label->IsEntrance()) {
3114            col = col_GREEN;
3115        } else if (m_FixedPts && label->IsFixedPt()) {
3116            col = col_RED;
3117        } else if (m_ExportedPts && label->IsExportedPt()) {
3118            col = col_TURQUOISE;
3119        } else {
3120            continue;
3121        }
3122
[e633bb1]3123        // Stations are sorted by blob type, so colour changes are infrequent.
3124        if (col != prev_col) {
[aa048c3]3125            SetColour(col);
[e633bb1]3126            prev_col = col;
[429465a]3127        }
[e633bb1]3128        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
[d9b3270]3129    }
[e633bb1]3130    EndBlobs();
[33b2094]3131}
3132
[6747314]3133void GfxCore::DrawIndicators()
[33b2094]3134{
[97ea48d]3135    // Draw colour key.
3136    if (m_ColourKey) {
[47c62d04]3137        drawing_list key_list = LIST_LIMIT_;
3138        switch (m_ColourBy) {
3139            case COLOUR_BY_DEPTH:
3140                key_list = LIST_DEPTH_KEY; break;
3141            case COLOUR_BY_DATE:
3142                key_list = LIST_DATE_KEY; break;
3143            case COLOUR_BY_ERROR:
3144                key_list = LIST_ERROR_KEY; break;
[cc9e2c65]3145            case COLOUR_BY_GRADIENT:
3146                key_list = LIST_GRADIENT_KEY; break;
[47c62d04]3147            case COLOUR_BY_LENGTH:
3148                key_list = LIST_LENGTH_KEY; break;
[68fb07a]3149#if 0 // FIXME Key for survey colours?
3150            case COLOUR_BY_SURVEY:
3151                key_list = LIST_SURVEY_KEY; break;
3152#endif
[47c62d04]3153        }
3154        if (key_list != LIST_LIMIT_) {
3155            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
[af50685]3156                       GetYSize() - KEY_OFFSET_Y, 0);
[1b164a0]3157        }
[33b2094]3158    }
[56da40e]3159
[203d2a7]3160    // Draw compass or elevation/heading indicators.
[eef68f9]3161    if (m_Compass || m_Clino) {
3162        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
[203d2a7]3163    }
[f433fda]3164
[56da40e]3165    // Draw scalebar.
[4a0e0623]3166    if (m_Scalebar && !GetPerspective()) {
[9c37beb]3167        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
[56da40e]3168    }
[33b2094]3169}
3170
[f336ab9]3171void GfxCore::PlaceVertexWithColour(const Vector3 & v,
3172                                    glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]3173                                    Double factor)
[f383708]3174{
[d1ce9bd]3175    SetColour(col_WHITE, factor);
[b839829]3176    PlaceVertex(v, tex_x, tex_y);
[da6c802]3177}
[f433fda]3178
[b839829]3179void GfxCore::SetDepthColour(Double z, Double factor) {
[da6c802]3180    // Set the drawing colour based on the altitude.
[78c67a6]3181    Double z_ext = m_Parent->GetDepthExtent();
[f383708]3182
[b839829]3183    z -= m_Parent->GetDepthMin();
[f383708]3184    // points arising from tubes may be slightly outside the limits...
[78c67a6]3185    if (z < 0) z = 0;
3186    if (z > z_ext) z = z_ext;
[a6f081c]3187
[2a9d2fa]3188    if (z == 0) {
3189        SetColour(GetPen(0), factor);
3190        return;
3191    }
3192
3193    assert(z_ext > 0.0);
[78c67a6]3194    Double how_far = z / z_ext;
[f383708]3195    assert(how_far >= 0.0);
3196    assert(how_far <= 1.0);
3197
[97ea48d]3198    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[0e69efe]3199    GLAPen pen1 = GetPen(band);
[97ea48d]3200    if (band < GetNumColourBands() - 1) {
[d4650b3]3201        const GLAPen& pen2 = GetPen(band + 1);
[f433fda]3202
[97ea48d]3203        Double interval = z_ext / (GetNumColourBands() - 1);
[78c67a6]3204        Double into_band = z / interval - band;
[f433fda]3205
[d4650b3]3206//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
3207//             z_offset, interval, band);
3208        // FIXME: why do we need to clamp here?  Is it because the walls can
3209        // extend further up/down than the centre-line?
3210        if (into_band < 0.0) into_band = 0.0;
3211        if (into_band > 1.0) into_band = 1.0;
3212        assert(into_band >= 0.0);
3213        assert(into_band <= 1.0);
[f433fda]3214
[d4650b3]3215        pen1.Interpolate(pen2, into_band);
3216    }
[aa048c3]3217    SetColour(pen1, factor);
[b839829]3218}
[f383708]3219
[b839829]3220void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
3221{
3222    SetDepthColour(v.GetZ(), factor);
[d67450e]3223    PlaceVertex(v);
[f383708]3224}
3225
[b839829]3226void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
[f336ab9]3227                                         glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]3228                                         Double factor)
3229{
3230    SetDepthColour(v.GetZ(), factor);
3231    PlaceVertex(v, tex_x, tex_y);
3232}
3233
[82f584f]3234void GfxCore::SplitLineAcrossBands(int band, int band2,
[4a0e6b35]3235                                   const Vector3 &p, const Vector3 &q,
[82f584f]3236                                   Double factor)
[b5d64e6]3237{
[4a0e6b35]3238    const int step = (band < band2) ? 1 : -1;
[b5d64e6]3239    for (int i = band; i != band2; i += step) {
[4a0e6b35]3240        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3241
3242        // Find the intersection point of the line p -> q
3243        // with the plane parallel to the xy-plane with z-axis intersection z.
[d67450e]3244        assert(q.GetZ() - p.GetZ() != 0.0);
[4a0e6b35]3245
[d67450e]3246        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
[4a0e6b35]3247//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
3248
[d67450e]3249        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3250        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
[4a0e6b35]3251
[d67450e]3252        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
[b5d64e6]3253    }
3254}
3255
[d7078b4]3256void GfxCore::SplitPolyAcrossBands(vector<vector<Split>>& splits,
[f2d6d32]3257                                   int band, int band2,
[ba828d4]3258                                   const Vector3 &p, const Vector3 &q,
3259                                   glaTexCoord ptx, glaTexCoord pty,
3260                                   glaTexCoord w, glaTexCoord h)
[f2d6d32]3261{
3262    const int step = (band < band2) ? 1 : -1;
3263    for (int i = band; i != band2; i += step) {
3264        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3265
3266        // Find the intersection point of the line p -> q
3267        // with the plane parallel to the xy-plane with z-axis intersection z.
3268        assert(q.GetZ() - p.GetZ() != 0.0);
3269
3270        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3271//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
3272
3273        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3274        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
[ba828d4]3275        glaTexCoord tx = ptx, ty = pty;
3276        if (w) tx += t * w;
3277        if (h) ty += t * h;
[f2d6d32]3278
[ba828d4]3279        splits[i].push_back(Split(Vector3(x, y, z), tx, ty));
3280        splits[i + step].push_back(Split(Vector3(x, y, z), tx, ty));
[f2d6d32]3281    }
3282}
3283
[14acdae]3284int GfxCore::GetDepthColour(Double z) const
[b5d64e6]3285{
[82f584f]3286    // Return the (0-based) depth colour band index for a z-coordinate.
[78c67a6]3287    Double z_ext = m_Parent->GetDepthExtent();
3288    z -= m_Parent->GetDepthMin();
[2ba3882]3289    // We seem to get rounding differences causing z to sometimes be slightly
[0a2aab8]3290    // less than GetDepthMin() here, and it can certainly be true for passage
3291    // tubes, so just clamp the value to 0.
[2ba3882]3292    if (z <= 0) return 0;
[6027220]3293    // We seem to get rounding differences causing z to sometimes exceed z_ext
[2c1c52e]3294    // by a small amount here (see: https://trac.survex.com/ticket/26) and it
[0a2aab8]3295    // can certainly be true for passage tubes, so just clamp the value.
3296    if (z >= z_ext) return GetNumColourBands() - 1;
[97ea48d]3297    return int(z / z_ext * (GetNumColourBands() - 1));
[b5d64e6]3298}
3299
[14acdae]3300Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
[b5d64e6]3301{
[82f584f]3302    // Return the z-coordinate of the depth colour boundary between
3303    // two adjacent depth colour bands (specified by 0-based indices).
3304
3305    assert((a == b - 1) || (a == b + 1));
[97ea48d]3306    if (GetNumColourBands() == 1) return 0;
[82f584f]3307
3308    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
[78c67a6]3309    Double z_ext = m_Parent->GetDepthExtent();
[2a9d2fa]3310    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
[b5d64e6]3311}
3312
[c61aa79]3313void GfxCore::AddPolyline(const traverse & centreline)
[da6c802]3314{
3315    BeginPolyline();
[d1ce9bd]3316    SetColour(col_WHITE);
[d4650b3]3317    vector<PointInfo>::const_iterator i = centreline.begin();
[d67450e]3318    PlaceVertex(*i);
[da6c802]3319    ++i;
3320    while (i != centreline.end()) {
[d67450e]3321        PlaceVertex(*i);
[da6c802]3322        ++i;
3323    }
3324    EndPolyline();
3325}
[2a3d328]3326
[c61aa79]3327void GfxCore::AddPolylineShadow(const traverse & centreline)
[f4c5932]3328{
3329    BeginPolyline();
[7ab01e7]3330    const double z = -0.5 * m_Parent->GetExtent().GetZ();
[d4650b3]3331    vector<PointInfo>::const_iterator i = centreline.begin();
[78c67a6]3332    PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]3333    ++i;
3334    while (i != centreline.end()) {
[78c67a6]3335        PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]3336        ++i;
3337    }
3338    EndPolyline();
3339}
3340
[c61aa79]3341void GfxCore::AddPolylineDepth(const traverse & centreline)
[da6c802]3342{
3343    BeginPolyline();
[d4650b3]3344    vector<PointInfo>::const_iterator i, prev_i;
[da6c802]3345    i = centreline.begin();
[ee7af72]3346    int band0 = GetDepthColour(i->GetZ());
[d67450e]3347    PlaceVertexWithDepthColour(*i);
[da6c802]3348    prev_i = i;
3349    ++i;
3350    while (i != centreline.end()) {
[ee7af72]3351        int band = GetDepthColour(i->GetZ());
[da6c802]3352        if (band != band0) {
[d67450e]3353            SplitLineAcrossBands(band0, band, *prev_i, *i);
[da6c802]3354            band0 = band;
3355        }
[d67450e]3356        PlaceVertexWithDepthColour(*i);
[da6c802]3357        prev_i = i;
3358        ++i;
3359    }
3360    EndPolyline();
3361}
3362
[f433fda]3363void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
[14acdae]3364                               const Vector3 &c, const Vector3 &d)
[da6c802]3365{
3366    Vector3 normal = (a - c) * (d - b);
3367    normal.normalise();
3368    Double factor = dot(normal, light) * .3 + .7;
[ba828d4]3369    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3370    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[9b57c71b]3371    // FIXME: should plot triangles instead to avoid rendering glitches.
[da6c802]3372    BeginQuadrilaterals();
[b839829]3373    PlaceVertexWithColour(a, 0, 0, factor);
3374    PlaceVertexWithColour(b, w, 0, factor);
3375    PlaceVertexWithColour(c, w, h, factor);
3376    PlaceVertexWithColour(d, 0, h, factor);
[da6c802]3377    EndQuadrilaterals();
3378}
3379
3380void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3381                                    const Vector3 &c, const Vector3 &d)
[2b02270]3382{
3383    Vector3 normal = (a - c) * (d - b);
3384    normal.normalise();
3385    Double factor = dot(normal, light) * .3 + .7;
3386    int a_band, b_band, c_band, d_band;
[d67450e]3387    a_band = GetDepthColour(a.GetZ());
[97ea48d]3388    a_band = min(max(a_band, 0), GetNumColourBands());
[d67450e]3389    b_band = GetDepthColour(b.GetZ());
[97ea48d]3390    b_band = min(max(b_band, 0), GetNumColourBands());
[d67450e]3391    c_band = GetDepthColour(c.GetZ());
[97ea48d]3392    c_band = min(max(c_band, 0), GetNumColourBands());
[d67450e]3393    d_band = GetDepthColour(d.GetZ());
[97ea48d]3394    d_band = min(max(d_band, 0), GetNumColourBands());
[ba828d4]3395    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3396    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[f2d6d32]3397    int min_band = min(min(a_band, b_band), min(c_band, d_band));
3398    int max_band = max(max(a_band, b_band), max(c_band, d_band));
3399    if (min_band == max_band) {
3400        // Simple case - the polygon is entirely within one band.
3401        BeginPolygon();
3402////    PlaceNormal(normal);
3403        PlaceVertexWithDepthColour(a, 0, 0, factor);
3404        PlaceVertexWithDepthColour(b, w, 0, factor);
3405        PlaceVertexWithDepthColour(c, w, h, factor);
3406        PlaceVertexWithDepthColour(d, 0, h, factor);
3407        EndPolygon();
3408    } else {
3409        // We need to make a separate polygon for each depth band...
[d7078b4]3410        vector<vector<Split>> splits;
[f2d6d32]3411        splits.resize(max_band + 1);
[ba828d4]3412        splits[a_band].push_back(Split(a, 0, 0));
[f2d6d32]3413        if (a_band != b_band) {
[ba828d4]3414            SplitPolyAcrossBands(splits, a_band, b_band, a, b, 0, 0, w, 0);
[f2d6d32]3415        }
[ba828d4]3416        splits[b_band].push_back(Split(b, w, 0));
[f2d6d32]3417        if (b_band != c_band) {
[ba828d4]3418            SplitPolyAcrossBands(splits, b_band, c_band, b, c, w, 0, 0, h);
[f2d6d32]3419        }
[ba828d4]3420        splits[c_band].push_back(Split(c, w, h));
[f2d6d32]3421        if (c_band != d_band) {
[ba828d4]3422            SplitPolyAcrossBands(splits, c_band, d_band, c, d, w, h, -w, 0);
[f2d6d32]3423        }
[ba828d4]3424        splits[d_band].push_back(Split(d, 0, h));
[f2d6d32]3425        if (d_band != a_band) {
[ba828d4]3426            SplitPolyAcrossBands(splits, d_band, a_band, d, a, 0, h, 0, -h);
[f2d6d32]3427        }
3428        for (int band = min_band; band <= max_band; ++band) {
3429            BeginPolygon();
[ba828d4]3430            for (auto&& item : splits[band]) {
3431                PlaceVertexWithDepthColour(item.vec, item.tx, item.ty, factor);
[f2d6d32]3432            }
3433            EndPolygon();
3434        }
[2b02270]3435    }
3436}
3437
[1ee204e]3438void GfxCore::SetColourFromDate(int date, Double factor)
[d4650b3]3439{
3440    // Set the drawing colour based on a date.
3441
[1ee204e]3442    if (date == -1) {
[2043961]3443        // Undated.
[522e0bd]3444        SetColour(NODATA_COLOUR, factor);
[d4650b3]3445        return;
3446    }
3447
[1ee204e]3448    int date_offset = date - m_Parent->GetDateMin();
[2043961]3449    if (date_offset == 0) {
3450        // Earliest date - handle as a special case for the single date case.
3451        SetColour(GetPen(0), factor);
3452        return;
3453    }
[d4650b3]3454
[2043961]3455    int date_ext = m_Parent->GetDateExtent();
[d4650b3]3456    Double how_far = (Double)date_offset / date_ext;
3457    assert(how_far >= 0.0);
3458    assert(how_far <= 1.0);
[371f9ed]3459    SetColourFrom01(how_far, factor);
[d4650b3]3460}
3461
[c61aa79]3462void GfxCore::AddPolylineDate(const traverse & centreline)
[d4650b3]3463{
3464    BeginPolyline();
3465    vector<PointInfo>::const_iterator i, prev_i;
3466    i = centreline.begin();
[1ee204e]3467    int date = i->GetDate();
[d4650b3]3468    SetColourFromDate(date, 1.0);
[d67450e]3469    PlaceVertex(*i);
[d4650b3]3470    prev_i = i;
3471    while (++i != centreline.end()) {
[1ee204e]3472        int newdate = i->GetDate();
[d4650b3]3473        if (newdate != date) {
3474            EndPolyline();
3475            BeginPolyline();
3476            date = newdate;
3477            SetColourFromDate(date, 1.0);
[d67450e]3478            PlaceVertex(*prev_i);
[d4650b3]3479        }
[d67450e]3480        PlaceVertex(*i);
[d4650b3]3481        prev_i = i;
3482    }
3483    EndPolyline();
3484}
3485
[1ee204e]3486static int static_date_hack; // FIXME
[d4650b3]3487
3488void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3489                                   const Vector3 &c, const Vector3 &d)
3490{
3491    Vector3 normal = (a - c) * (d - b);
3492    normal.normalise();
3493    Double factor = dot(normal, light) * .3 + .7;
[ba828d4]3494    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3495    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[d4650b3]3496    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]3497    BeginQuadrilaterals();
[d67450e]3498////    PlaceNormal(normal);
[d4650b3]3499    SetColourFromDate(static_date_hack, factor);
[b839829]3500    PlaceVertex(a, 0, 0);
3501    PlaceVertex(b, w, 0);
3502    PlaceVertex(c, w, h);
3503    PlaceVertex(d, 0, h);
3504    EndQuadrilaterals();
[d4650b3]3505}
3506
[c61aa79]3507static double static_E_hack; // FIXME
3508
3509void GfxCore::SetColourFromError(double E, Double factor)
3510{
3511    // Set the drawing colour based on an error value.
3512
3513    if (E < 0) {
[522e0bd]3514        SetColour(NODATA_COLOUR, factor);
[c61aa79]3515        return;
3516    }
3517
3518    Double how_far = E / MAX_ERROR;
3519    assert(how_far >= 0.0);
3520    if (how_far > 1.0) how_far = 1.0;
[371f9ed]3521    SetColourFrom01(how_far, factor);
[c61aa79]3522}
3523
3524void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3525                                    const Vector3 &c, const Vector3 &d)
3526{
3527    Vector3 normal = (a - c) * (d - b);
3528    normal.normalise();
3529    Double factor = dot(normal, light) * .3 + .7;
[ba828d4]3530    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3531    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[c61aa79]3532    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]3533    BeginQuadrilaterals();
[c61aa79]3534////    PlaceNormal(normal);
3535    SetColourFromError(static_E_hack, factor);
[b839829]3536    PlaceVertex(a, 0, 0);
3537    PlaceVertex(b, w, 0);
3538    PlaceVertex(c, w, h);
3539    PlaceVertex(d, 0, h);
3540    EndQuadrilaterals();
[c61aa79]3541}
3542
3543void GfxCore::AddPolylineError(const traverse & centreline)
3544{
3545    BeginPolyline();
3546    SetColourFromError(centreline.E, 1.0);
3547    vector<PointInfo>::const_iterator i;
3548    for(i = centreline.begin(); i != centreline.end(); ++i) {
3549        PlaceVertex(*i);
3550    }
3551    EndPolyline();
3552}
3553
[cc9e2c65]3554// gradient is in *radians*.
3555void GfxCore::SetColourFromGradient(double gradient, Double factor)
3556{
3557    // Set the drawing colour based on the gradient of the leg.
3558
3559    const Double GRADIENT_MAX = M_PI_2;
3560    gradient = fabs(gradient);
3561    Double how_far = gradient / GRADIENT_MAX;
3562    SetColourFrom01(how_far, factor);
3563}
3564
3565void GfxCore::AddPolylineGradient(const traverse & centreline)
3566{
3567    vector<PointInfo>::const_iterator i, prev_i;
3568    i = centreline.begin();
3569    prev_i = i;
3570    while (++i != centreline.end()) {
3571        BeginPolyline();
3572        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3573        PlaceVertex(*prev_i);
3574        PlaceVertex(*i);
3575        prev_i = i;
3576        EndPolyline();
3577    }
3578}
3579
3580static double static_gradient_hack; // FIXME
3581
3582void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3583                                       const Vector3 &c, const Vector3 &d)
3584{
3585    Vector3 normal = (a - c) * (d - b);
3586    normal.normalise();
3587    Double factor = dot(normal, light) * .3 + .7;
[ba828d4]3588    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3589    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[cc9e2c65]3590    // FIXME: should plot triangles instead to avoid rendering glitches.
3591    BeginQuadrilaterals();
3592////    PlaceNormal(normal);
3593    SetColourFromGradient(static_gradient_hack, factor);
3594    PlaceVertex(a, 0, 0);
3595    PlaceVertex(b, w, 0);
3596    PlaceVertex(c, w, h);
3597    PlaceVertex(d, 0, h);
3598    EndQuadrilaterals();
3599}
3600
[af50685]3601void GfxCore::SetColourFromLength(double length, Double factor)
3602{
3603    // Set the drawing colour based on log(length_of_leg).
3604
3605    Double log_len = log10(length);
3606    Double how_far = log_len / LOG_LEN_MAX;
3607    how_far = max(how_far, 0.0);
3608    how_far = min(how_far, 1.0);
[371f9ed]3609    SetColourFrom01(how_far, factor);
3610}
[af50685]3611
[68fb07a]3612void GfxCore::SetColourFromSurvey(const wxString& survey)
3613{
3614    // Set the drawing colour based on hash of name.
3615    int hash = hash_string(survey.utf8_str());
3616    wxImage::HSVValue hsv((hash & 0xff) / 256.0, (((hash >> 8) & 0x7f) | 0x80) / 256.0, 0.9);
3617    wxImage::RGBValue rgb = wxImage::HSVtoRGB(hsv);
3618    GLAPen pen;
3619    pen.SetColour(rgb.red / 256.0, rgb.green / 256.0, rgb.blue / 256.0);
3620    SetColour(pen);
3621}
3622
3623void GfxCore::SetColourFromSurveyStation(const wxString& name, Double factor)
3624{
3625    // Set the drawing colour based on hash of survey name.
3626    const char* p = name.utf8_str();
3627    const char* q = strrchr(p, m_Parent->GetSeparator());
3628    size_t len = q ? (q - p) : strlen(p);
3629    int hash = hash_data(p, len);
3630    wxImage::HSVValue hsv((hash & 0xff) / 256.0, (((hash >> 8) & 0x7f) | 0x80) / 256.0, 0.9);
3631    wxImage::RGBValue rgb = wxImage::HSVtoRGB(hsv);
3632    GLAPen pen;
3633    pen.SetColour(rgb.red / 256.0, rgb.green / 256.0, rgb.blue / 256.0);
3634    SetColour(pen, factor);
3635}
3636
[371f9ed]3637void GfxCore::SetColourFrom01(double how_far, Double factor)
3638{
3639    double b;
3640    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3641    int band(b);
[af50685]3642    GLAPen pen1 = GetPen(band);
[371f9ed]3643    // With 24bit colour, interpolating by less than this can have no effect.
3644    if (into_band >= 1.0 / 512.0) {
[af50685]3645        const GLAPen& pen2 = GetPen(band + 1);
3646        pen1.Interpolate(pen2, into_band);
3647    }
3648    SetColour(pen1, factor);
3649}
3650
3651void GfxCore::AddPolylineLength(const traverse & centreline)
3652{
3653    vector<PointInfo>::const_iterator i, prev_i;
3654    i = centreline.begin();
3655    prev_i = i;
3656    while (++i != centreline.end()) {
3657        BeginPolyline();
[5afbd60]3658        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
[af50685]3659        PlaceVertex(*prev_i);
3660        PlaceVertex(*i);
3661        prev_i = i;
3662        EndPolyline();
3663    }
3664}
3665
3666static double static_length_hack; // FIXME
3667
3668void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3669                                     const Vector3 &c, const Vector3 &d)
3670{
3671    Vector3 normal = (a - c) * (d - b);
3672    normal.normalise();
3673    Double factor = dot(normal, light) * .3 + .7;
[ba828d4]3674    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3675    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
[af50685]3676    // FIXME: should plot triangles instead to avoid rendering glitches.
3677    BeginQuadrilaterals();
3678////    PlaceNormal(normal);
3679    SetColourFromLength(static_length_hack, factor);
3680    PlaceVertex(a, 0, 0);
3681    PlaceVertex(b, w, 0);
3682    PlaceVertex(c, w, h);
3683    PlaceVertex(d, 0, h);
3684    EndQuadrilaterals();
3685}
3686
[68fb07a]3687void GfxCore::AddPolylineSurvey(const traverse & centreline)
3688{
3689    SetColourFromSurvey(centreline.name);
3690    vector<PointInfo>::const_iterator i, prev_i;
3691    i = centreline.begin();
3692    prev_i = i;
3693    while (++i != centreline.end()) {
3694        BeginPolyline();
3695        PlaceVertex(*prev_i);
3696        PlaceVertex(*i);
3697        prev_i = i;
3698        EndPolyline();
3699    }
3700}
3701
3702static const wxString* static_survey_hack;
3703
3704void GfxCore::AddQuadrilateralSurvey(const Vector3 &a, const Vector3 &b,
3705                                     const Vector3 &c, const Vector3 &d)
3706{
3707    Vector3 normal = (a - c) * (d - b);
3708    normal.normalise();
3709    Double factor = dot(normal, light) * .3 + .7;
3710    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3711    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3712    // FIXME: should plot triangles instead to avoid rendering glitches.
3713    BeginQuadrilaterals();
3714////    PlaceNormal(normal);
3715    SetColourFromSurveyStation(*static_survey_hack, factor);
3716    PlaceVertex(a, 0, 0);
3717    PlaceVertex(b, w, 0);
3718    PlaceVertex(c, w, h);
3719    PlaceVertex(d, 0, h);
3720    EndQuadrilaterals();
3721}
3722
[da6c802]3723void
[46a9883]3724GfxCore::SkinPassage(vector<XSect> & centreline)
[3ddcad8]3725{
[1a46879]3726    const SurveyFilter* filter = m_Parent->GetTreeFilter();
[b3852b5]3727    assert(centreline.size() > 1);
[3ddcad8]3728    Vector3 U[4];
[672459c]3729    XSect* prev_pt_v = NULL;
[3ddcad8]3730    Vector3 last_right(1.0, 0.0, 0.0);
3731
[c61aa79]3732//  FIXME: it's not simple to set the colour of a tube based on error...
3733//    static_E_hack = something...
[fc68ad5]3734    vector<XSect>::iterator i = centreline.begin();
[ee05463]3735    vector<XSect>::size_type segment = 0;
[3ddcad8]3736    while (i != centreline.end()) {
3737        // get the coordinates of this vertex
[fc68ad5]3738        XSect & pt_v = *i++;
[3ddcad8]3739
3740        bool cover_end = false;
3741
3742        Vector3 right, up;
3743
3744        const Vector3 up_v(0.0, 0.0, 1.0);
3745
[68fb07a]3746        static_survey_hack = &(pt_v.GetLabel());
[3ddcad8]3747        if (segment == 0) {
3748            assert(i != centreline.end());
3749            // first segment
3750
3751            // get the coordinates of the next vertex
[ee05463]3752            const XSect & next_pt_v = *i;
[3ddcad8]3753
3754            // calculate vector from this pt to the next one
[d67450e]3755            Vector3 leg_v = next_pt_v - pt_v;
[3ddcad8]3756
3757            // obtain a vector in the LRUD plane
3758            right = leg_v * up_v;
3759            if (right.magnitude() == 0) {
3760                right = last_right;
3761                // Obtain a second vector in the LRUD plane,
3762                // perpendicular to the first.
[760ad29d]3763                //up = right * leg_v;
3764                up = up_v;
[3ddcad8]3765            } else {
3766                last_right = right;
3767                up = up_v;
[da6c802]3768            }
3769
[3ddcad8]3770            cover_end = true;
[d4650b3]3771            static_date_hack = next_pt_v.GetDate();
[3ddcad8]3772        } else if (segment + 1 == centreline.size()) {
3773            // last segment
3774
3775            // Calculate vector from the previous pt to this one.
[672459c]3776            Vector3 leg_v = pt_v - *prev_pt_v;
[3ddcad8]3777
3778            // Obtain a horizontal vector in the LRUD plane.
3779            right = leg_v * up_v;
3780            if (right.magnitude() == 0) {
[d67450e]3781                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
[3ddcad8]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;
3789            }
[da6c802]3790
[3ddcad8]3791            cover_end = true;
[d4650b3]3792            static_date_hack = pt_v.GetDate();
[3ddcad8]3793        } else {
3794            assert(i != centreline.end());
3795            // Intermediate segment.
3796
3797            // Get the coordinates of the next vertex.
[ee05463]3798            const XSect & next_pt_v = *i;
[3ddcad8]3799
3800            // Calculate vectors from this vertex to the
3801            // next vertex, and from the previous vertex to
3802            // this one.
[672459c]3803            Vector3 leg1_v = pt_v - *prev_pt_v;
[d67450e]3804            Vector3 leg2_v = next_pt_v - pt_v;
[3ddcad8]3805
3806            // Obtain horizontal vectors perpendicular to
3807            // both legs, then normalise and average to get
3808            // a horizontal bisector.
3809            Vector3 r1 = leg1_v * up_v;
3810            Vector3 r2 = leg2_v * up_v;
3811            r1.normalise();
3812            r2.normalise();
3813            right = r1 + r2;
3814            if (right.magnitude() == 0) {
3815                // This is the "mid-pitch" case...
3816                right = last_right;
3817            }
3818            if (r1.magnitude() == 0) {
[760ad29d]3819                up = up_v;
[3ddcad8]3820
3821                // Rotate pitch section to minimise the
[cbe7dde]3822                // "torsional stress" - FIXME: use
[3ddcad8]3823                // triangles instead of rectangles?
3824                int shift = 0;
3825                Double maxdotp = 0;
3826
3827                // Scale to unit vectors in the LRUD plane.
3828                right.normalise();
3829                up.normalise();
3830                Vector3 vec = up - right;
3831                for (int orient = 0; orient <= 3; ++orient) {
[672459c]3832                    Vector3 tmp = U[orient] - prev_pt_v->GetPoint();
[3ddcad8]3833                    tmp.normalise();
3834                    Double dotp = dot(vec, tmp);
3835                    if (dotp > maxdotp) {
3836                        maxdotp = dotp;
3837                        shift = orient;
3838                    }
3839                }
3840                if (shift) {
3841                    if (shift != 2) {
3842                        Vector3 temp(U[0]);
[b3852b5]3843                        U[0] = U[shift];
3844                        U[shift] = U[2];
3845                        U[2] = U[shift ^ 2];
3846                        U[shift ^ 2] = temp;
[ee7af72]3847                    } else {
[3ddcad8]3848                        swap(U[0], U[2]);
3849                        swap(U[1], U[3]);
[ee7af72]3850                    }
[3ddcad8]3851                }
3852#if 0
3853                // Check that the above code actually permuted
3854                // the vertices correctly.
3855                shift = 0;
3856                maxdotp = 0;
[b3852b5]3857                for (int j = 0; j <= 3; ++j) {
[672459c]3858                    Vector3 tmp = U[j] - *prev_pt_v;
[3ddcad8]3859                    tmp.normalise();
3860                    Double dotp = dot(vec, tmp);
3861                    if (dotp > maxdotp) {
3862                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
[b3852b5]3863                        shift = j;
[da6c802]3864                    }
[3ddcad8]3865                }
3866                if (shift) {
3867                    printf("New shift = %d!\n", shift);
3868                    shift = 0;
3869                    maxdotp = 0;
[b3852b5]3870                    for (int j = 0; j <= 3; ++j) {
[672459c]3871                        Vector3 tmp = U[j] - *prev_pt_v;
[3ddcad8]3872                        tmp.normalise();
3873                        Double dotp = dot(vec, tmp);
[b3852b5]3874                        printf("    %d : %.8f\n", j, dotp);
[da6c802]3875                    }
3876                }
[3ddcad8]3877#endif
3878            } else {
3879                up = up_v;
[da6c802]3880            }
[3ddcad8]3881            last_right = right;
[d4650b3]3882            static_date_hack = pt_v.GetDate();
[da6c802]3883        }
3884
[3ddcad8]3885        // Scale to unit vectors in the LRUD plane.
3886        right.normalise();
3887        up.normalise();
[33b2094]3888
[57a3cd4]3889        Double l = fabs(pt_v.GetL());
3890        Double r = fabs(pt_v.GetR());
3891        Double u = fabs(pt_v.GetU());
3892        Double d = fabs(pt_v.GetD());
[3ddcad8]3893
3894        // Produce coordinates of the corners of the LRUD "plane".
3895        Vector3 v[4];
[672459c]3896        v[0] = pt_v.GetPoint() - right * l + up * u;
3897        v[1] = pt_v.GetPoint() + right * r + up * u;
3898        v[2] = pt_v.GetPoint() + right * r - up * d;
3899        v[3] = pt_v.GetPoint() - right * l - up * d;
[3ddcad8]3900
[46a9883]3901        if (segment > 0) {
3902            if (!filter || (filter->CheckVisible(pt_v.GetLabel()) &&
3903                            filter->CheckVisible(prev_pt_v->GetLabel()))) {
3904                const Vector3 & delta = pt_v - *prev_pt_v;
3905                static_length_hack = delta.magnitude();
3906                static_gradient_hack = delta.gradient();
3907                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3908                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3909                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3910                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
[384534c]3911            }
[46a9883]3912        }
[9eb58d0]3913
[46a9883]3914        if (cover_end) {
3915            if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
3916                if (segment == 0) {
3917                    (this->*AddQuad)(v[0], v[1], v[2], v[3]);
3918                } else {
3919                    (this->*AddQuad)(v[3], v[2], v[1], v[0]);
[8fc6473]3920                }
[384534c]3921            }
[3ddcad8]3922        }
[9eb58d0]3923
[672459c]3924        prev_pt_v = &pt_v;
[3ddcad8]3925        U[0] = v[0];
3926        U[1] = v[1];
3927        U[2] = v[2];
3928        U[3] = v[3];
[9eb58d0]3929
[3ddcad8]3930        ++segment;
3931    }
[33b2094]3932}
[b13aee4]3933
3934void GfxCore::FullScreenMode()
3935{
[ea940373]3936    m_Parent->ViewFullScreen();
[b13aee4]3937}
[fdfa926]3938
3939bool GfxCore::IsFullScreen() const
3940{
3941    return m_Parent->IsFullScreen();
3942}
[1690fa9]3943
[b75a37d]3944bool GfxCore::FullScreenModeShowingMenus() const
3945{
3946    return m_Parent->FullScreenModeShowingMenus();
3947}
3948
3949void GfxCore::FullScreenModeShowMenus(bool show)
3950{
3951    m_Parent->FullScreenModeShowMenus(show);
3952}
3953
[46361bc]3954void
3955GfxCore::MoveViewer(double forward, double up, double right)
3956{
[e577f89]3957    double cT = cos(rad(m_TiltAngle));
3958    double sT = sin(rad(m_TiltAngle));
3959    double cP = cos(rad(m_PanAngle));
3960    double sP = sin(rad(m_PanAngle));
[7a57dc7]3961    Vector3 v_forward(cT * sP, cT * cP, sT);
3962    Vector3 v_up(sT * sP, sT * cP, -cT);
[867a1141]3963    Vector3 v_right(-cP, sP, 0);
[d4a5aaf]3964    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3965    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3966    assert(fabs(dot(v_right, v_up)) < 1e-6);
[46361bc]3967    Vector3 move = v_forward * forward + v_up * up + v_right * right;
[d67450e]3968    AddTranslation(-move);
[d877aa2]3969    // Show current position.
[d67450e]3970    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
[46361bc]3971    ForceRefresh();
3972}
3973
[1690fa9]3974PresentationMark GfxCore::GetView() const
3975{
[d67450e]3976    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
[7a57dc7]3977                            m_PanAngle, -m_TiltAngle, m_Scale);
[1690fa9]3978}
3979
3980void GfxCore::SetView(const PresentationMark & p)
3981{
3982    m_SwitchingTo = 0;
[d67450e]3983    SetTranslation(p - m_Parent->GetOffset());
[1690fa9]3984    m_PanAngle = p.angle;
[7a57dc7]3985    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
[08253d9]3986    SetRotation(m_PanAngle, m_TiltAngle);
[1690fa9]3987    SetScale(p.scale);
3988    ForceRefresh();
3989}
3990
[128fac4]3991void GfxCore::PlayPres(double speed, bool change_speed) {
3992    if (!change_speed || presentation_mode == 0) {
3993        if (speed == 0.0) {
3994            presentation_mode = 0;
3995            return;
3996        }
3997        presentation_mode = PLAYING;
3998        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3999        SetView(next_mark);
4000        next_mark_time = 0; // There already!
4001        this_mark_total = 0;
4002        pres_reverse = (speed < 0);
4003    }
4004
[d67450e]4005    if (change_speed) pres_speed = speed;
4006
[128fac4]4007    if (speed != 0.0) {
4008        bool new_pres_reverse = (speed < 0);
4009        if (new_pres_reverse != pres_reverse) {
4010            pres_reverse = new_pres_reverse;
4011            if (pres_reverse) {
4012                next_mark = m_Parent->GetPresMark(MARK_PREV);
4013            } else {
4014                next_mark = m_Parent->GetPresMark(MARK_NEXT);
4015            }
4016            swap(this_mark_total, next_mark_time);
4017        }
4018    }
[1690fa9]4019}
[6a4cdcb6]4020
[da6c802]4021void GfxCore::SetColourBy(int colour_by) {
4022    m_ColourBy = colour_by;
4023    switch (colour_by) {
4024        case COLOUR_BY_DEPTH:
4025            AddQuad = &GfxCore::AddQuadrilateralDepth;
4026            AddPoly = &GfxCore::AddPolylineDepth;
4027            break;
[d4650b3]4028        case COLOUR_BY_DATE:
4029            AddQuad = &GfxCore::AddQuadrilateralDate;
4030            AddPoly = &GfxCore::AddPolylineDate;
4031            break;
[c61aa79]4032        case COLOUR_BY_ERROR:
4033            AddQuad = &GfxCore::AddQuadrilateralError;
4034            AddPoly = &GfxCore::AddPolylineError;
4035            break;
[cc9e2c65]4036        case COLOUR_BY_GRADIENT:
4037            AddQuad = &GfxCore::AddQuadrilateralGradient;
4038            AddPoly = &GfxCore::AddPolylineGradient;
4039            break;
[af50685]4040        case COLOUR_BY_LENGTH:
4041            AddQuad = &GfxCore::AddQuadrilateralLength;
4042            AddPoly = &GfxCore::AddPolylineLength;
4043            break;
[68fb07a]4044        case COLOUR_BY_SURVEY:
4045            AddQuad = &GfxCore::AddQuadrilateralSurvey;
4046            AddPoly = &GfxCore::AddPolylineSurvey;
4047            break;
[da6c802]4048        default: // case COLOUR_BY_NONE:
4049            AddQuad = &GfxCore::AddQuadrilateral;
4050            AddPoly = &GfxCore::AddPolyline;
4051            break;
4052    }
4053
[d2fcc9b]4054    InvalidateList(LIST_UNDERGROUND_LEGS);
[c61aa79]4055    InvalidateList(LIST_SURFACE_LEGS);
[d2fcc9b]4056    InvalidateList(LIST_TUBES);
[da6c802]4057
4058    ForceRefresh();
4059}
4060
[6a4cdcb6]4061bool GfxCore::ExportMovie(const wxString & fnm)
4062{
[8f9bade6]4063    FILE* fh = wxFopen(fnm.fn_str(), wxT("wb"));
[f4e4b56]4064    if (fh == NULL) {
4065        wxGetApp().ReportError(wxString::Format(wmsg(/*Failed to open output file “%s”*/47), fnm.c_str()));
4066        return false;
4067    }
4068
4069    wxString ext;
4070    wxFileName::SplitPath(fnm, NULL, NULL, NULL, &ext, wxPATH_NATIVE);
4071
[6a4cdcb6]4072    int width;
4073    int height;
4074    GetSize(&width, &height);
[028829f]4075    // Round up to next multiple of 2 (required by ffmpeg).
4076    width += (width & 1);
[6a4cdcb6]4077    height += (height & 1);
4078
[75d4a2b]4079    movie = new MovieMaker();
[6a4cdcb6]4080
[f4e4b56]4081    // movie takes ownership of fh.
4082    if (!movie->Open(fh, ext.utf8_str(), width, height)) {
[091069f]4083        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
[75d4a2b]4084        delete movie;
[81f1266]4085        movie = NULL;
[6a4cdcb6]4086        return false;
4087    }
[f433fda]4088
[d10d369]4089    PlayPres(1);
[6a4cdcb6]4090    return true;
4091}
[223f1ad]4092
[ce403f1]4093void
4094GfxCore::OnPrint(const wxString &filename, const wxString &title,
[1798716]4095                 const wxString &datestamp,
[4ed8154]4096                 bool close_after_print)
[ce403f1]4097{
4098    svxPrintDlg * p;
[60d7755]4099    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
[ce403f1]4100                        m_PanAngle, m_TiltAngle,
[ddcf585]4101                        m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
4102                        m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
[4ed8154]4103                        true, close_after_print);
[6d1bc83]4104    p->Show(true);
[ce403f1]4105}
4106
[5940815]4107void
[70462c8]4108GfxCore::OnExport(const wxString &filename, const wxString &title,
[60d7755]4109                  const wxString &datestamp)
[223f1ad]4110{
[5940815]4111    svxPrintDlg * p;
[60d7755]4112    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
[5940815]4113                        m_PanAngle, m_TiltAngle,
[ddcf585]4114                        m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
4115                        m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
[5940815]4116                        false);
[6d1bc83]4117    p->Show(true);
[223f1ad]4118}
[e2c1671]4119
4120static wxCursor
4121make_cursor(const unsigned char * bits, const unsigned char * mask,
4122            int hotx, int hoty)
4123{
[6654cf2]4124#if defined __WXGTK__ && !defined __WXGTK3__
4125    // Use this code for GTK < 3 only - it doesn't work properly with GTK3
4126    // (reported and should be fixed in wxWidgets 3.0.4 and 3.1.1, see:
4127    // https://trac.wxwidgets.org/ticket/17916)
4128    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
4129                    (const char *)mask, wxBLACK, wxWHITE);
4130#else
[60adbce]4131# ifdef __WXMAC__
4132    // The default Mac cursor is black with a white edge, so
4133    // invert our custom cursors to match.
4134    char b[128];
4135    for (int i = 0; i < 128; ++i)
4136        b[i] = bits[i] ^ 0xff;
4137# else
4138    const char * b = reinterpret_cast<const char *>(bits);
4139# endif
4140    wxBitmap cursor_bitmap(b, 32, 32);
[7f3fe6d]4141    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
[4dc4384]4142    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
[e2c1671]4143    wxImage cursor_image = cursor_bitmap.ConvertToImage();
4144    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
4145    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
[7f3fe6d]4146    return wxCursor(cursor_image);
[e2c1671]4147#endif
4148}
4149
4150const
4151#include "hand.xbm"
4152const
4153#include "handmask.xbm"
4154
4155const
4156#include "brotate.xbm"
4157const
4158#include "brotatemask.xbm"
4159
4160const
4161#include "vrotate.xbm"
4162const
4163#include "vrotatemask.xbm"
4164
4165const
4166#include "rotate.xbm"
4167const
4168#include "rotatemask.xbm"
4169
[ecf2d23]4170const
4171#include "rotatezoom.xbm"
4172const
4173#include "rotatezoommask.xbm"
4174
[e2c1671]4175void
[242cb07]4176GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
[e2c1671]4177{
4178    // Check if we're already showing that cursor.
4179    if (current_cursor == new_cursor) return;
4180
4181    current_cursor = new_cursor;
4182    switch (current_cursor) {
4183        case GfxCore::CURSOR_DEFAULT:
4184            GLACanvas::SetCursor(wxNullCursor);
4185            break;
4186        case GfxCore::CURSOR_POINTING_HAND:
4187            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
4188            break;
4189        case GfxCore::CURSOR_DRAGGING_HAND:
4190            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
4191            break;
4192        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
4193            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
4194            break;
4195        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
4196            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
4197            break;
4198        case GfxCore::CURSOR_ROTATE_VERTICALLY:
4199            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
4200            break;
4201        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
4202            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
4203            break;
4204        case GfxCore::CURSOR_ZOOM:
4205            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
4206            break;
[ecf2d23]4207        case GfxCore::CURSOR_ZOOM_ROTATE:
4208            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
4209            break;
[e2c1671]4210    }
4211}
[6b061db]4212
4213bool GfxCore::MeasuringLineActive() const
4214{
4215    if (Animating()) return false;
[381ae6e]4216    return HereIsReal() || m_there;
[6b061db]4217}
[acdb8aa]4218
4219bool GfxCore::HandleRClick(wxPoint point)
4220{
4221    if (PointWithinCompass(point)) {
4222        // Pop up menu.
4223        wxMenu menu;
[736f7df]4224        /* TRANSLATORS: View *looking* North */
[055bfc58]4225        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
[736f7df]4226        /* TRANSLATORS: View *looking* East */
[055bfc58]4227        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
[736f7df]4228        /* TRANSLATORS: View *looking* South */
[055bfc58]4229        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
[736f7df]4230        /* TRANSLATORS: View *looking* West */
[055bfc58]4231        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
4232        menu.AppendSeparator();
[736f7df]4233        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
[4d2301e]4234        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
[0b8c321]4235        /* TRANSLATORS: tickable menu item in View menu.
4236         *
4237         * Degrees are the angular measurement where there are 360 in a full
4238         * circle. */
[acdb8aa]4239        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]4240        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]4241        PopupMenu(&menu);
4242        return true;
4243    }
4244
4245    if (PointWithinClino(point)) {
4246        // Pop up menu.
4247        wxMenu menu;
[055bfc58]4248        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
4249        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
4250        menu.AppendSeparator();
[736f7df]4251        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
[acdb8aa]4252        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
[736f7df]4253        /* TRANSLATORS: tickable menu item in View menu.
4254         *
4255         * Degrees are the angular measurement where there are 360 in a full
4256         * circle. */
[acdb8aa]4257        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[736f7df]4258        /* TRANSLATORS: tickable menu item in View menu.
4259         *
4260         * Show the tilt of the survey as a percentage gradient (100% = 45
4261         * degrees = 50 grad). */
[d171c0c]4262        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
[ee3e284]4263        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4264        PopupMenu(&menu);
[acdb8aa]4265        return true;
4266    }
4267
4268    if (PointWithinScaleBar(point)) {
4269        // Pop up menu.
4270        wxMenu menu;
[736f7df]4271        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
[acdb8aa]4272        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
[0b8c321]4273        /* TRANSLATORS: tickable menu item in View menu.
4274         *
4275         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
4276         */
[acdb8aa]4277        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]4278        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]4279        PopupMenu(&menu);
4280        return true;
4281    }
4282
4283    if (PointWithinColourKey(point)) {
4284        // Pop up menu.
4285        wxMenu menu;
[46beda0]4286        menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
4287        menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
4288        menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
4289        menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
4290        menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
[68fb07a]4291        menu.AppendCheckItem(menu_COLOUR_BY_SURVEY, wmsg(/*Colour by &Survey*/448));
[d43fa84]4292        menu.AppendSeparator();
[736f7df]4293        /* TRANSLATORS: Menu item which turns off the colour key.
4294         * The "Colour Key" is the thing in aven showing which colour
4295         * corresponds to which depth, date, survey closure error, etc. */
[97ea48d]4296        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
[391af6a]4297        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
[d43fa84]4298            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[cc9e2c65]4299        else if (m_ColourBy == COLOUR_BY_GRADIENT)
4300            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]4301        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]4302        PopupMenu(&menu);
4303        return true;
4304    }
4305
4306    return false;
4307}
[dd6af8b]4308
4309void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
4310{
4311    if (centred) {
4312        p1.x = p2.x + (p1.x - p2.x) * 2;
4313        p1.y = p2.y + (p1.y - p2.y) * 2;
4314    }
4315    if (aspect) {
4316#if 0 // FIXME: This needs more work.
4317        int sx = GetXSize();
4318        int sy = GetYSize();
4319        int dx = p1.x - p2.x;
4320        int dy = p1.y - p2.y;
4321        int dy_new = dx * sy / sx;
4322        if (abs(dy_new) >= abs(dy)) {
4323            p1.y += (dy_new - dy) / 2;
4324            p2.y -= (dy_new - dy) / 2;
4325        } else {
4326            int dx_new = dy * sx / sy;
4327            p1.x += (dx_new - dx) / 2;
4328            p2.x -= (dx_new - dx) / 2;
4329        }
4330#endif
4331    }
4332    zoombox.set(p1, p2);
4333    ForceRefresh();
4334}
4335
4336void GfxCore::ZoomBoxGo()
4337{
4338    if (!zoombox.active()) return;
4339
4340    int width = GetXSize();
4341    int height = GetYSize();
4342
4343    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
4344                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
4345    int box_w = abs(zoombox.x1 - zoombox.x2);
4346    int box_h = abs(zoombox.y1 - zoombox.y2);
4347
4348    double factor = min(double(width) / box_w, double(height) / box_h);
4349
4350    zoombox.unset();
4351
4352    SetScale(GetScale() * factor);
4353}
Note: See TracBrowser for help on using the repository browser.