source: git/src/gfxcore.cc @ 9df33bc

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

src/gfxcore.cc,src/gfxcore.h: Add support for reading DEM data from
SRTM .hgt files.

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