source: git/src/gfxcore.cc @ dbd50e2

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

src/commands.c,src/gfxcore.cc: Add and enhance some TRANSLATORS
comments.

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