source: git/src/gfxcore.cc @ f4e4b56

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

Fix movie export to Unicode out path on wxMSW

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