source: git/src/gfxcore.cc @ 91732f2

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

src/gfxcore.cc: Test with the void-filled 3-arc second SRTM data.

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