source: git/src/gfxcore.cc @ 8ed917dc

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

src/gfxcore.cc: Make stats read from DEM file static.

  • Property mode set to 100644
File size: 100.9 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                if (fd < 0) {
2360                    wxMessageBox(wxT("Failed to open DEM zip"));
2361                    ToggleTerrain();
2362                    return;
2363                }
2364                wxZipEntry * ze_bil = NULL;
2365                wxFileInputStream fs(fd);
2366                wxZipInputStream zs(fs);
2367                wxZipEntry * ze;
2368                while ((ze = zs.GetNextEntry()) != NULL) {
2369                    if (!ze->IsDir()) {
2370                        const wxString & name = ze->GetName();
2371                        if (!ze_bil && name.EndsWith(wxT(".bil"))) {
2372                            ze_bil = ze;
2373                            continue;
2374                        }
2375
2376                        if (name.EndsWith(wxT(".hdr"))) {
2377                            unsigned long nbits;
2378                            while (!zs.Eof()) {
2379                                wxString line;
2380                                int ch;
2381                                while ((ch = zs.GetC()) != wxEOF) {
2382                                    if (ch == '\n' || ch == '\r') break;
2383                                    line += wxChar(ch);
2384                                }
2385#define CHECK(X, COND) \
2386    } else if (line.StartsWith(wxT(X" "))) { \
2387        size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2388        if (v == line.npos || !(COND)) { \
2389            err += wxT("Unexpected value for "X); \
2390        }
2391                                wxString err;
2392                                unsigned long dummy;
2393                                if (false) {
2394                                CHECK("BYTEORDER", line[v] == 'I')
2395                                CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2396                                CHECK("NROWS", line.substr(v).ToCULong(&width))
2397                                CHECK("NCOLS", line.substr(v).ToCULong(&height))
2398                                CHECK("NBANDS", line.substr(v).ToCULong(&dummy) && dummy == 1)
2399                                CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2400                                //: BANDROWBYTES   7202
2401                                //: TOTALROWBYTES  7202
2402                                CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2403                                CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2404                                CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2405                                CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2406                                CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2407                                CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2408                                }
2409                                if (!err.empty()) {
2410                                    wxMessageBox(err);
2411                                }
2412                            }
2413                            size = ((nbits + 7) / 8) * width * height;
2414                            bil = new short[size];
2415                        } else if (name.EndsWith(wxT(".prj"))) {
2416                            //FIXME: check this matches the datum string we use
2417                            //Projection    GEOGRAPHIC
2418                            //Datum         WGS84
2419                            //Zunits        METERS
2420                            //Units         DD
2421                            //Spheroid      WGS84
2422                            //Xshift        0.0000000000
2423                            //Yshift        0.0000000000
2424                            //Parameters
2425                        }
2426                    }
2427                    delete ze;
2428                }
2429                if (ze_bil && zs.OpenEntry(*ze_bil)) {
2430#if wxCHECK_VERSION(2,9,5)
2431                    if (!zs.ReadAll(bil, size)) {
2432                        wxMessageBox(wxT("Failed to read terrain data"));
2433                    }
2434#else
2435                    char * p = reinterpret_cast<char *>(bil);
2436                    while (size) {
2437                        zs.Read(p, size);
2438                        size_t c = zs.LastRead();
2439                        if (c == 0) {
2440                            wxMessageBox(wxT("Failed to read terrain data"));
2441                            break;
2442                        }
2443                        p += c;
2444                        size -= c;
2445                    }
2446#endif
2447                }
2448                delete ze_bil;
2449            }
2450            if (!bil) {
2451                break;
2452            }
2453#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2454            static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2455            if (!pj_in) {
2456                fatalerror(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2457            }
2458            static projPJ pj_out = pj_init_plus(m_Parent->m_cs_proj.c_str());
2459            if (!pj_out) {
2460                fatalerror(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->m_cs_proj.c_str());
2461            }
2462            size_t n_x = 0;
2463            SetAlpha(0.3);
2464            SetColour(col_WHITE);
2465            const Vector3 & off = m_Parent->GetOffset();
2466            for (size_t x = 0; x < width; ++x) {
2467                double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2468                bool in_line = false;
2469                for (size_t y = 0; y < height; ++y) {
2470                    double Z = bil[x + y * width];
2471                    if (Z == nodata_value) {
2472                        if (in_line) {
2473                            EndPolyline();
2474                            in_line = false;
2475                        }
2476                        continue;
2477                    }
2478                    double X = X_;
2479                    double Y = (o_y - y * step_y) * DEG_TO_RAD;
2480                    pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2481                    X -= off.GetX();
2482                    Y -= off.GetY();
2483                    double dist_2 = sqrd(X) + sqrd(Y);
2484                    if (dist_2 < sqrd(8000.0)) {
2485                        Z -= off.GetZ();
2486                        if (!in_line) {
2487                            in_line = true;
2488                            BeginPolyline();
2489                        }
2490                        PlaceVertex(X, Y, Z);
2491                        ++n_x;
2492                    }
2493                }
2494                if (in_line) {
2495                    EndPolyline();
2496                }
2497            }
2498            SetAlpha(1.0);
2499            printf("%d DEM points drawn\n", n_x);
2500            break;
2501        }
2502        default:
2503            assert(false);
2504            break;
2505    }
2506}
2507
2508void GfxCore::ToggleSmoothShading()
2509{
2510    GLACanvas::ToggleSmoothShading();
2511    InvalidateList(LIST_TUBES);
2512    ForceRefresh();
2513}
2514
2515void GfxCore::GenerateDisplayList()
2516{
2517    // Generate the display list for the underground legs.
2518    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2519    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2520
2521    if (m_Splays == SPLAYS_SHOW_FADED) {
2522        SetAlpha(0.4);
2523        while (trav != tend) {
2524            if ((*trav).isSplay)
2525                (this->*AddPoly)(*trav);
2526            ++trav;
2527        }
2528        SetAlpha(1.0);
2529        trav = m_Parent->traverses_begin();
2530    }
2531
2532    while (trav != tend) {
2533        if (m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
2534            (this->*AddPoly)(*trav);
2535        ++trav;
2536    }
2537}
2538
2539void GfxCore::GenerateDisplayListTubes()
2540{
2541    // Generate the display list for the tubes.
2542    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2543    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2544    while (trav != tend) {
2545        SkinPassage(*trav);
2546        ++trav;
2547    }
2548}
2549
2550void GfxCore::GenerateDisplayListSurface()
2551{
2552    // Generate the display list for the surface legs.
2553    EnableDashedLines();
2554    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2555    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2556    while (trav != tend) {
2557        if (m_ColourBy == COLOUR_BY_ERROR) {
2558            AddPolylineError(*trav);
2559        } else {
2560            AddPolyline(*trav);
2561        }
2562        ++trav;
2563    }
2564    DisableDashedLines();
2565}
2566
2567void GfxCore::GenerateDisplayListShadow()
2568{
2569    SetColour(col_BLACK);
2570    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2571    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2572    while (trav != tend) {
2573        AddPolylineShadow(*trav);
2574        ++trav;
2575    }
2576}
2577
2578// Plot blobs.
2579void GfxCore::GenerateBlobsDisplayList()
2580{
2581    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2582          m_Parent->GetNumHighlightedPts()))
2583        return;
2584
2585    // Plot blobs.
2586    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2587    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2588    BeginBlobs();
2589    while (pos != m_Parent->GetLabelsEnd()) {
2590        const LabelInfo* label = *pos++;
2591
2592        // When more than one flag is set on a point:
2593        // search results take priority over entrance highlighting
2594        // which takes priority over fixed point
2595        // highlighting, which in turn takes priority over exported
2596        // point highlighting.
2597
2598        if (!((m_Surface && label->IsSurface()) ||
2599              (m_Legs && label->IsUnderground()) ||
2600              (!label->IsSurface() && !label->IsUnderground()))) {
2601            // if this station isn't to be displayed, skip to the next
2602            // (last case is for stns with no legs attached)
2603            continue;
2604        }
2605
2606        gla_colour col;
2607
2608        if (label->IsHighLighted()) {
2609            col = col_YELLOW;
2610        } else if (m_Entrances && label->IsEntrance()) {
2611            col = col_GREEN;
2612        } else if (m_FixedPts && label->IsFixedPt()) {
2613            col = col_RED;
2614        } else if (m_ExportedPts && label->IsExportedPt()) {
2615            col = col_TURQUOISE;
2616        } else {
2617            continue;
2618        }
2619
2620        // Stations are sorted by blob type, so colour changes are infrequent.
2621        if (col != prev_col) {
2622            SetColour(col);
2623            prev_col = col;
2624        }
2625        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2626    }
2627    EndBlobs();
2628}
2629
2630void GfxCore::DrawIndicators()
2631{
2632    // Draw colour key.
2633    if (m_ColourKey) {
2634        drawing_list key_list = LIST_LIMIT_;
2635        switch (m_ColourBy) {
2636            case COLOUR_BY_DEPTH:
2637                key_list = LIST_DEPTH_KEY; break;
2638            case COLOUR_BY_DATE:
2639                key_list = LIST_DATE_KEY; break;
2640            case COLOUR_BY_ERROR:
2641                key_list = LIST_ERROR_KEY; break;
2642            case COLOUR_BY_GRADIENT:
2643                key_list = LIST_GRADIENT_KEY; break;
2644            case COLOUR_BY_LENGTH:
2645                key_list = LIST_LENGTH_KEY; break;
2646        }
2647        if (key_list != LIST_LIMIT_) {
2648            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
2649                       GetYSize() - KEY_OFFSET_Y, 0);
2650        }
2651    }
2652
2653    // Draw compass or elevation/heading indicators.
2654    if (m_Compass || m_Clino) {
2655        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2656    }
2657
2658    // Draw scalebar.
2659    if (m_Scalebar) {
2660        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2661    }
2662}
2663
2664void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2665                                    glaTexCoord tex_x, glaTexCoord tex_y,
2666                                    Double factor)
2667{
2668    SetColour(col_WHITE, factor);
2669    PlaceVertex(v, tex_x, tex_y);
2670}
2671
2672void GfxCore::SetDepthColour(Double z, Double factor) {
2673    // Set the drawing colour based on the altitude.
2674    Double z_ext = m_Parent->GetDepthExtent();
2675
2676    z -= m_Parent->GetDepthMin();
2677    // points arising from tubes may be slightly outside the limits...
2678    if (z < 0) z = 0;
2679    if (z > z_ext) z = z_ext;
2680
2681    if (z == 0) {
2682        SetColour(GetPen(0), factor);
2683        return;
2684    }
2685
2686    assert(z_ext > 0.0);
2687    Double how_far = z / z_ext;
2688    assert(how_far >= 0.0);
2689    assert(how_far <= 1.0);
2690
2691    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2692    GLAPen pen1 = GetPen(band);
2693    if (band < GetNumColourBands() - 1) {
2694        const GLAPen& pen2 = GetPen(band + 1);
2695
2696        Double interval = z_ext / (GetNumColourBands() - 1);
2697        Double into_band = z / interval - band;
2698
2699//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2700//             z_offset, interval, band);
2701        // FIXME: why do we need to clamp here?  Is it because the walls can
2702        // extend further up/down than the centre-line?
2703        if (into_band < 0.0) into_band = 0.0;
2704        if (into_band > 1.0) into_band = 1.0;
2705        assert(into_band >= 0.0);
2706        assert(into_band <= 1.0);
2707
2708        pen1.Interpolate(pen2, into_band);
2709    }
2710    SetColour(pen1, factor);
2711}
2712
2713void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2714{
2715    SetDepthColour(v.GetZ(), factor);
2716    PlaceVertex(v);
2717}
2718
2719void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2720                                         glaTexCoord tex_x, glaTexCoord tex_y,
2721                                         Double factor)
2722{
2723    SetDepthColour(v.GetZ(), factor);
2724    PlaceVertex(v, tex_x, tex_y);
2725}
2726
2727void GfxCore::SplitLineAcrossBands(int band, int band2,
2728                                   const Vector3 &p, const Vector3 &q,
2729                                   Double factor)
2730{
2731    const int step = (band < band2) ? 1 : -1;
2732    for (int i = band; i != band2; i += step) {
2733        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2734
2735        // Find the intersection point of the line p -> q
2736        // with the plane parallel to the xy-plane with z-axis intersection z.
2737        assert(q.GetZ() - p.GetZ() != 0.0);
2738
2739        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2740//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2741
2742        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2743        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2744
2745        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2746    }
2747}
2748
2749int GfxCore::GetDepthColour(Double z) const
2750{
2751    // Return the (0-based) depth colour band index for a z-coordinate.
2752    Double z_ext = m_Parent->GetDepthExtent();
2753    z -= m_Parent->GetDepthMin();
2754    // We seem to get rounding differences causing z to sometimes be slightly
2755    // less than GetDepthMin() here, and it can certainly be true for passage
2756    // tubes, so just clamp the value to 0.
2757    if (z <= 0) return 0;
2758    // We seem to get rounding differences causing z to sometimes exceed z_ext
2759    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2760    // can certainly be true for passage tubes, so just clamp the value.
2761    if (z >= z_ext) return GetNumColourBands() - 1;
2762    return int(z / z_ext * (GetNumColourBands() - 1));
2763}
2764
2765Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2766{
2767    // Return the z-coordinate of the depth colour boundary between
2768    // two adjacent depth colour bands (specified by 0-based indices).
2769
2770    assert((a == b - 1) || (a == b + 1));
2771    if (GetNumColourBands() == 1) return 0;
2772
2773    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2774    Double z_ext = m_Parent->GetDepthExtent();
2775    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
2776}
2777
2778void GfxCore::AddPolyline(const traverse & centreline)
2779{
2780    BeginPolyline();
2781    SetColour(col_WHITE);
2782    vector<PointInfo>::const_iterator i = centreline.begin();
2783    PlaceVertex(*i);
2784    ++i;
2785    while (i != centreline.end()) {
2786        PlaceVertex(*i);
2787        ++i;
2788    }
2789    EndPolyline();
2790}
2791
2792void GfxCore::AddPolylineShadow(const traverse & centreline)
2793{
2794    BeginPolyline();
2795    const double z = -0.5 * m_Parent->GetZExtent();
2796    vector<PointInfo>::const_iterator i = centreline.begin();
2797    PlaceVertex(i->GetX(), i->GetY(), z);
2798    ++i;
2799    while (i != centreline.end()) {
2800        PlaceVertex(i->GetX(), i->GetY(), z);
2801        ++i;
2802    }
2803    EndPolyline();
2804}
2805
2806void GfxCore::AddPolylineDepth(const traverse & centreline)
2807{
2808    BeginPolyline();
2809    vector<PointInfo>::const_iterator i, prev_i;
2810    i = centreline.begin();
2811    int band0 = GetDepthColour(i->GetZ());
2812    PlaceVertexWithDepthColour(*i);
2813    prev_i = i;
2814    ++i;
2815    while (i != centreline.end()) {
2816        int band = GetDepthColour(i->GetZ());
2817        if (band != band0) {
2818            SplitLineAcrossBands(band0, band, *prev_i, *i);
2819            band0 = band;
2820        }
2821        PlaceVertexWithDepthColour(*i);
2822        prev_i = i;
2823        ++i;
2824    }
2825    EndPolyline();
2826}
2827
2828void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
2829                               const Vector3 &c, const Vector3 &d)
2830{
2831    Vector3 normal = (a - c) * (d - b);
2832    normal.normalise();
2833    Double factor = dot(normal, light) * .3 + .7;
2834    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2835    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2836    // FIXME: should plot triangles instead to avoid rendering glitches.
2837    BeginQuadrilaterals();
2838    PlaceVertexWithColour(a, 0, 0, factor);
2839    PlaceVertexWithColour(b, w, 0, factor);
2840    PlaceVertexWithColour(c, w, h, factor);
2841    PlaceVertexWithColour(d, 0, h, factor);
2842    EndQuadrilaterals();
2843}
2844
2845void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2846                                    const Vector3 &c, const Vector3 &d)
2847{
2848    Vector3 normal = (a - c) * (d - b);
2849    normal.normalise();
2850    Double factor = dot(normal, light) * .3 + .7;
2851    int a_band, b_band, c_band, d_band;
2852    a_band = GetDepthColour(a.GetZ());
2853    a_band = min(max(a_band, 0), GetNumColourBands());
2854    b_band = GetDepthColour(b.GetZ());
2855    b_band = min(max(b_band, 0), GetNumColourBands());
2856    c_band = GetDepthColour(c.GetZ());
2857    c_band = min(max(c_band, 0), GetNumColourBands());
2858    d_band = GetDepthColour(d.GetZ());
2859    d_band = min(max(d_band, 0), GetNumColourBands());
2860    // All this splitting is incorrect - we need to make a separate polygon
2861    // for each depth band...
2862    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2863    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2864    BeginPolygon();
2865////    PlaceNormal(normal);
2866    PlaceVertexWithDepthColour(a, 0, 0, factor);
2867    if (a_band != b_band) {
2868        SplitLineAcrossBands(a_band, b_band, a, b, factor);
2869    }
2870    PlaceVertexWithDepthColour(b, w, 0, factor);
2871    if (b_band != c_band) {
2872        SplitLineAcrossBands(b_band, c_band, b, c, factor);
2873    }
2874    PlaceVertexWithDepthColour(c, w, h, factor);
2875    if (c_band != d_band) {
2876        SplitLineAcrossBands(c_band, d_band, c, d, factor);
2877    }
2878    PlaceVertexWithDepthColour(d, 0, h, factor);
2879    if (d_band != a_band) {
2880        SplitLineAcrossBands(d_band, a_band, d, a, factor);
2881    }
2882    EndPolygon();
2883}
2884
2885void GfxCore::SetColourFromDate(int date, Double factor)
2886{
2887    // Set the drawing colour based on a date.
2888
2889    if (date == -1) {
2890        // Undated.
2891        SetColour(col_WHITE, factor);
2892        return;
2893    }
2894
2895    int date_offset = date - m_Parent->GetDateMin();
2896    if (date_offset == 0) {
2897        // Earliest date - handle as a special case for the single date case.
2898        SetColour(GetPen(0), factor);
2899        return;
2900    }
2901
2902    int date_ext = m_Parent->GetDateExtent();
2903    Double how_far = (Double)date_offset / date_ext;
2904    assert(how_far >= 0.0);
2905    assert(how_far <= 1.0);
2906    SetColourFrom01(how_far, factor);
2907}
2908
2909void GfxCore::AddPolylineDate(const traverse & centreline)
2910{
2911    BeginPolyline();
2912    vector<PointInfo>::const_iterator i, prev_i;
2913    i = centreline.begin();
2914    int date = i->GetDate();
2915    SetColourFromDate(date, 1.0);
2916    PlaceVertex(*i);
2917    prev_i = i;
2918    while (++i != centreline.end()) {
2919        int newdate = i->GetDate();
2920        if (newdate != date) {
2921            EndPolyline();
2922            BeginPolyline();
2923            date = newdate;
2924            SetColourFromDate(date, 1.0);
2925            PlaceVertex(*prev_i);
2926        }
2927        PlaceVertex(*i);
2928        prev_i = i;
2929    }
2930    EndPolyline();
2931}
2932
2933static int static_date_hack; // FIXME
2934
2935void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2936                                   const Vector3 &c, const Vector3 &d)
2937{
2938    Vector3 normal = (a - c) * (d - b);
2939    normal.normalise();
2940    Double factor = dot(normal, light) * .3 + .7;
2941    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2942    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2943    // FIXME: should plot triangles instead to avoid rendering glitches.
2944    BeginQuadrilaterals();
2945////    PlaceNormal(normal);
2946    SetColourFromDate(static_date_hack, factor);
2947    PlaceVertex(a, 0, 0);
2948    PlaceVertex(b, w, 0);
2949    PlaceVertex(c, w, h);
2950    PlaceVertex(d, 0, h);
2951    EndQuadrilaterals();
2952}
2953
2954static double static_E_hack; // FIXME
2955
2956void GfxCore::SetColourFromError(double E, Double factor)
2957{
2958    // Set the drawing colour based on an error value.
2959
2960    if (E < 0) {
2961        SetColour(col_WHITE, factor);
2962        return;
2963    }
2964
2965    Double how_far = E / MAX_ERROR;
2966    assert(how_far >= 0.0);
2967    if (how_far > 1.0) how_far = 1.0;
2968    SetColourFrom01(how_far, factor);
2969}
2970
2971void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2972                                    const Vector3 &c, const Vector3 &d)
2973{
2974    Vector3 normal = (a - c) * (d - b);
2975    normal.normalise();
2976    Double factor = dot(normal, light) * .3 + .7;
2977    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2978    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2979    // FIXME: should plot triangles instead to avoid rendering glitches.
2980    BeginQuadrilaterals();
2981////    PlaceNormal(normal);
2982    SetColourFromError(static_E_hack, factor);
2983    PlaceVertex(a, 0, 0);
2984    PlaceVertex(b, w, 0);
2985    PlaceVertex(c, w, h);
2986    PlaceVertex(d, 0, h);
2987    EndQuadrilaterals();
2988}
2989
2990void GfxCore::AddPolylineError(const traverse & centreline)
2991{
2992    BeginPolyline();
2993    SetColourFromError(centreline.E, 1.0);
2994    vector<PointInfo>::const_iterator i;
2995    for(i = centreline.begin(); i != centreline.end(); ++i) {
2996        PlaceVertex(*i);
2997    }
2998    EndPolyline();
2999}
3000
3001// gradient is in *radians*.
3002void GfxCore::SetColourFromGradient(double gradient, Double factor)
3003{
3004    // Set the drawing colour based on the gradient of the leg.
3005
3006    const Double GRADIENT_MAX = M_PI_2;
3007    gradient = fabs(gradient);
3008    Double how_far = gradient / GRADIENT_MAX;
3009    SetColourFrom01(how_far, factor);
3010}
3011
3012void GfxCore::AddPolylineGradient(const traverse & centreline)
3013{
3014    vector<PointInfo>::const_iterator i, prev_i;
3015    i = centreline.begin();
3016    prev_i = i;
3017    while (++i != centreline.end()) {
3018        BeginPolyline();
3019        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3020        PlaceVertex(*prev_i);
3021        PlaceVertex(*i);
3022        prev_i = i;
3023        EndPolyline();
3024    }
3025}
3026
3027static double static_gradient_hack; // FIXME
3028
3029void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3030                                       const Vector3 &c, const Vector3 &d)
3031{
3032    Vector3 normal = (a - c) * (d - b);
3033    normal.normalise();
3034    Double factor = dot(normal, light) * .3 + .7;
3035    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3036    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3037    // FIXME: should plot triangles instead to avoid rendering glitches.
3038    BeginQuadrilaterals();
3039////    PlaceNormal(normal);
3040    SetColourFromGradient(static_gradient_hack, factor);
3041    PlaceVertex(a, 0, 0);
3042    PlaceVertex(b, w, 0);
3043    PlaceVertex(c, w, h);
3044    PlaceVertex(d, 0, h);
3045    EndQuadrilaterals();
3046}
3047
3048void GfxCore::SetColourFromLength(double length, Double factor)
3049{
3050    // Set the drawing colour based on log(length_of_leg).
3051
3052    Double log_len = log10(length);
3053    Double how_far = log_len / LOG_LEN_MAX;
3054    how_far = max(how_far, 0.0);
3055    how_far = min(how_far, 1.0);
3056    SetColourFrom01(how_far, factor);
3057}
3058
3059void GfxCore::SetColourFrom01(double how_far, Double factor)
3060{
3061    double b;
3062    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3063    int band(b);
3064    GLAPen pen1 = GetPen(band);
3065    // With 24bit colour, interpolating by less than this can have no effect.
3066    if (into_band >= 1.0 / 512.0) {
3067        const GLAPen& pen2 = GetPen(band + 1);
3068        pen1.Interpolate(pen2, into_band);
3069    }
3070    SetColour(pen1, factor);
3071}
3072
3073void GfxCore::AddPolylineLength(const traverse & centreline)
3074{
3075    vector<PointInfo>::const_iterator i, prev_i;
3076    i = centreline.begin();
3077    prev_i = i;
3078    while (++i != centreline.end()) {
3079        BeginPolyline();
3080        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3081        PlaceVertex(*prev_i);
3082        PlaceVertex(*i);
3083        prev_i = i;
3084        EndPolyline();
3085    }
3086}
3087
3088static double static_length_hack; // FIXME
3089
3090void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3091                                     const Vector3 &c, const Vector3 &d)
3092{
3093    Vector3 normal = (a - c) * (d - b);
3094    normal.normalise();
3095    Double factor = dot(normal, light) * .3 + .7;
3096    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3097    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3098    // FIXME: should plot triangles instead to avoid rendering glitches.
3099    BeginQuadrilaterals();
3100////    PlaceNormal(normal);
3101    SetColourFromLength(static_length_hack, factor);
3102    PlaceVertex(a, 0, 0);
3103    PlaceVertex(b, w, 0);
3104    PlaceVertex(c, w, h);
3105    PlaceVertex(d, 0, h);
3106    EndQuadrilaterals();
3107}
3108
3109void
3110GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3111{
3112    assert(centreline.size() > 1);
3113    Vector3 U[4];
3114    XSect prev_pt_v;
3115    Vector3 last_right(1.0, 0.0, 0.0);
3116
3117//  FIXME: it's not simple to set the colour of a tube based on error...
3118//    static_E_hack = something...
3119    vector<XSect>::iterator i = centreline.begin();
3120    vector<XSect>::size_type segment = 0;
3121    while (i != centreline.end()) {
3122        // get the coordinates of this vertex
3123        XSect & pt_v = *i++;
3124
3125        double z_pitch_adjust = 0.0;
3126        bool cover_end = false;
3127
3128        Vector3 right, up;
3129
3130        const Vector3 up_v(0.0, 0.0, 1.0);
3131
3132        if (segment == 0) {
3133            assert(i != centreline.end());
3134            // first segment
3135
3136            // get the coordinates of the next vertex
3137            const XSect & next_pt_v = *i;
3138
3139            // calculate vector from this pt to the next one
3140            Vector3 leg_v = next_pt_v - pt_v;
3141
3142            // obtain a vector in the LRUD plane
3143            right = leg_v * up_v;
3144            if (right.magnitude() == 0) {
3145                right = last_right;
3146                // Obtain a second vector in the LRUD plane,
3147                // perpendicular to the first.
3148                //up = right * leg_v;
3149                up = up_v;
3150            } else {
3151                last_right = right;
3152                up = up_v;
3153            }
3154
3155            cover_end = true;
3156            static_date_hack = next_pt_v.GetDate();
3157        } else if (segment + 1 == centreline.size()) {
3158            // last segment
3159
3160            // Calculate vector from the previous pt to this one.
3161            Vector3 leg_v = pt_v - prev_pt_v;
3162
3163            // Obtain a horizontal vector in the LRUD plane.
3164            right = leg_v * up_v;
3165            if (right.magnitude() == 0) {
3166                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3167                // Obtain a second vector in the LRUD plane,
3168                // perpendicular to the first.
3169                //up = right * leg_v;
3170                up = up_v;
3171            } else {
3172                last_right = right;
3173                up = up_v;
3174            }
3175
3176            cover_end = true;
3177            static_date_hack = pt_v.GetDate();
3178        } else {
3179            assert(i != centreline.end());
3180            // Intermediate segment.
3181
3182            // Get the coordinates of the next vertex.
3183            const XSect & next_pt_v = *i;
3184
3185            // Calculate vectors from this vertex to the
3186            // next vertex, and from the previous vertex to
3187            // this one.
3188            Vector3 leg1_v = pt_v - prev_pt_v;
3189            Vector3 leg2_v = next_pt_v - pt_v;
3190
3191            // Obtain horizontal vectors perpendicular to
3192            // both legs, then normalise and average to get
3193            // a horizontal bisector.
3194            Vector3 r1 = leg1_v * up_v;
3195            Vector3 r2 = leg2_v * up_v;
3196            r1.normalise();
3197            r2.normalise();
3198            right = r1 + r2;
3199            if (right.magnitude() == 0) {
3200                // This is the "mid-pitch" case...
3201                right = last_right;
3202            }
3203            if (r1.magnitude() == 0) {
3204                Vector3 n = leg1_v;
3205                n.normalise();
3206                z_pitch_adjust = n.GetZ();
3207                //up = Vector3(0, 0, leg1_v.GetZ());
3208                //up = right * up;
3209                up = up_v;
3210
3211                // Rotate pitch section to minimise the
3212                // "tortional stress" - FIXME: use
3213                // triangles instead of rectangles?
3214                int shift = 0;
3215                Double maxdotp = 0;
3216
3217                // Scale to unit vectors in the LRUD plane.
3218                right.normalise();
3219                up.normalise();
3220                Vector3 vec = up - right;
3221                for (int orient = 0; orient <= 3; ++orient) {
3222                    Vector3 tmp = U[orient] - prev_pt_v;
3223                    tmp.normalise();
3224                    Double dotp = dot(vec, tmp);
3225                    if (dotp > maxdotp) {
3226                        maxdotp = dotp;
3227                        shift = orient;
3228                    }
3229                }
3230                if (shift) {
3231                    if (shift != 2) {
3232                        Vector3 temp(U[0]);
3233                        U[0] = U[shift];
3234                        U[shift] = U[2];
3235                        U[2] = U[shift ^ 2];
3236                        U[shift ^ 2] = temp;
3237                    } else {
3238                        swap(U[0], U[2]);
3239                        swap(U[1], U[3]);
3240                    }
3241                }
3242#if 0
3243                // Check that the above code actually permuted
3244                // the vertices correctly.
3245                shift = 0;
3246                maxdotp = 0;
3247                for (int j = 0; j <= 3; ++j) {
3248                    Vector3 tmp = U[j] - prev_pt_v;
3249                    tmp.normalise();
3250                    Double dotp = dot(vec, tmp);
3251                    if (dotp > maxdotp) {
3252                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3253                        shift = j;
3254                    }
3255                }
3256                if (shift) {
3257                    printf("New shift = %d!\n", shift);
3258                    shift = 0;
3259                    maxdotp = 0;
3260                    for (int j = 0; j <= 3; ++j) {
3261                        Vector3 tmp = U[j] - prev_pt_v;
3262                        tmp.normalise();
3263                        Double dotp = dot(vec, tmp);
3264                        printf("    %d : %.8f\n", j, dotp);
3265                    }
3266                }
3267#endif
3268            } else if (r2.magnitude() == 0) {
3269                Vector3 n = leg2_v;
3270                n.normalise();
3271                z_pitch_adjust = n.GetZ();
3272                //up = Vector3(0, 0, leg2_v.GetZ());
3273                //up = right * up;
3274                up = up_v;
3275            } else {
3276                up = up_v;
3277            }
3278            last_right = right;
3279            static_date_hack = pt_v.GetDate();
3280        }
3281
3282        // Scale to unit vectors in the LRUD plane.
3283        right.normalise();
3284        up.normalise();
3285
3286        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
3287
3288        Double l = fabs(pt_v.GetL());
3289        Double r = fabs(pt_v.GetR());
3290        Double u = fabs(pt_v.GetU());
3291        Double d = fabs(pt_v.GetD());
3292
3293        // Produce coordinates of the corners of the LRUD "plane".
3294        Vector3 v[4];
3295        v[0] = pt_v - right * l + up * u;
3296        v[1] = pt_v + right * r + up * u;
3297        v[2] = pt_v + right * r - up * d;
3298        v[3] = pt_v - right * l - up * d;
3299
3300        if (draw) {
3301            const Vector3 & delta = pt_v - prev_pt_v;
3302            static_length_hack = delta.magnitude();
3303            static_gradient_hack = delta.gradient();
3304            if (segment > 0) {
3305                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3306                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3307                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3308                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3309            }
3310
3311            if (cover_end) {
3312                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3313            }
3314        }
3315
3316        prev_pt_v = pt_v;
3317        U[0] = v[0];
3318        U[1] = v[1];
3319        U[2] = v[2];
3320        U[3] = v[3];
3321
3322        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3323
3324        ++segment;
3325    }
3326}
3327
3328void GfxCore::FullScreenMode()
3329{
3330    m_Parent->ViewFullScreen();
3331}
3332
3333bool GfxCore::IsFullScreen() const
3334{
3335    return m_Parent->IsFullScreen();
3336}
3337
3338bool GfxCore::FullScreenModeShowingMenus() const
3339{
3340    return m_Parent->FullScreenModeShowingMenus();
3341}
3342
3343void GfxCore::FullScreenModeShowMenus(bool show)
3344{
3345    m_Parent->FullScreenModeShowMenus(show);
3346}
3347
3348void
3349GfxCore::MoveViewer(double forward, double up, double right)
3350{
3351    double cT = cos(rad(m_TiltAngle));
3352    double sT = sin(rad(m_TiltAngle));
3353    double cP = cos(rad(m_PanAngle));
3354    double sP = sin(rad(m_PanAngle));
3355    Vector3 v_forward(cT * sP, cT * cP, sT);
3356    Vector3 v_up(sT * sP, sT * cP, -cT);
3357    Vector3 v_right(-cP, sP, 0);
3358    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3359    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3360    assert(fabs(dot(v_right, v_up)) < 1e-6);
3361    Vector3 move = v_forward * forward + v_up * up + v_right * right;
3362    AddTranslation(-move);
3363    // Show current position.
3364    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3365    ForceRefresh();
3366}
3367
3368PresentationMark GfxCore::GetView() const
3369{
3370    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3371                            m_PanAngle, -m_TiltAngle, m_Scale);
3372}
3373
3374void GfxCore::SetView(const PresentationMark & p)
3375{
3376    m_SwitchingTo = 0;
3377    SetTranslation(p - m_Parent->GetOffset());
3378    m_PanAngle = p.angle;
3379    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3380    SetRotation(m_PanAngle, m_TiltAngle);
3381    SetScale(p.scale);
3382    ForceRefresh();
3383}
3384
3385void GfxCore::PlayPres(double speed, bool change_speed) {
3386    if (!change_speed || presentation_mode == 0) {
3387        if (speed == 0.0) {
3388            presentation_mode = 0;
3389            return;
3390        }
3391        presentation_mode = PLAYING;
3392        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3393        SetView(next_mark);
3394        next_mark_time = 0; // There already!
3395        this_mark_total = 0;
3396        pres_reverse = (speed < 0);
3397    }
3398
3399    if (change_speed) pres_speed = speed;
3400
3401    if (speed != 0.0) {
3402        bool new_pres_reverse = (speed < 0);
3403        if (new_pres_reverse != pres_reverse) {
3404            pres_reverse = new_pres_reverse;
3405            if (pres_reverse) {
3406                next_mark = m_Parent->GetPresMark(MARK_PREV);
3407            } else {
3408                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3409            }
3410            swap(this_mark_total, next_mark_time);
3411        }
3412    }
3413}
3414
3415void GfxCore::SetColourBy(int colour_by) {
3416    m_ColourBy = colour_by;
3417    switch (colour_by) {
3418        case COLOUR_BY_DEPTH:
3419            AddQuad = &GfxCore::AddQuadrilateralDepth;
3420            AddPoly = &GfxCore::AddPolylineDepth;
3421            break;
3422        case COLOUR_BY_DATE:
3423            AddQuad = &GfxCore::AddQuadrilateralDate;
3424            AddPoly = &GfxCore::AddPolylineDate;
3425            break;
3426        case COLOUR_BY_ERROR:
3427            AddQuad = &GfxCore::AddQuadrilateralError;
3428            AddPoly = &GfxCore::AddPolylineError;
3429            break;
3430        case COLOUR_BY_GRADIENT:
3431            AddQuad = &GfxCore::AddQuadrilateralGradient;
3432            AddPoly = &GfxCore::AddPolylineGradient;
3433            break;
3434        case COLOUR_BY_LENGTH:
3435            AddQuad = &GfxCore::AddQuadrilateralLength;
3436            AddPoly = &GfxCore::AddPolylineLength;
3437            break;
3438        default: // case COLOUR_BY_NONE:
3439            AddQuad = &GfxCore::AddQuadrilateral;
3440            AddPoly = &GfxCore::AddPolyline;
3441            break;
3442    }
3443
3444    InvalidateList(LIST_UNDERGROUND_LEGS);
3445    InvalidateList(LIST_SURFACE_LEGS);
3446    InvalidateList(LIST_TUBES);
3447
3448    ForceRefresh();
3449}
3450
3451bool GfxCore::ExportMovie(const wxString & fnm)
3452{
3453    int width;
3454    int height;
3455    GetSize(&width, &height);
3456    // Round up to next multiple of 2 (required by ffmpeg).
3457    width += (width & 1);
3458    height += (height & 1);
3459
3460    movie = new MovieMaker();
3461
3462    // FIXME: This should really use fn_str() - currently we probably can't
3463    // save to a Unicode path on wxmsw.
3464    if (!movie->Open(fnm.mb_str(), width, height)) {
3465        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3466        delete movie;
3467        movie = NULL;
3468        return false;
3469    }
3470
3471    PlayPres(1);
3472    return true;
3473}
3474
3475void
3476GfxCore::OnPrint(const wxString &filename, const wxString &title,
3477                 const wxString &datestamp, time_t datestamp_numeric,
3478                 const wxString &cs_proj,
3479                 bool close_after_print)
3480{
3481    svxPrintDlg * p;
3482    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3483                        datestamp, datestamp_numeric,
3484                        m_PanAngle, m_TiltAngle,
3485                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3486                        m_Entrances, m_FixedPts, m_ExportedPts,
3487                        true, close_after_print);
3488    p->Show(true);
3489}
3490
3491void
3492GfxCore::OnExport(const wxString &filename, const wxString &title,
3493                  const wxString &datestamp, time_t datestamp_numeric,
3494                  const wxString &cs_proj)
3495{
3496    // Fill in "right_bearing" for each cross-section.
3497    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3498    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3499    while (trav != tend) {
3500        SkinPassage(*trav, false);
3501        ++trav;
3502    }
3503
3504    svxPrintDlg * p;
3505    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3506                        datestamp, datestamp_numeric,
3507                        m_PanAngle, m_TiltAngle,
3508                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3509                        m_Entrances, m_FixedPts, m_ExportedPts,
3510                        false);
3511    p->Show(true);
3512}
3513
3514static wxCursor
3515make_cursor(const unsigned char * bits, const unsigned char * mask,
3516            int hotx, int hoty)
3517{
3518#if defined __WXMSW__ || defined __WXMAC__
3519# ifdef __WXMAC__
3520    // The default Mac cursor is black with a white edge, so
3521    // invert our custom cursors to match.
3522    char b[128];
3523    for (int i = 0; i < 128; ++i)
3524        b[i] = bits[i] ^ 0xff;
3525# else
3526    const char * b = reinterpret_cast<const char *>(bits);
3527# endif
3528    wxBitmap cursor_bitmap(b, 32, 32);
3529    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3530    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3531    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3532    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3533    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3534    return wxCursor(cursor_image);
3535#else
3536    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3537                    (const char *)mask, wxBLACK, wxWHITE);
3538#endif
3539}
3540
3541const
3542#include "hand.xbm"
3543const
3544#include "handmask.xbm"
3545
3546const
3547#include "brotate.xbm"
3548const
3549#include "brotatemask.xbm"
3550
3551const
3552#include "vrotate.xbm"
3553const
3554#include "vrotatemask.xbm"
3555
3556const
3557#include "rotate.xbm"
3558const
3559#include "rotatemask.xbm"
3560
3561const
3562#include "rotatezoom.xbm"
3563const
3564#include "rotatezoommask.xbm"
3565
3566void
3567GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
3568{
3569    // Check if we're already showing that cursor.
3570    if (current_cursor == new_cursor) return;
3571
3572    current_cursor = new_cursor;
3573    switch (current_cursor) {
3574        case GfxCore::CURSOR_DEFAULT:
3575            GLACanvas::SetCursor(wxNullCursor);
3576            break;
3577        case GfxCore::CURSOR_POINTING_HAND:
3578            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3579            break;
3580        case GfxCore::CURSOR_DRAGGING_HAND:
3581            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3582            break;
3583        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3584            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3585            break;
3586        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3587            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3588            break;
3589        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3590            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3591            break;
3592        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3593            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3594            break;
3595        case GfxCore::CURSOR_ZOOM:
3596            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3597            break;
3598        case GfxCore::CURSOR_ZOOM_ROTATE:
3599            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3600            break;
3601    }
3602}
3603
3604bool GfxCore::MeasuringLineActive() const
3605{
3606    if (Animating()) return false;
3607    return HereIsReal() || m_there;
3608}
3609
3610bool GfxCore::HandleRClick(wxPoint point)
3611{
3612    if (PointWithinCompass(point)) {
3613        // Pop up menu.
3614        wxMenu menu;
3615        /* TRANSLATORS: View *looking* North */
3616        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3617        /* TRANSLATORS: View *looking* East */
3618        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3619        /* TRANSLATORS: View *looking* South */
3620        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3621        /* TRANSLATORS: View *looking* West */
3622        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3623        menu.AppendSeparator();
3624        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
3625        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
3626        /* TRANSLATORS: tickable menu item in View menu.
3627         *
3628         * Degrees are the angular measurement where there are 360 in a full
3629         * circle. */
3630        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3631        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3632        PopupMenu(&menu);
3633        return true;
3634    }
3635
3636    if (PointWithinClino(point)) {
3637        // Pop up menu.
3638        wxMenu menu;
3639        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3640        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3641        menu.AppendSeparator();
3642        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
3643        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3644        /* TRANSLATORS: tickable menu item in View menu.
3645         *
3646         * Degrees are the angular measurement where there are 360 in a full
3647         * circle. */
3648        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3649        /* TRANSLATORS: tickable menu item in View menu.
3650         *
3651         * Show the tilt of the survey as a percentage gradient (100% = 45
3652         * degrees = 50 grad). */
3653        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
3654        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3655        PopupMenu(&menu);
3656        return true;
3657    }
3658
3659    if (PointWithinScaleBar(point)) {
3660        // Pop up menu.
3661        wxMenu menu;
3662        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
3663        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3664        /* TRANSLATORS: tickable menu item in View menu.
3665         *
3666         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3667         */
3668        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3669        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3670        PopupMenu(&menu);
3671        return true;
3672    }
3673
3674    if (PointWithinColourKey(point)) {
3675        // Pop up menu.
3676        wxMenu menu;
3677        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3678        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3679        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
3680        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_GRADIENT, wmsg(/*Colour by Grad&ient*/85));
3681        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
3682        menu.AppendSeparator();
3683        /* TRANSLATORS: Menu item which turns off the colour key.
3684         * The "Colour Key" is the thing in aven showing which colour
3685         * corresponds to which depth, date, survey closure error, etc. */
3686        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3687        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
3688            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3689        else if (m_ColourBy == COLOUR_BY_GRADIENT)
3690            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3691        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3692        PopupMenu(&menu);
3693        return true;
3694    }
3695
3696    return false;
3697}
3698
3699void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3700{
3701    if (centred) {
3702        p1.x = p2.x + (p1.x - p2.x) * 2;
3703        p1.y = p2.y + (p1.y - p2.y) * 2;
3704    }
3705    if (aspect) {
3706#if 0 // FIXME: This needs more work.
3707        int sx = GetXSize();
3708        int sy = GetYSize();
3709        int dx = p1.x - p2.x;
3710        int dy = p1.y - p2.y;
3711        int dy_new = dx * sy / sx;
3712        if (abs(dy_new) >= abs(dy)) {
3713            p1.y += (dy_new - dy) / 2;
3714            p2.y -= (dy_new - dy) / 2;
3715        } else {
3716            int dx_new = dy * sx / sy;
3717            p1.x += (dx_new - dx) / 2;
3718            p2.x -= (dx_new - dx) / 2;
3719        }
3720#endif
3721    }
3722    zoombox.set(p1, p2);
3723    ForceRefresh();
3724}
3725
3726void GfxCore::ZoomBoxGo()
3727{
3728    if (!zoombox.active()) return;
3729
3730    int width = GetXSize();
3731    int height = GetYSize();
3732
3733    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
3734                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
3735    int box_w = abs(zoombox.x1 - zoombox.x2);
3736    int box_h = abs(zoombox.y1 - zoombox.y2);
3737
3738    double factor = min(double(width) / box_w, double(height) / box_h);
3739
3740    zoombox.unset();
3741
3742    SetScale(GetScale() * factor);
3743}
Note: See TracBrowser for help on using the repository browser.