source: git/src/gfxcore.cc @ 1798716

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

Adjust export to use Model class

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