source: git/src/gfxcore.cc @ f4e4b56

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

Fix movie export to Unicode out path on wxMSW

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