source: git/src/gfxcore.cc @ 036c777

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 036c777 was 036c777, checked in by Olly Betts <olly@…>, 7 years ago

Disable texturing while drawing terrain

Previously the terrain got a bit darker when "Textured Walls" were
enabled.

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