source: git/src/gfxcore.cc @ 82277dd

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

src/gfxcore.cc: Don't default to percent gradient.

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