source: git/src/gfxcore.cc @ 29f2e7d

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

src/gfxcore.cc: Increase volume diameter so that terrain doesn't get
clipped.

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