source: git/src/gfxcore.cc @ dbd50e2

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

src/commands.c,src/gfxcore.cc: Add and enhance some TRANSLATORS
comments.

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