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

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

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

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