source: git/src/gfxcore.cc @ 622460e

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

lib/survex.pot,src/: Add UI for loading terrain files.

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