source: git/src/gfxcore.cc @ 84bfd98

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

src/gfxcore.cc: When reading .hgt files, flag a read error if we
can't read any data.

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