source: git/src/gfxcore.cc @ bb3d137

stereo
Last change on this file since bb3d137 was 938fee8, checked in by Olly Betts <olly@…>, 6 years ago

Fix to work with stereo buffers

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