source: git/src/gfxcore.cc @ 355809f

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 355809f was 355809f, checked in by Olly Betts <olly@…>, 9 years ago

src/gfxcore.cc: Put units below length key (like we do for depth
key) and only show one decimal place on the lengths.

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