source: git/src/gfxcore.cc @ 29f2e7d

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

src/gfxcore.cc: Increase volume diameter so that terrain doesn't get
clipped.

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