source: git/src/gfxcore.cc @ 8ed917dc

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

src/gfxcore.cc: Make stats read from DEM file static.

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