source: git/src/gfxcore.cc @ cf1368a

stereo
Last change on this file since cf1368a was e9c9ce0f, checked in by Olly Betts <olly@…>, 6 years ago

Experimental stereo viewing support

Tries to use OpenGL stereo by default.

Comment out this in aven.h to use coloured glasses:

#define STEREO_BUFFERS

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