source: git/src/gfxcore.cc @ 2a26b45

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

src/gfxcore.cc,src/gfxcore.h: Take the width of the messages used
above the compass and clino into account when calculating how wide
they are.

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