source: git/src/gfxcore.cc @ c3b20c5

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

src/gfxcore.cc,src/gfxcore.h: Reimplement animation so that it's
based on angular change per unit of elapsed time, rather than
averaging the time take for the last two scene redraws. This gives
a more even animation in the face of variable load and scene redraw
time, and should be more consistent between platforms.
src/gfxcore.cc: Switch to a point of the compass during auto-rotation
now jumps straight there rather than the two animations fighting.
src/gfxcore.cc: Reduce the maximum auto-rotation speed, as the
previous limit was uselessly fast.

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