source: git/src/gfxcore.cc @ f15ca67f

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since f15ca67f was 6e0c5879, checked in by Olly Betts <olly@…>, 14 years ago

src/gfxcore.cc,src/gfxcore.h: Update copyright years.

git-svn-id: file:///home/survex-svn/survex/trunk@3923 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 78.7 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
[6e0c5879]7//  Copyright (C) 2001-2003,2004,2005,2006,2007,2010,2011,2012 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"
[5809313]34#include "gfxcore.h"
[137bf99]35#include "mainfrm.h"
[93c3f97]36#include "message.h"
[7a89dc2]37#include "useful.h"
[ce403f1]38#include "printwx.h"
[5876fcb]39#include "guicontrol.h"
[6a4cdcb6]40#include "moviemaker.h"
[8000d8f]41
42#include <wx/confbase.h>
43#include <wx/image.h>
[5809313]44
[db4b33c]45#define MAX(a, b) ((a) > (b) ? (a) : (b))
[003d953]46#define MAX3(a, b, c) ((a) > (b) ? MAX(a, c) : MAX(b, c))
[5809313]47
[3d00693]48// Values for m_SwitchingTo
49#define PLAN 1
50#define ELEVATION 2
[3ddd351]51#define NORTH 3
52#define EAST 4
53#define SOUTH 5
54#define WEST 6
[3d00693]55
[c61aa79]56// Any error value higher than this is clamped to this.
57#define MAX_ERROR 12.0
58
[86cdcf2]59// How many bins per letter height to use when working out non-overlapping
60// labels.
61const unsigned int QUANTISE_FACTOR = 2;
62
[0e69efe]63#include "avenpal.h"
64
[6606406]65static const int COMPASS_OFFSET_X = 60;
66static const int COMPASS_OFFSET_Y = 80;
67static const int INDICATOR_BOX_SIZE = 60;
[c300a04]68static const int INDICATOR_GAP = 2;
[6606406]69static const int INDICATOR_MARGIN = 5;
70static const int INDICATOR_OFFSET_X = 15;
[c300a04]71static const int INDICATOR_OFFSET_Y = 15;
[fe665c4]72static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
[dde4fe7]73static const int CLINO_OFFSET_X = 6 + INDICATOR_OFFSET_X +
[429465a]74                                  INDICATOR_BOX_SIZE + INDICATOR_GAP;
[62da267]75static const int KEY_OFFSET_X = 10;
76static const int KEY_OFFSET_Y = 10;
77static const int KEY_EXTRA_LEFT_MARGIN = 2;
78static const int KEY_BLOCK_WIDTH = 20;
79static const int KEY_BLOCK_HEIGHT = 16;
[b56df45]80static const int TICK_LENGTH = 4;
[42adb19]81static const int SCALE_BAR_OFFSET_X = 15;
82static const int SCALE_BAR_OFFSET_Y = 12;
83static const int SCALE_BAR_HEIGHT = 12;
[aa048c3]84
85static const gla_colour TEXT_COLOUR = col_GREEN;
86static const gla_colour HERE_COLOUR = col_WHITE;
87static const gla_colour NAME_COLOUR = col_GREEN;
[33b2094]88
[39e460c9]89#define HITTEST_SIZE 20
90
[dde4fe7]91// vector for lighting angle
92static const Vector3 light(.577, .577, .577);
93
[c6d95d8]94BEGIN_EVENT_TABLE(GfxCore, wxGLCanvas)
[5809313]95    EVT_PAINT(GfxCore::OnPaint)
96    EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
97    EVT_LEFT_UP(GfxCore::OnLButtonUp)
98    EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
99    EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
100    EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
101    EVT_RIGHT_UP(GfxCore::OnRButtonUp)
[34d8d1a]102    EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
[5809313]103    EVT_MOTION(GfxCore::OnMouseMove)
[887c26e]104    EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
[5809313]105    EVT_SIZE(GfxCore::OnSize)
[a8e9fde]106    EVT_IDLE(GfxCore::OnIdle)
[4b1fc48]107    EVT_CHAR(GfxCore::OnKeyPress)
[5809313]108END_EVENT_TABLE()
109
[5876fcb]110GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
[88707e0b]111    GLACanvas(parent_win, 100),
112    m_Scale(0.0),
113    m_ScaleBarWidth(0),
114    m_Control(control),
115    m_LabelGrid(NULL),
116    m_Parent(parent),
117    m_DoneFirstShow(false),
118    m_TiltAngle(0.0),
119    m_PanAngle(0.0),
120    m_Rotating(false),
121    m_RotationStep(0.0),
122    m_SwitchingTo(0),
123    m_Crosses(false),
124    m_Legs(true),
125    m_Names(false),
126    m_Scalebar(true),
[97ea48d]127    m_ColourKey(true),
[88707e0b]128    m_OverlappingNames(false),
129    m_Compass(true),
130    m_Clino(true),
131    m_Tubes(false),
132    m_ColourBy(COLOUR_BY_DEPTH),
133    m_HaveData(false),
134    m_MouseOutsideCompass(false),
135    m_MouseOutsideElev(false),
136    m_Surface(false),
137    m_Entrances(false),
138    m_FixedPts(false),
139    m_ExportedPts(false),
140    m_Grid(false),
141    m_BoundingBox(false),
142    m_Degrees(false),
143    m_Metric(false),
144    m_HitTestGridValid(false),
145    m_here_is_temporary(false),
146    presentation_mode(0),
147    pres_reverse(false),
148    pres_speed(0.0),
[75d4a2b]149    movie(NULL),
[88707e0b]150    current_cursor(GfxCore::CURSOR_DEFAULT)
[5809313]151{
[da6c802]152    AddQuad = &GfxCore::AddQuadrilateralDepth;
153    AddPoly = &GfxCore::AddPolylineDepth;
[5627cbb]154    wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
155    wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
[d67450e]156    m_here.Invalidate();
157    m_there.Invalidate();
[5809313]158
[39e460c9]159    // Initialise grid for hit testing.
[fa42426]160    m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
[0e69efe]161
[97ea48d]162    m_Pens = new GLAPen[NUM_COLOUR_BANDS + 1];
163    for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
[0e69efe]164        m_Pens[pen].SetColour(REDS[pen] / 255.0,
165                              GREENS[pen] / 255.0,
166                              BLUES[pen] / 255.0);
167    }
[5809313]168}
169
170GfxCore::~GfxCore()
171{
172    TryToFreeArrays();
[156dc16]173
[0e69efe]174    delete[] m_Pens;
[39e460c9]175    delete[] m_PointGrid;
[5809313]176}
177
178void GfxCore::TryToFreeArrays()
179{
180    // Free up any memory allocated for arrays.
[81f1266]181    delete[] m_LabelGrid;
182    m_LabelGrid = NULL;
[5809313]183}
184
185//
186//  Initialisation methods
187//
188
[0c6bf5e8]189void GfxCore::Initialise(bool same_file)
[5809313]190{
191    // Initialise the view from the parent holding the survey data.
192
193    TryToFreeArrays();
194
[33b2094]195    m_DoneFirstShow = false;
196
[dfe4454c]197    m_HitTestGridValid = false;
[d35144d]198    m_here_is_temporary = true;
[d67450e]199    m_here.Invalidate();
200    m_there.Invalidate();
[dfe4454c]201
[d35144d]202    m_MouseOutsideCompass = m_MouseOutsideElev = false;
203
[0c6bf5e8]204    if (!same_file) {
205        // Apply default parameters unless reloading the same file.
206        DefaultParameters();
207
208        // Set the initial scale.
209        SetScale(1.0);
210    }
[9eb58d0]211
212    m_HaveData = true;
[936a197]213
214    ForceRefresh();
[9eb58d0]215}
216
217void GfxCore::FirstShow()
218{
219    GLACanvas::FirstShow();
220
[8bd480e]221    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
[86cdcf2]222    list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
223    while (pos != m_Parent->GetLabelsNCEnd()) {
224        LabelInfo* label = *pos++;
225        // Calculate and set the label width for use when plotting
226        // none-overlapping labels.
227        int ext_x;
228        GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
[5a24583]229        label->set_width(unsigned(ext_x) / quantise + 1);
[86cdcf2]230    }
231
[c5fc8eb]232    // Set diameter of the viewing volume.
233    SetVolumeDiameter(sqrt(sqrd(m_Parent->GetXExtent()) +
234                           sqrd(m_Parent->GetYExtent()) +
235                           sqrd(m_Parent->GetZExtent())));
[9eb58d0]236
[5809313]237    m_DoneFirstShow = true;
238}
239
240//
241//  Recalculating methods
242//
243
[cd6ea75]244void GfxCore::SetScale(Double scale)
[5047c53]245{
[8b0d57f]246    if (scale < 0.05) {
247        scale = 0.05;
[70acad9]248    } else if (scale > GetVolumeDiameter()) {
249        scale = GetVolumeDiameter();
[5047c53]250    }
251
[5b7164d]252    m_Scale = scale;
[00a68e0]253    m_HitTestGridValid = false;
[c00c6713]254    if (m_here_is_temporary) SetHere();
[33b2094]255
256    GLACanvas::SetScale(scale);
[d9b3270]257}
258
[f433fda]259bool GfxCore::HasUndergroundLegs() const
260{
261    return m_Parent->HasUndergroundLegs();
262}
263
264bool GfxCore::HasSurfaceLegs() const
265{
266    return m_Parent->HasSurfaceLegs();
267}
268
[50e8979]269bool GfxCore::HasTubes() const
270{
271    return m_Parent->HasTubes();
272}
273
[d9b3270]274void GfxCore::UpdateBlobs()
275{
[d2fcc9b]276    InvalidateList(LIST_BLOBS);
[33b2094]277}
278
[cd6ea75]279//
[5876fcb]280//  Event handlers
[cd6ea75]281//
[5047c53]282
[887c26e]283void GfxCore::OnLeaveWindow(wxMouseEvent& event) {
284    SetHere();
285    ClearCoords();
286}
287
[5876fcb]288void GfxCore::OnIdle(wxIdleEvent& event)
289{
290    // Handle an idle event.
[b72f4b5]291    if (Animate()) {
292        ForceRefresh();
293        event.RequestMore();
294    }
[5809313]295}
296
[b4fe9fb]297void GfxCore::OnPaint(wxPaintEvent&)
[5809313]298{
299    // Redraw the window.
[b462168]300
301    // Get a graphics context.
[1b12b82]302    wxPaintDC dc(this);
[5809313]303
[815eab2]304    if (m_HaveData) {
[01d91fd0]305        // Make sure we're initialised.
306        bool first_time = !m_DoneFirstShow;
307        if (first_time) {
308            FirstShow();
309        }
310
[58dfdd21]311        StartDrawing();
312
313        // Clear the background.
314        Clear();
315
[429465a]316        // Set up model transformation matrix.
317        SetDataTransform();
318
[9eb58d0]319        timer.Start(); // reset timer
[203d2a7]320
[429465a]321        if (m_Legs || m_Tubes) {
322            if (m_Tubes) {
[d67450e]323                EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
[d2fcc9b]324                DrawList(LIST_TUBES);
[429465a]325                DisableSmoothPolygons();
326            }
[e4d40792]327
[50e8979]328            // Draw the underground legs.  Do this last so that anti-aliasing
[e4d40792]329            // works over polygons.
330            SetColour(col_GREEN);
[d2fcc9b]331            DrawList(LIST_UNDERGROUND_LEGS);
[429465a]332        }
[33b2094]333
[429465a]334        if (m_Surface) {
335            // Draw the surface legs.
[d2fcc9b]336            DrawList(LIST_SURFACE_LEGS);
[429465a]337        }
[bbc22ca]338
[f4c5932]339        if (m_BoundingBox) {
340            DrawShadowedBoundingBox();
341        }
[429465a]342        if (m_Grid) {
343            // Draw the grid.
[37d7084]344            DrawList(LIST_GRID);
[429465a]345        }
[b13aee4]346
[d2cc100]347        DrawList(LIST_BLOBS);
348
[86fe6e4]349        if (m_Crosses) {
350            DrawList(LIST_CROSSES);
351        }
352
[429465a]353        SetIndicatorTransform();
354
[6adffadf]355        // Draw station names.
356        if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
357            SetColour(NAME_COLOUR);
358
359            if (m_OverlappingNames) {
360                SimpleDrawNames();
361            } else {
362                NattyDrawNames();
363            }
364        }
365
[6b061db]366        if (MeasuringLineActive()) {
[429465a]367            // Draw "here" and "there".
[f6d8375]368            double hx, hy;
[aa048c3]369            SetColour(HERE_COLOUR);
[d67450e]370            if (m_here.IsValid()) {
[f6d8375]371                double dummy;
[d67450e]372                Transform(m_here, &hx, &hy, &dummy);
[570d62c3]373                if (!m_here_is_temporary) DrawRing(hx, hy);
[429465a]374            }
[d67450e]375            if (m_there.IsValid()) {
[f6d8375]376                double tx, ty;
377                double dummy;
[d67450e]378                Transform(m_there, &tx, &ty, &dummy);
379                if (m_here.IsValid()) {
[429465a]380                    BeginLines();
381                    PlaceIndicatorVertex(hx, hy);
382                    PlaceIndicatorVertex(tx, ty);
[42d23c5]383                    EndLines();
[429465a]384                }
[e633bb1]385                BeginBlobs();
[81aea4e]386                DrawBlob(tx, ty);
[e633bb1]387                EndBlobs();
[429465a]388            }
389        }
[f433fda]390
[429465a]391        // Draw indicators.
[6747314]392        //
393        // There's no advantage in generating an OpenGL list for the
394        // indicators since they change with almost every redraw (and
395        // sometimes several times between redraws).  This way we avoid
396        // the need to track when to update the indicator OpenGL list,
397        // and also avoid indicator update bugs when we don't quite get this
398        // right...
399        DrawIndicators();
[33b2094]400
[58dfdd21]401        FinishDrawing();
402
403        drawtime = timer.Time();
[5997ffdc]404    } else {
405        dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
406        dc.Clear();
[58dfdd21]407    }
[5809313]408}
409
[f4c5932]410void GfxCore::DrawBoundingBox()
411{
[d67450e]412    const Vector3 v = 0.5 * m_Parent->GetExtent();
[f4c5932]413
414    SetColour(col_BLUE);
415    EnableDashedLines();
416    BeginPolyline();
[d67450e]417    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
418    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
419    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
420    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
421    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
[f4c5932]422    EndPolyline();
423    BeginPolyline();
[d67450e]424    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
425    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
426    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
427    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
428    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]429    EndPolyline();
430    BeginLines();
[d67450e]431    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
432    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
433    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
434    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
435    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
436    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
437    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
438    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]439    EndLines();
440    DisableDashedLines();
441}
442
443void GfxCore::DrawShadowedBoundingBox()
444{
[d67450e]445    const Vector3 v = 0.5 * m_Parent->GetExtent();
[f4c5932]446
[f7dae86]447    DrawBoundingBox();
448
[f9ca87c]449    PolygonOffset(true);
[f4c5932]450    SetColour(col_DARK_GREY);
451    BeginQuadrilaterals();
[d67450e]452    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
453    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
454    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
455    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]456    EndQuadrilaterals();
[f9ca87c]457    PolygonOffset(false);
[f4c5932]458
[d2fcc9b]459    DrawList(LIST_SHADOW);
[f4c5932]460}
461
[c1cf79d]462void GfxCore::DrawGrid()
463{
464    // Draw the grid.
[156dc16]465    SetColour(col_RED);
[c1cf79d]466
467    // Calculate the extent of the survey, in metres across the screen plane.
[b81eee2]468    Double m_across_screen = SurveyUnitsAcrossViewport();
[c1cf79d]469    // Calculate the length of the scale bar in metres.
470    //--move this elsewhere
[c6d95d8]471    Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
472    Double t = m_across_screen * 0.75 / size_snap;
[c1cf79d]473    if (t >= 5.0) {
[429465a]474        size_snap *= 5.0;
[c1cf79d]475    }
476    else if (t >= 2.0) {
[429465a]477        size_snap *= 2.0;
[c1cf79d]478    }
479
[d67450e]480    Double grid_size = size_snap * 0.1;
[c6d95d8]481    Double edge = grid_size * 2.0;
[d67450e]482    Double grid_z = -m_Parent->GetZExtent() * 0.5 - grid_size;
483    Double left = -m_Parent->GetXExtent() * 0.5 - edge;
484    Double right = m_Parent->GetXExtent() * 0.5 + edge;
485    Double bottom = -m_Parent->GetYExtent() * 0.5 - edge;
486    Double top = m_Parent->GetYExtent() * 0.5 + edge;
[c1cf79d]487    int count_x = (int) ceil((right - left) / grid_size);
488    int count_y = (int) ceil((top - bottom) / grid_size);
[c6d95d8]489    Double actual_right = left + count_x*grid_size;
490    Double actual_top = bottom + count_y*grid_size;
[c1cf79d]491
[b81eee2]492    BeginLines();
493
[c1cf79d]494    for (int xc = 0; xc <= count_x; xc++) {
[429465a]495        Double x = left + xc*grid_size;
[f433fda]496
[b81eee2]497        PlaceVertex(x, bottom, grid_z);
498        PlaceVertex(x, actual_top, grid_z);
[c1cf79d]499    }
500
501    for (int yc = 0; yc <= count_y; yc++) {
[429465a]502        Double y = bottom + yc*grid_size;
[b81eee2]503        PlaceVertex(left, y, grid_z);
504        PlaceVertex(actual_right, y, grid_z);
[c1cf79d]505    }
[b81eee2]506
507    EndLines();
[c1cf79d]508}
509
[1eeb55a]510int GfxCore::GetClinoOffset() const
[c300a04]511{
512    return m_Compass ? CLINO_OFFSET_X : INDICATOR_OFFSET_X;
513}
514
[fe665c4]515void GfxCore::DrawTick(int angle_cw)
[6606406]516{
[fe665c4]517    const Double theta = rad(angle_cw);
518    const wxCoord length1 = INDICATOR_RADIUS;
519    const wxCoord length0 = length1 + TICK_LENGTH;
520    wxCoord x0 = wxCoord(length0 * sin(theta));
521    wxCoord y0 = wxCoord(length0 * cos(theta));
522    wxCoord x1 = wxCoord(length1 * sin(theta));
523    wxCoord y1 = wxCoord(length1 * cos(theta));
[6606406]524
[fe665c4]525    PlaceIndicatorVertex(x0, y0);
526    PlaceIndicatorVertex(x1, y1);
[6606406]527}
528
[d67450e]529void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
530    Vector3 p1(0, INDICATOR_RADIUS, 0);
531    Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
532    Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
533    Vector3 pc(0, 0, 0);
534
535    DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
536    DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
537}
538
[fe665c4]539void GfxCore::DrawCompass() {
540    // Ticks.
541    BeginLines();
542    for (int angle = 315; angle > 0; angle -= 45) {
543        DrawTick(angle);
544    }
545    SetColour(col_GREEN);
546    DrawTick(0);
547    EndLines();
548
549    // Compass background.
550    DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
[6606406]551
[fe665c4]552    // Compass arrow.
[d67450e]553    DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
[6606406]554}
555
[fe665c4]556// Draw the non-rotating background to the clino.
557void GfxCore::DrawClinoBack() {
558    BeginLines();
559    for (int angle = 0; angle <= 180; angle += 90) {
560        DrawTick(angle);
561    }
562
563    SetColour(col_GREY);
564    PlaceIndicatorVertex(0, INDICATOR_RADIUS);
565    PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
566    PlaceIndicatorVertex(0, 0);
567    PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
[b56df45]568
[fe665c4]569    EndLines();
570}
571
572void GfxCore::DrawClino() {
573    // Ticks.
574    SetColour(col_GREEN);
[33b2094]575    BeginLines();
[fe665c4]576    DrawTick(0);
[33b2094]577    EndLines();
[fe665c4]578
579    // Clino background.
580    DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
581
582    // Elevation arrow.
[d67450e]583    DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
[b56df45]584}
585
[6606406]586void GfxCore::Draw2dIndicators()
587{
[76dd228]588    // Draw the compass and elevation indicators.
589
590    const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
591
[fe665c4]592    const int comp_centre_x = GetCompassXPosition();
[6606406]593
[eef68f9]594    if (m_Compass && !m_Parent->IsExtendedElevation()) {
[fe665c4]595        // If the user is dragging the compass with the pointer outside the
596        // compass, we snap to 45 degree multiples, and the ticks go white.
[76dd228]597        SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
[fe665c4]598        DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
[c300a04]599    }
[76dd228]600
[fe665c4]601    const int elev_centre_x = GetClinoXPosition();
[76dd228]602
[eef68f9]603    if (m_Clino) {
[fe665c4]604        // If the user is dragging the clino with the pointer outside the
605        // clino, we snap to 90 degree multiples, and the ticks go white.
606        SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
607        DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
[7a57dc7]608        DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
[c300a04]609    }
[6606406]610
[aa048c3]611    SetColour(TEXT_COLOUR);
[6606406]612
[21958ec]613    static int triple_zero_width = 0;
614    static int height = 0;
615    if (!triple_zero_width) {
[5627cbb]616        GetTextExtent(wxT("000"), &triple_zero_width, &height);
[21958ec]617    }
618    const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
[421b7d2]619
[eef68f9]620    if (m_Compass && !m_Parent->IsExtendedElevation()) {
[21958ec]621        wxString str;
622        int value;
[429465a]623        if (m_Degrees) {
[21958ec]624            value = int(m_PanAngle);
[429465a]625        } else {
[21958ec]626            value = int(m_PanAngle * 200.0 / 180.0);
[f433fda]627        }
[5627cbb]628        str.Printf(wxT("%03d"), value);
[21958ec]629        DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
630
[5627cbb]631        str = wmsg(/*Facing*/203);
[21958ec]632        int w;
[d92d282]633        GetTextExtent(str, &w, NULL);
[21958ec]634        DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
[c300a04]635    }
636
[eef68f9]637    if (m_Clino) {
[429465a]638        int angle;
[21958ec]639        wxString str;
640        int width;
[429465a]641        if (m_Degrees) {
[21958ec]642            static int zero_zero_width = 0;
643            if (!zero_zero_width) {
[5627cbb]644                GetTextExtent(wxT("00"), &zero_zero_width, NULL);
[21958ec]645            }
646            width = zero_zero_width;
[7a57dc7]647            angle = int(m_TiltAngle);
[5627cbb]648            str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
[429465a]649        } else {
[21958ec]650            width = triple_zero_width;
[7a57dc7]651            angle = int(m_TiltAngle * 200.0 / 180.0);
[5627cbb]652            str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
[f433fda]653        }
[21958ec]654
655        // Adjust horizontal position so the left of the first digit is
656        // always in the same place.
657        int sign_offset = 0;
658        if (angle < 0) {
659            static int minus_width = 0;
660            if (!minus_width) {
[5627cbb]661                GetTextExtent(wxT("-"), &minus_width, NULL);
[21958ec]662            }
663            sign_offset = minus_width + 1;
664        } else if (angle > 0) {
665            static int plus_width = 0;
666            if (!plus_width) {
[5627cbb]667                GetTextExtent(wxT("+"), &plus_width, NULL);
[21958ec]668            }
669            sign_offset = plus_width + 1;
670        }
671        DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
672
[5627cbb]673        str = wmsg(/*Elevation*/118);
[21958ec]674        int w;
[d92d282]675        GetTextExtent(str, &w, NULL);
[21958ec]676        DrawIndicatorText(elev_centre_x - w / 2, y_off + height, str);
[c300a04]677    }
[5809313]678}
679
680void GfxCore::NattyDrawNames()
681{
[84cab34]682    // Draw station names, without overlapping.
[f433fda]683
[d92d282]684    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
[90430f2]685    const unsigned int quantised_x = GetXSize() / quantise;
686    const unsigned int quantised_y = GetYSize() / quantise;
[84cab34]687    const size_t buffer_size = quantised_x * quantised_y;
[f433fda]688
[69463a0]689    if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
[5809313]690
[33b2094]691    memset((void*) m_LabelGrid, 0, buffer_size);
[156dc16]692
[33b2094]693    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
[36c3285]694    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
[ece003f]695        if (!((m_Surface && (*label)->IsSurface()) ||
696              (m_Legs && (*label)->IsUnderground()) ||
697              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
698            // if this station isn't to be displayed, skip to the next
699            // (last case is for stns with no legs attached)
700            continue;
701        }
702
[f6d8375]703        double x, y, z;
[f433fda]704
[d67450e]705        Transform(**label, &x, &y, &z);
[36c3285]706        // Check if the label is behind us (in perspective view).
[d92d282]707        if (z <= 0.0 || z >= 1.0) continue;
[421b7d2]708
[1eeb55a]709        // Apply a small shift so that translating the view doesn't make which
710        // labels are displayed change as the resulting twinkling effect is
711        // distracting.
[f6d8375]712        double tx, ty, tz;
[d67450e]713        Transform(Vector3(), &tx, &ty, &tz);
[429465a]714        tx -= floor(tx / quantise) * quantise;
715        ty -= floor(ty / quantise) * quantise;
[5809313]716
[f12e8cc]717        tx = x - tx;
718        if (tx < 0) continue;
719
720        ty = y - ty;
721        if (ty < 0) continue;
[421b7d2]722
[f12e8cc]723        unsigned int iy = unsigned(ty) / quantise;
[d92d282]724        if (iy >= quantised_y) continue;
[5a24583]725        unsigned int width = (*label)->get_width();
[f12e8cc]726        unsigned int ix = unsigned(tx) / quantise;
727        if (ix + width >= quantised_x) continue;
[33b2094]728
[f12e8cc]729        char * test = m_LabelGrid + ix + iy * quantised_x;
[d92d282]730        if (memchr(test, 1, width)) continue;
[33b2094]731
[8bd480e]732        x += 3;
733        y -= GetFontSize() / 2;
[d92d282]734        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
735
736        if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
737        test -= quantised_x * iy;
[f12e8cc]738        iy += 4;
739        while (--iy && test < m_LabelGrid + buffer_size) {
[d92d282]740            memset(test, 1, width);
741            test += quantised_x;
[429465a]742        }
[84cab34]743    }
[5809313]744}
745
746void GfxCore::SimpleDrawNames()
747{
[a8aedf4]748    // Draw all station names, without worrying about overlaps
[d5de678]749    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
[01d91fd0]750    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
[ece003f]751        if (!((m_Surface && (*label)->IsSurface()) ||
752              (m_Legs && (*label)->IsUnderground()) ||
753              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
754            // if this station isn't to be displayed, skip to the next
755            // (last case is for stns with no legs attached)
756            continue;
757        }
758
[f6d8375]759        double x, y, z;
[d67450e]760        Transform(**label, &x, &y, &z);
[d92d282]761
762        // Check if the label is behind us (in perspective view).
763        if (z <= 0) continue;
764
[8bd480e]765        x += 3;
766        y -= GetFontSize() / 2;
[d92d282]767        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
[84cab34]768    }
[5809313]769}
770
[825bdff]771void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
[5809313]772{
[7cdb1c3]773    int total_block_height =
[62da267]774        KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
775    if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
[825bdff]776    if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
[5809313]777
[3585243]778    const int bottom = -total_block_height;
[a74b014]779
[d4650b3]780    int size = 0;
[7cdb1c3]781    if (!other.empty()) GetTextExtent(other, &size, NULL);
[d4650b3]782    int band;
[2043961]783    for (band = 0; band < num_bands; ++band) {
[a74b014]784        int x;
[7cdb1c3]785        GetTextExtent(key_legends[band], &x, NULL);
[d4650b3]786        if (x > size) size = x;
787    }
788
[3585243]789    int left = -KEY_BLOCK_WIDTH - size;
[d4650b3]790
[fcc3741]791    key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
792    key_lowerleft[m_ColourBy].y = bottom;
[d4650b3]793
[d43fa84]794    int y = bottom;
[825bdff]795    if (!units.empty()) y += KEY_BLOCK_HEIGHT;
[a74b014]796
[7cdb1c3]797    if (!other.empty()) {
[a74b014]798        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
[62da267]799                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
[2779338f]800        SetColour(col_BLACK);
801        BeginPolyline();
802        PlaceIndicatorVertex(left, y);
803        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
804        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y + KEY_BLOCK_HEIGHT);
805        PlaceIndicatorVertex(left, y + KEY_BLOCK_HEIGHT);
806        PlaceIndicatorVertex(left, y);
807        EndPolyline();
[62da267]808        y += KEY_BLOCK_HEIGHT * 2;
[a74b014]809    }
810
[2779338f]811    int start = y;
[2043961]812    if (num_bands == 1) {
813        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
[62da267]814                            KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
[2779338f]815        y += KEY_BLOCK_HEIGHT;
[2043961]816    } else {
817        for (band = 0; band < num_bands - 1; ++band) {
818            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
[62da267]819                                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
820            y += KEY_BLOCK_HEIGHT;
[2043961]821        }
[d4650b3]822    }
823
[2779338f]824    SetColour(col_BLACK);
825    BeginPolyline();
826    PlaceIndicatorVertex(left, y);
827    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
828    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
829    PlaceIndicatorVertex(left, start);
830    PlaceIndicatorVertex(left, y);
831    EndPolyline();
832
[825bdff]833    SetColour(TEXT_COLOUR);
834
835    y = bottom;
836    if (!units.empty()) {
837        GetTextExtent(units, &size, NULL);
838        DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
839        y += KEY_BLOCK_HEIGHT;
840    }
841    y -= GetFontSize() / 2;
[62da267]842    left += KEY_BLOCK_WIDTH + 5;
[d4650b3]843
[7cdb1c3]844    if (!other.empty()) {
[62da267]845        y += KEY_BLOCK_HEIGHT / 2;
[7cdb1c3]846        DrawIndicatorText(left, y, other);
[62da267]847        y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
[a74b014]848    }
849
[2043961]850    if (num_bands == 1) {
[62da267]851        y += KEY_BLOCK_HEIGHT / 2;
[7cdb1c3]852        DrawIndicatorText(left, y, key_legends[0]);
[2043961]853    } else {
[62c5fc6]854        for (band = 0; band < num_bands; ++band) {
[7cdb1c3]855            DrawIndicatorText(left, y, key_legends[band]);
[62da267]856            y += KEY_BLOCK_HEIGHT;
[2043961]857        }
[d4650b3]858    }
859}
860
[e2ea75a]861void GfxCore::DrawDepthKey()
[c61aa79]862{
[62c5fc6]863    Double z_ext = m_Parent->GetDepthExtent();
[825bdff]864    int num_bands = 1;
865    int sf = 0;
866    if (z_ext > 0.0) {
[62c5fc6]867        num_bands = GetNumColourBands();
[825bdff]868        Double z_range = z_ext;
869        if (!m_Metric) z_range /= METRES_PER_FOOT;
870        sf = max(0, 1 - (int)floor(log10(z_range)));
[62c5fc6]871    }
872
[825bdff]873    Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
874    for (int band = 0; band < num_bands; ++band) {
875        Double z = z_min;
[62c5fc6]876        if (band)
877            z += z_ext * band / (num_bands - 1);
[825bdff]878
879        if (!m_Metric)
880            z /= METRES_PER_FOOT;
881
882        key_legends[band].Printf(wxT("%.*f"), sf, z);
[c61aa79]883    }
884
[825bdff]885    DrawColourKey(num_bands, wxString(), m_Metric ? wxT("m") : wxT("ft"));
[7cdb1c3]886}
[a74b014]887
[e2ea75a]888void GfxCore::DrawDateKey()
[7cdb1c3]889{
890    int num_bands;
[62c5fc6]891    if (!HasDateInformation()) {
892        num_bands = 0;
[7cdb1c3]893    } else {
[62c5fc6]894        int date_ext = m_Parent->GetDateExtent();
895        if (date_ext == 0) {
896            num_bands = 1;
897        } else {
898            num_bands = GetNumColourBands();
899        }
900        for (int band = 0; band < num_bands; ++band) {
901            int y, m, d;
902            int days = m_Parent->GetDateMin();
903            if (band)
904                days += date_ext * band / (num_bands - 1);
905            ymd_from_days_since_1900(days, &y, &m, &d);
906            key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
907        }
[7cdb1c3]908    }
[62c5fc6]909
[7cdb1c3]910    wxString other;
911    if (!m_Parent->HasCompleteDateInfo()) {
912        other = wmsg(/*Undated*/221);
[c61aa79]913    }
914
[825bdff]915    DrawColourKey(num_bands, other, wxString());
[7cdb1c3]916}
[a74b014]917
[e2ea75a]918void GfxCore::DrawErrorKey()
[7cdb1c3]919{
[62c5fc6]920    int num_bands;
921    if (HasErrorInformation()) {
922        // Use fixed colours for each error factor so it's directly visually
923        // comparable between surveys.
924        num_bands = GetNumColourBands();
925        for (int band = 0; band < num_bands; ++band) {
926            double E = MAX_ERROR * band / (num_bands - 1);
927            key_legends[band].Printf(wxT("%.2f"), E);
928        }
929    } else {
930        num_bands = 0;
[c61aa79]931    }
932
[7cdb1c3]933    // Always show the "Not in loop" legend for now (FIXME).
[825bdff]934    DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
[ac537e9]935}
936
[9c37beb]937void GfxCore::DrawScaleBar()
[5809313]938{
[84cab34]939    // Draw the scalebar.
[eef68f9]940    if (GetPerspective()) return;
[5809313]941
[37bc1f5]942    // Calculate how many metres of survey are currently displayed across the
943    // screen.
[087bc72]944    Double across_screen = SurveyUnitsAcrossViewport();
[156dc16]945
[90430f2]946    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
[5f50488]947    if (f > 0.75) {
948        f = 0.75;
949    } else if (f < 0.5) {
950        // Stop it getting squeezed to nothing.
951        // FIXME: In this case we should probably move the compass and clino up
952        // to make room rather than letting stuff overlap.
953        f = 0.5;
954    }
955
[087bc72]956    // Convert to imperial measurements if required.
[7a89dc2]957    Double multiplier = 1.0;
958    if (!m_Metric) {
[429465a]959        across_screen /= METRES_PER_FOOT;
960        multiplier = METRES_PER_FOOT;
[5f50488]961        if (across_screen >= 5280.0 / f) {
[429465a]962            across_screen /= 5280.0;
963            multiplier *= 5280.0;
964        }
[7a89dc2]965    }
[5757725]966
[7a89dc2]967    // Calculate the length of the scale bar.
[5f50488]968    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
969    Double t = across_screen * f / size_snap;
[98860c5]970    if (t >= 5.0) {
[429465a]971        size_snap *= 5.0;
[7a89dc2]972    } else if (t >= 2.0) {
[429465a]973        size_snap *= 2.0;
[98860c5]974    }
975
[7a89dc2]976    if (!m_Metric) size_snap *= multiplier;
977
[84cab34]978    // Actual size of the thing in pixels:
[90430f2]979    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
[e2c1671]980    m_ScaleBarWidth = size;
[421b7d2]981
[5809313]982    // Draw it...
[e2c1671]983    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
[5809313]984    int interval = size / 10;
985
[aa048c3]986    gla_colour col = col_WHITE;
[5809313]987    for (int ix = 0; ix < 10; ix++) {
[e2c1671]988        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
[421b7d2]989
[e2c1671]990        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
[421b7d2]991
[aa048c3]992        col = (col == col_WHITE) ? col_GREY : col_WHITE;
[5809313]993    }
994
[84cab34]995    // Add labels.
[825bdff]996    wxString str;
997    if (m_Metric) {
998        if (size_snap >= 1e3) {
999            str.Printf(wxT("%.fkm"), size_snap * 1e-3);
1000        } else if (size_snap >= 1.0) {
1001            str.Printf(wxT("%.fm"), size_snap);
1002        } else {
1003            int sf = -(int)floor(log10(size_snap));
1004            str.Printf(wxT("%.*fm"), sf, size_snap);
1005        }
1006    } else {
1007        size_snap /= METRES_PER_FOOT;
1008        Double miles = size_snap / 5280.0;
1009        if (miles >= 2.0) {
1010            str.Printf(wxT("%.f miles"), miles);
1011        } else if (miles >= 1.0) {
1012            str.Printf(wxT("%.f mile"), miles);
1013        } else if (size_snap >= 1.0) {
1014            str.Printf(wxT("%.fft"), size_snap);
1015        } else {
1016            Double inches = size_snap * 12;
1017            if (inches >= 1.0) {
1018                str.Printf(wxT("%.fin"), inches);
1019            } else {
1020                int sf = -(int)floor(log10(inches));
1021                str.Printf(wxT("%.*fin"), sf, inches);
1022            }
1023        }
1024    }
[84cab34]1025
[1eeb55a]1026    int text_width, text_height;
[56da40e]1027    GetTextExtent(str, &text_width, &text_height);
[8bd480e]1028    const int text_y = end_y - text_height + 1;
1029    SetColour(TEXT_COLOUR);
[5627cbb]1030    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
[8bd480e]1031    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
[5809313]1032}
[56da40e]1033
[2072157]1034bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
[2effbf1]1035{
[0874c07e]1036    if (Animating()) return false;
1037
[90430f2]1038    if (point.x < 0 || point.x >= GetXSize() ||
1039        point.y < 0 || point.y >= GetYSize()) {
[429465a]1040        return false;
[137e31b]1041    }
[421b7d2]1042
[156f645]1043    SetDataTransform();
[00a68e0]1044
[69463a0]1045    if (!m_HitTestGridValid) CreateHitTestGrid();
[fa42426]1046
[90430f2]1047    int grid_x = (point.x * (HITTEST_SIZE - 1)) / GetXSize();
1048    int grid_y = (point.y * (HITTEST_SIZE - 1)) / GetYSize();
[137e31b]1049
[fa42426]1050    LabelInfo *best = NULL;
1051    int dist_sqrd = 25;
[2effbf1]1052    int square = grid_x + grid_y * HITTEST_SIZE;
[fa42426]1053    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
[00a68e0]1054
[fa42426]1055    while (iter != m_PointGrid[square].end()) {
[429465a]1056        LabelInfo *pt = *iter++;
[fa42426]1057
[f6d8375]1058        double cx, cy, cz;
[00a68e0]1059
[d67450e]1060        Transform(*pt, &cx, &cy, &cz);
[00a68e0]1061
[90430f2]1062        cy = GetYSize() - cy;
[00a68e0]1063
[429465a]1064        int dx = point.x - int(cx);
1065        int ds = dx * dx;
1066        if (ds >= dist_sqrd) continue;
1067        int dy = point.y - int(cy);
[fa42426]1068
[429465a]1069        ds += dy * dy;
1070        if (ds >= dist_sqrd) continue;
[f433fda]1071
[429465a]1072        dist_sqrd = ds;
1073        best = pt;
[f433fda]1074
[429465a]1075        if (ds == 0) break;
[2effbf1]1076    }
[f433fda]1077
[fa42426]1078    if (best) {
[6b061db]1079        m_Parent->ShowInfo(best);
[429465a]1080        if (centre) {
[e67ed1b]1081            // FIXME: allow Ctrl-Click to not set there or something?
[82c3731]1082            CentreOn(*best);
[90430f2]1083            WarpPointer(GetXSize() / 2, GetYSize() / 2);
[82c3731]1084            SetThere(*best);
[429465a]1085            m_Parent->SelectTreeItem(best);
1086        }
[e67ed1b]1087    } else {
1088        // Left-clicking not on a survey cancels the measuring line.
[0633bcc]1089        if (centre) {
1090            ClearTreeSelection();
1091        } else {
[6b061db]1092            m_Parent->ShowInfo(best);
[f6d8375]1093            double x, y, z;
[90430f2]1094            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
[0633bcc]1095            SetHere(Point(Vector3(x, y, z)));
[c00c6713]1096            m_here_is_temporary = true;
[0633bcc]1097        }
[2effbf1]1098    }
[203d2a7]1099
1100    return best;
[2effbf1]1101}
1102
[5876fcb]1103void GfxCore::OnSize(wxSizeEvent& event)
[5809313]1104{
[5876fcb]1105    // Handle a change in window size.
1106    wxSize size = event.GetSize();
[5809313]1107
[78beaf1]1108    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
[0580c6a]1109        // Before things are fully initialised, we sometimes get a bogus
1110        // resize message...
[6ef8bd73]1111        // FIXME have changes in MainFrm cured this?  It still happens with
[880b954]1112        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1113        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
[78beaf1]1114        // is resized such that the GfxCore window isn't visible.
1115        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
[0580c6a]1116        return;
1117    }
[b72f4b5]1118
[90430f2]1119    GLACanvas::OnSize(event);
[39e460c9]1120
[5876fcb]1121    if (m_DoneFirstShow) {
[81f1266]1122        TryToFreeArrays();
[6ebc0ce]1123
[69463a0]1124        m_HitTestGridValid = false;
[33b2094]1125
[d67450e]1126        ForceRefresh();
[5809313]1127    }
1128}
1129
[de7a879]1130void GfxCore::DefaultParameters()
[5809313]1131{
[33b2094]1132    // Set default viewing parameters.
[b462168]1133
[f433fda]1134    m_Surface = false;
1135    if (!m_Parent->HasUndergroundLegs()) {
1136        if (m_Parent->HasSurfaceLegs()) {
1137            // If there are surface legs, but no underground legs, turn
1138            // surface surveys on.
1139            m_Surface = true;
1140        } else {
1141            // If there are no legs (e.g. after loading a .pos file), turn
1142            // crosses on.
1143            m_Crosses = true;
1144        }
[b462168]1145    }
1146
[714daae]1147    m_PanAngle = 0.0;
[eef68f9]1148    if (m_Parent->IsExtendedElevation()) {
1149        m_TiltAngle = 0.0;
1150    } else {
[7a57dc7]1151        m_TiltAngle = -90.0;
[b462168]1152    }
[714daae]1153
[08253d9]1154    SetRotation(m_PanAngle, m_TiltAngle);
[d67450e]1155    SetTranslation(Vector3());
[33b2094]1156
[e577f89]1157    m_RotationStep = 30.0;
[5809313]1158    m_Rotating = false;
[3d00693]1159    m_SwitchingTo = 0;
[fe444b8]1160    m_Entrances = false;
1161    m_FixedPts = false;
1162    m_ExportedPts = false;
[c1cf79d]1163    m_Grid = false;
[f4c5932]1164    m_BoundingBox = false;
[33b2094]1165    m_Tubes = false;
[1eeb55a]1166    if (GetPerspective()) TogglePerspective();
[de7a879]1167}
[5809313]1168
[de7a879]1169void GfxCore::Defaults()
1170{
1171    // Restore default scale, rotation and translation parameters.
1172    DefaultParameters();
[8b0d57f]1173    SetScale(1.0);
[ba358fc]1174
1175    // Invalidate all the cached lists.
1176    GLACanvas::FirstShow();
1177
[fa42426]1178    ForceRefresh();
[5809313]1179}
[84cab34]1180
[5876fcb]1181// return: true if animation occured (and ForceRefresh() needs to be called)
[1690fa9]1182bool GfxCore::Animate()
[5809313]1183{
[2a3d328]1184    if (!Animating()) return false;
1185
1186    // Don't show pointer coordinates while animating.
[4b031c0]1187    // FIXME : only do this when we *START* animating!  Use a static copy
1188    // of the value of "Animating()" last time we were here to track this?
1189    // MainFrm now checks if we're trying to clear already cleared labels
1190    // and just returns, but it might be simpler to check here!
[2a3d328]1191    ClearCoords();
[7c29c976]1192    m_Parent->ShowInfo(NULL);
[5809313]1193
[5876fcb]1194    static double last_t = 0;
[6a4cdcb6]1195    double t;
[75d4a2b]1196    if (movie) {
[aea4f8b]1197        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
[75d4a2b]1198        movie->AddFrame();
[6a4cdcb6]1199        t = 1.0 / 25.0; // 25 frames per second
1200    } else {
1201        t = timer.Time() * 1.0e-3;
1202        if (t == 0) t = 0.001;
1203        else if (t > 1.0) t = 1.0;
1204        if (last_t > 0) t = (t + last_t) / 2;
1205        last_t = t;
1206    }
[5809313]1207
[128fac4]1208    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1209        t *= fabs(pres_speed);
[1690fa9]1210        while (t >= next_mark_time) {
1211            t -= next_mark_time;
[128fac4]1212            this_mark_total = 0;
[58dfdd21]1213            PresentationMark prev_mark = next_mark;
[e577f89]1214            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1215            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
[128fac4]1216            if (pres_reverse)
1217                next_mark = m_Parent->GetPresMark(MARK_PREV);
1218            else
1219                next_mark = m_Parent->GetPresMark(MARK_NEXT);
[1690fa9]1220            if (!next_mark.is_valid()) {
[128fac4]1221                SetView(prev_mark);
[1690fa9]1222                presentation_mode = 0;
[81f1266]1223                delete movie;
1224                movie = NULL;
[1690fa9]1225                break;
1226            }
[58dfdd21]1227
[128fac4]1228            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1229            if (tmp > 0) {
1230                next_mark_time = tmp;
[58dfdd21]1231            } else {
[d67450e]1232                double d = (next_mark - prev_mark).magnitude();
[49ce5b0]1233                // FIXME: should ignore component of d which is unseen in
1234                // non-perspective mode?
[8674eea]1235                next_mark_time = sqrd(d / 30.0);
[49ce5b0]1236                double a = next_mark.angle - prev_mark.angle;
1237                if (a > 180.0) {
1238                    next_mark.angle -= 360.0;
1239                    a = 360.0 - a;
1240                } else if (a < -180.0) {
1241                    next_mark.angle += 360.0;
1242                    a += 360.0;
1243                } else {
1244                    a = fabs(a);
1245                }
1246                next_mark_time += sqrd(a / 60.0);
1247                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1248                next_mark_time += sqrd(ta / 60.0);
1249                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
[8674eea]1250                next_mark_time += sqrd(s / 2.0);
[49ce5b0]1251                next_mark_time = sqrt(next_mark_time);
[8674eea]1252                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
[49ce5b0]1253                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
[8674eea]1254                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1255                if (tmp < 0) next_mark_time /= -tmp;
[58dfdd21]1256            }
[1690fa9]1257        }
1258
1259        if (presentation_mode) {
1260            // Advance position towards next_mark
1261            double p = t / next_mark_time;
1262            double q = 1 - p;
1263            PresentationMark here = GetView();
[d877aa2]1264            if (next_mark.angle < 0) {
[e577f89]1265                if (here.angle >= next_mark.angle + 360.0)
1266                    here.angle -= 360.0;
1267            } else if (next_mark.angle >= 360.0) {
1268                if (here.angle <= next_mark.angle - 360.0)
1269                    here.angle += 360.0;
[d877aa2]1270            }
[8674eea]1271            here.assign(q * here + p * next_mark);
[1690fa9]1272            here.angle = q * here.angle + p * next_mark.angle;
[e577f89]1273            if (here.angle < 0) here.angle += 360.0;
1274            else if (here.angle >= 360.0) here.angle -= 360.0;
[1690fa9]1275            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
[58dfdd21]1276            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
[1690fa9]1277            SetView(here);
[128fac4]1278            this_mark_total += t;
[1690fa9]1279            next_mark_time -= t;
1280        }
1281    }
1282
[5876fcb]1283    // When rotating...
1284    if (m_Rotating) {
[1690fa9]1285        TurnCave(m_RotationStep * t);
[5876fcb]1286    }
[5809313]1287
[5876fcb]1288    if (m_SwitchingTo == PLAN) {
[429465a]1289        // When switching to plan view...
[7a57dc7]1290        TiltCave(-90.0 * t);
1291        if (m_TiltAngle == -90.0) {
[429465a]1292            m_SwitchingTo = 0;
1293        }
[1690fa9]1294    } else if (m_SwitchingTo == ELEVATION) {
[429465a]1295        // When switching to elevation view...
[e577f89]1296        if (fabs(m_TiltAngle) < 90.0 * t) {
[429465a]1297            m_SwitchingTo = 0;
1298            TiltCave(-m_TiltAngle);
[7a57dc7]1299        } else if (m_TiltAngle > 0.0) {
[e577f89]1300            TiltCave(-90.0 * t);
[7a57dc7]1301        } else {
1302            TiltCave(90.0 * t);
[429465a]1303        }
[3ddd351]1304    } else if (m_SwitchingTo) {
1305        int angle = (m_SwitchingTo - NORTH) * 90;
1306        double diff = angle - m_PanAngle;
1307        if (diff < -180) diff += 360;
1308        if (diff > 180) diff -= 360;
1309        double move = 90.0 * t;
1310        if (move >= fabs(diff)) {
1311            TurnCave(diff);
1312            m_SwitchingTo = 0;
1313        } else if (diff < 0) {
1314            TurnCave(-move);
1315        } else {
1316            TurnCave(move);
1317        }
[5876fcb]1318    }
[5809313]1319
[7757a4ed]1320    return true;
[5809313]1321}
[84cab34]1322
[0580c6a]1323// How much to allow around the box - this is because of the ring shape
1324// at one end of the line.
1325static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1326#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1327void GfxCore::RefreshLine(const Point &a, const Point &b, const Point &c)
[7a89dc2]1328{
[06d367d]1329    // Best of all might be to copy the window contents before we draw the
1330    // line, then replace each time we redraw.
[796d7bf]1331
[5876fcb]1332    // Calculate the minimum rectangle which includes the old and new
1333    // measuring lines to minimise the redraw time
1334    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
[f6d8375]1335    double X, Y, Z;
[d67450e]1336    if (a.IsValid()) {
1337        if (!Transform(a, &X, &Y, &Z)) {
[796d7bf]1338            printf("oops\n");
1339        } else {
1340            int x = int(X);
[90430f2]1341            int y = GetYSize() - 1 - int(Y);
[796d7bf]1342            l = x - MARGIN;
1343            r = x + MARGIN;
1344            u = y + MARGIN;
1345            d = y - MARGIN;
1346        }
[5876fcb]1347    }
[d67450e]1348    if (b.IsValid()) {
1349        if (!Transform(b, &X, &Y, &Z)) {
[796d7bf]1350            printf("oops\n");
1351        } else {
1352            int x = int(X);
[90430f2]1353            int y = GetYSize() - 1 - int(Y);
[796d7bf]1354            l = min(l, x - MARGIN);
1355            r = max(r, x + MARGIN);
1356            u = max(u, y + MARGIN);
1357            d = min(d, y - MARGIN);
1358        }
[5876fcb]1359    }
[d67450e]1360    if (c.IsValid()) {
1361        if (!Transform(c, &X, &Y, &Z)) {
[796d7bf]1362            printf("oops\n");
1363        } else {
1364            int x = int(X);
[90430f2]1365            int y = GetYSize() - 1 - int(Y);
[796d7bf]1366            l = min(l, x - MARGIN);
1367            r = max(r, x + MARGIN);
1368            u = max(u, y + MARGIN);
1369            d = min(d, y - MARGIN);
1370        }
[5876fcb]1371    }
1372    const wxRect R(l, d, r - l, u - d);
1373    Refresh(false, &R);
[7a89dc2]1374}
1375
[5876fcb]1376void GfxCore::SetHere()
[7a89dc2]1377{
[d67450e]1378    if (!m_here.IsValid()) return;
[6b061db]1379    bool line_active = MeasuringLineActive();
[5876fcb]1380    Point old = m_here;
[d67450e]1381    m_here.Invalidate();
[6b061db]1382    if (line_active || MeasuringLineActive())
1383        RefreshLine(old, m_there, m_here);
[7a89dc2]1384}
1385
[82c3731]1386void GfxCore::SetHere(const Point &p)
[c6d95d8]1387{
[6b061db]1388    bool line_active = MeasuringLineActive();
[5876fcb]1389    Point old = m_here;
[82c3731]1390    m_here = p;
[6b061db]1391    if (line_active || MeasuringLineActive())
1392        RefreshLine(old, m_there, m_here);
[c00c6713]1393    m_here_is_temporary = false;
[156dc16]1394}
1395
[5876fcb]1396void GfxCore::SetThere()
[156dc16]1397{
[d67450e]1398    if (!m_there.IsValid()) return;
[5876fcb]1399    Point old = m_there;
[d67450e]1400    m_there.Invalidate();
[0580c6a]1401    RefreshLine(m_here, old, m_there);
[156dc16]1402}
1403
[82c3731]1404void GfxCore::SetThere(const Point &p)
[156dc16]1405{
[5876fcb]1406    Point old = m_there;
[82c3731]1407    m_there = p;
[0580c6a]1408    RefreshLine(m_here, old, m_there);
[156dc16]1409}
1410
[5876fcb]1411void GfxCore::CreateHitTestGrid()
[156dc16]1412{
[00a68e0]1413    // Clear hit-test grid.
[5876fcb]1414    for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
[429465a]1415        m_PointGrid[i].clear();
[5876fcb]1416    }
[156dc16]1417
[5876fcb]1418    // Fill the grid.
1419    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1420    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1421    while (pos != end) {
[429465a]1422        LabelInfo* label = *pos++;
[33b2094]1423
[429465a]1424        if (!((m_Surface && label->IsSurface()) ||
[dc42b8e]1425              (m_Legs && label->IsUnderground()) ||
1426              (!label->IsSurface() && !label->IsUnderground()))) {
1427            // if this station isn't to be displayed, skip to the next
1428            // (last case is for stns with no legs attached)
[429465a]1429            continue;
1430        }
[33b2094]1431
[429465a]1432        // Calculate screen coordinates.
[f6d8375]1433        double cx, cy, cz;
[d67450e]1434        Transform(*label, &cx, &cy, &cz);
[90430f2]1435        if (cx < 0 || cx >= GetXSize()) continue;
1436        if (cy < 0 || cy >= GetYSize()) continue;
[33b2094]1437
[90430f2]1438        cy = GetYSize() - cy;
[00a68e0]1439
[429465a]1440        // On-screen, so add to hit-test grid...
[90430f2]1441        int grid_x = int((cx * (HITTEST_SIZE - 1)) / GetXSize());
1442        int grid_y = int((cy * (HITTEST_SIZE - 1)) / GetYSize());
[33b2094]1443
[429465a]1444        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
[33b2094]1445    }
1446
[00a68e0]1447    m_HitTestGridValid = true;
[33b2094]1448}
[c6d95d8]1449
[2a02de2]1450//
[5876fcb]1451//  Methods for controlling the orientation of the survey
[2a02de2]1452//
1453
[5876fcb]1454void GfxCore::TurnCave(Double angle)
[156dc16]1455{
[5876fcb]1456    // Turn the cave around its z-axis by a given angle.
[156dc16]1457
[5876fcb]1458    m_PanAngle += angle;
[e577f89]1459    if (m_PanAngle >= 360.0) {
1460        m_PanAngle -= 360.0;
[5876fcb]1461    } else if (m_PanAngle < 0.0) {
[e577f89]1462        m_PanAngle += 360.0;
[156dc16]1463    }
[33b2094]1464
[00a68e0]1465    m_HitTestGridValid = false;
[c00c6713]1466    if (m_here_is_temporary) SetHere();
[00a68e0]1467
[08253d9]1468    SetRotation(m_PanAngle, m_TiltAngle);
[156dc16]1469}
1470
[5876fcb]1471void GfxCore::TurnCaveTo(Double angle)
[d80805e]1472{
[3ddd351]1473    timer.Start(drawtime);
1474    int new_switching_to = ((int)angle) / 90 + NORTH;
1475    if (new_switching_to == m_SwitchingTo) {
1476        // A second order to switch takes us there right away
1477        TurnCave(angle - m_PanAngle);
1478        m_SwitchingTo = 0;
1479        ForceRefresh();
1480    } else {
1481        m_SwitchingTo = new_switching_to;
1482    }
[d80805e]1483}
1484
[5876fcb]1485void GfxCore::TiltCave(Double tilt_angle)
[156dc16]1486{
[5876fcb]1487    // Tilt the cave by a given angle.
[e577f89]1488    if (m_TiltAngle + tilt_angle > 90.0) {
[08253d9]1489        m_TiltAngle = 90.0;
[e577f89]1490    } else if (m_TiltAngle + tilt_angle < -90.0) {
[08253d9]1491        m_TiltAngle = -90.0;
1492    } else {
1493        m_TiltAngle += tilt_angle;
[d80805e]1494    }
1495
[00a68e0]1496    m_HitTestGridValid = false;
[c00c6713]1497    if (m_here_is_temporary) SetHere();
[00a68e0]1498
[08253d9]1499    SetRotation(m_PanAngle, m_TiltAngle);
[5ffa439]1500}
1501
[5876fcb]1502void GfxCore::TranslateCave(int dx, int dy)
[5ffa439]1503{
[33b2094]1504    AddTranslationScreenCoordinates(dx, dy);
[00a68e0]1505    m_HitTestGridValid = false;
1506
[c00c6713]1507    if (m_here_is_temporary) SetHere();
1508
[33b2094]1509    ForceRefresh();
1510}
[5876fcb]1511
[33b2094]1512void GfxCore::DragFinished()
1513{
[76dd228]1514    m_MouseOutsideCompass = m_MouseOutsideElev = false;
[5876fcb]1515    ForceRefresh();
[2173dbd]1516}
1517
[d877aa2]1518void GfxCore::ClearCoords()
1519{
1520    m_Parent->ClearCoords();
1521}
1522
[5876fcb]1523void GfxCore::SetCoords(wxPoint point)
[fd6e0d5]1524{
[0874c07e]1525    // We can't work out 2D coordinates from a perspective view, and it
1526    // doesn't really make sense to show coordinates while we're animating.
1527    if (GetPerspective() || Animating()) return;
[0a811ab]1528
[5876fcb]1529    // Update the coordinate or altitude display, given the (x, y) position in
1530    // window coordinates.  The relevant display is updated depending on
1531    // whether we're in plan or elevation view.
1532
[f6d8375]1533    double cx, cy, cz;
[5876fcb]1534
[a2b3d62]1535    SetDataTransform();
[90430f2]1536    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
[5876fcb]1537
[0633bcc]1538    if (ShowingPlan()) {
[d67450e]1539        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1540                            cy + m_Parent->GetOffset().GetY());
[0633bcc]1541    } else if (ShowingElevation()) {
[d67450e]1542        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ());
[d479c15]1543    } else {
[429465a]1544        m_Parent->ClearCoords();
[a2b3d62]1545    }
[fd6e0d5]1546}
1547
[1eeb55a]1548int GfxCore::GetCompassXPosition() const
[1fd2edb]1549{
[f433fda]1550    // Return the x-coordinate of the centre of the compass in window
1551    // coordinates.
[90430f2]1552    return GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1553}
1554
[1eeb55a]1555int GfxCore::GetClinoXPosition() const
[1fd2edb]1556{
[f433fda]1557    // Return the x-coordinate of the centre of the compass in window
1558    // coordinates.
[90430f2]1559    return GetXSize() - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1560}
1561
[1eeb55a]1562int GfxCore::GetIndicatorYPosition() const
[dfe4454c]1563{
[f433fda]1564    // Return the y-coordinate of the centre of the indicators in window
1565    // coordinates.
[90430f2]1566    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
[5876fcb]1567}
[fa42426]1568
[1eeb55a]1569int GfxCore::GetIndicatorRadius() const
[5876fcb]1570{
1571    // Return the radius of each indicator.
[1eeb55a]1572    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
[5876fcb]1573}
[dfe4454c]1574
[14acdae]1575bool GfxCore::PointWithinCompass(wxPoint point) const
[5876fcb]1576{
[f433fda]1577    // Determine whether a point (in window coordinates) lies within the
1578    // compass.
[e2c1671]1579    if (!ShowingCompass()) return false;
1580
[33b2094]1581    glaCoord dx = point.x - GetCompassXPosition();
1582    glaCoord dy = point.y - GetIndicatorYPosition();
1583    glaCoord radius = GetIndicatorRadius();
[f433fda]1584
[5876fcb]1585    return (dx * dx + dy * dy <= radius * radius);
1586}
[fa42426]1587
[14acdae]1588bool GfxCore::PointWithinClino(wxPoint point) const
[5876fcb]1589{
1590    // Determine whether a point (in window coordinates) lies within the clino.
[e2c1671]1591    if (!ShowingClino()) return false;
1592
[33b2094]1593    glaCoord dx = point.x - GetClinoXPosition();
1594    glaCoord dy = point.y - GetIndicatorYPosition();
1595    glaCoord radius = GetIndicatorRadius();
[f433fda]1596
[5876fcb]1597    return (dx * dx + dy * dy <= radius * radius);
[dfe4454c]1598}
[8000d8f]1599
[14acdae]1600bool GfxCore::PointWithinScaleBar(wxPoint point) const
[5876fcb]1601{
[e2c1671]1602    // Determine whether a point (in window coordinates) lies within the scale
1603    // bar.
1604    if (!ShowingScaleBar()) return false;
[8000d8f]1605
[e2c1671]1606    return (point.x >= SCALE_BAR_OFFSET_X &&
1607            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
[90430f2]1608            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1609            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
[5876fcb]1610}
[8000d8f]1611
[d43fa84]1612bool GfxCore::PointWithinColourKey(wxPoint point) const
1613{
1614    // Determine whether a point (in window coordinates) lies within the key.
[62da267]1615    point.x -= GetXSize() - KEY_OFFSET_X;
1616    point.y = KEY_OFFSET_Y - point.y;
[fcc3741]1617    return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
1618            point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
[d43fa84]1619}
1620
[5876fcb]1621void GfxCore::SetCompassFromPoint(wxPoint point)
[8000d8f]1622{
[d877aa2]1623    // Given a point in window coordinates, set the heading of the survey.  If
1624    // the point is outside the compass, it snaps to 45 degree intervals;
1625    // otherwise it operates as normal.
[8000d8f]1626
[5876fcb]1627    wxCoord dx = point.x - GetCompassXPosition();
1628    wxCoord dy = point.y - GetIndicatorYPosition();
1629    wxCoord radius = GetIndicatorRadius();
[7aa15c0]1630
[0580c6a]1631    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
[5876fcb]1632    if (dx * dx + dy * dy <= radius * radius) {
[3ddd351]1633        TurnCave(angle - m_PanAngle);
[429465a]1634        m_MouseOutsideCompass = false;
[e577f89]1635    } else {
[3ddd351]1636        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
[429465a]1637        m_MouseOutsideCompass = true;
[7aa15c0]1638    }
[8000d8f]1639
[5876fcb]1640    ForceRefresh();
1641}
1642
1643void GfxCore::SetClinoFromPoint(wxPoint point)
1644{
[d877aa2]1645    // Given a point in window coordinates, set the elevation of the survey.
1646    // If the point is outside the clino, it snaps to 90 degree intervals;
1647    // otherwise it operates as normal.
[8000d8f]1648
[33b2094]1649    glaCoord dx = point.x - GetClinoXPosition();
1650    glaCoord dy = point.y - GetIndicatorYPosition();
1651    glaCoord radius = GetIndicatorRadius();
[f433fda]1652
[5876fcb]1653    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
[7a57dc7]1654        TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
[429465a]1655        m_MouseOutsideElev = false;
[e577f89]1656    } else if (dy >= INDICATOR_MARGIN) {
[7a57dc7]1657        TiltCave(-90.0 - m_TiltAngle);
[429465a]1658        m_MouseOutsideElev = true;
[e577f89]1659    } else if (dy <= -INDICATOR_MARGIN) {
[7a57dc7]1660        TiltCave(90.0 - m_TiltAngle);
[429465a]1661        m_MouseOutsideElev = true;
[e577f89]1662    } else {
[429465a]1663        TiltCave(-m_TiltAngle);
1664        m_MouseOutsideElev = true;
[5876fcb]1665    }
[8000d8f]1666
[5876fcb]1667    ForceRefresh();
[8000d8f]1668}
1669
[5876fcb]1670void GfxCore::SetScaleBarFromOffset(wxCoord dx)
[8000d8f]1671{
[5876fcb]1672    // Set the scale of the survey, given an offset as to how much the mouse has
1673    // been dragged over the scalebar since the last scale change.
[8000d8f]1674
[5b7164d]1675    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
[5876fcb]1676    ForceRefresh();
1677}
[8000d8f]1678
[5876fcb]1679void GfxCore::RedrawIndicators()
1680{
1681    // Redraw the compass and clino indicators.
[8000d8f]1682
[90430f2]1683    const wxRect r(GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
[429465a]1684                     INDICATOR_GAP,
[90430f2]1685                   GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
[429465a]1686                   INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1687                   INDICATOR_BOX_SIZE);
[f433fda]1688
[5876fcb]1689    Refresh(false, &r);
[8000d8f]1690}
1691
[5876fcb]1692void GfxCore::StartRotation()
[8000d8f]1693{
[5876fcb]1694    // Start the survey rotating.
[f433fda]1695
[5876fcb]1696    m_Rotating = true;
1697    timer.Start(drawtime);
1698}
[8000d8f]1699
[5876fcb]1700void GfxCore::ToggleRotation()
1701{
1702    // Toggle the survey rotation on/off.
[f433fda]1703
[5876fcb]1704    if (m_Rotating) {
[2a3d328]1705        StopRotation();
1706    } else {
1707        StartRotation();
[5876fcb]1708    }
1709}
[8000d8f]1710
[5876fcb]1711void GfxCore::StopRotation()
1712{
1713    // Stop the survey rotating.
[8000d8f]1714
[5876fcb]1715    m_Rotating = false;
[33b2094]1716    ForceRefresh();
[5876fcb]1717}
[8000d8f]1718
[eef68f9]1719bool GfxCore::IsExtendedElevation() const
[5876fcb]1720{
[eef68f9]1721    return m_Parent->IsExtendedElevation();
[5876fcb]1722}
[8000d8f]1723
[5876fcb]1724void GfxCore::ReverseRotation()
1725{
1726    // Reverse the direction of rotation.
[8000d8f]1727
[5876fcb]1728    m_RotationStep = -m_RotationStep;
1729}
[8000d8f]1730
[5876fcb]1731void GfxCore::RotateSlower(bool accel)
1732{
1733    // Decrease the speed of rotation, optionally by an increased amount.
[8000d8f]1734
[5876fcb]1735    m_RotationStep /= accel ? 1.44 : 1.2;
[e577f89]1736    if (m_RotationStep < 1.0) {
1737        m_RotationStep = 1.0;
[1690fa9]1738    }
[8000d8f]1739}
1740
[5876fcb]1741void GfxCore::RotateFaster(bool accel)
1742{
1743    // Increase the speed of rotation, optionally by an increased amount.
1744
1745    m_RotationStep *= accel ? 1.44 : 1.2;
[e577f89]1746    if (m_RotationStep > 450.0) {
1747        m_RotationStep = 450.0;
[1690fa9]1748    }
[5876fcb]1749}
[8000d8f]1750
[5876fcb]1751void GfxCore::SwitchToElevation()
[8000d8f]1752{
[5876fcb]1753    // Perform an animated switch to elevation view.
[8000d8f]1754
[5876fcb]1755    switch (m_SwitchingTo) {
[429465a]1756        case 0:
1757            timer.Start(drawtime);
1758            m_SwitchingTo = ELEVATION;
1759            break;
[f433fda]1760
[429465a]1761        case PLAN:
1762            m_SwitchingTo = ELEVATION;
1763            break;
[f433fda]1764
[429465a]1765        case ELEVATION:
1766            // a second order to switch takes us there right away
1767            TiltCave(-m_TiltAngle);
1768            m_SwitchingTo = 0;
1769            ForceRefresh();
[5876fcb]1770    }
[8000d8f]1771}
1772
[5876fcb]1773void GfxCore::SwitchToPlan()
[8000d8f]1774{
[5876fcb]1775    // Perform an animated switch to plan view.
[8000d8f]1776
[5876fcb]1777    switch (m_SwitchingTo) {
[429465a]1778        case 0:
1779            timer.Start(drawtime);
1780            m_SwitchingTo = PLAN;
1781            break;
[f433fda]1782
[429465a]1783        case ELEVATION:
1784            m_SwitchingTo = PLAN;
1785            break;
[8000d8f]1786
[429465a]1787        case PLAN:
[0580c6a]1788            // A second order to switch takes us there right away
[7a57dc7]1789            TiltCave(-90.0 - m_TiltAngle);
[429465a]1790            m_SwitchingTo = 0;
1791            ForceRefresh();
[8000d8f]1792    }
[5876fcb]1793}
[8000d8f]1794
[d1628e8e]1795void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
1796{
1797
1798    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
[d0f5918]1799    Double scale = HUGE_VAL;
[d1628e8e]1800    const Vector3 ext = m_Parent->GetExtent();
1801    if (xmax > xmin) {
1802        Double s = ext.GetX() / (xmax - xmin);
1803        if (s < scale) scale = s;
1804    }
1805    if (ymax > ymin) {
1806        Double s = ext.GetY() / (ymax - ymin);
1807        if (s < scale) scale = s;
1808    }
1809    if (!ShowingPlan() && zmax > zmin) {
1810        Double s = ext.GetZ() / (zmax - zmin);
1811        if (s < scale) scale = s;
1812    }
[d0f5918]1813    if (scale != HUGE_VAL) SetScale(scale);
[d1628e8e]1814    ForceRefresh();
1815}
1816
[14acdae]1817bool GfxCore::CanRaiseViewpoint() const
[5876fcb]1818{
1819    // Determine if the survey can be viewed from a higher angle of elevation.
[f433fda]1820
[7a57dc7]1821    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
[8000d8f]1822}
1823
[14acdae]1824bool GfxCore::CanLowerViewpoint() const
[2effbf1]1825{
[5876fcb]1826    // Determine if the survey can be viewed from a lower angle of elevation.
[2effbf1]1827
[7a57dc7]1828    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
[5876fcb]1829}
[2effbf1]1830
[78c67a6]1831bool GfxCore::HasDepth() const
[bd21214]1832{
[78c67a6]1833    return m_Parent->GetDepthExtent() == 0.0;
[bd21214]1834}
1835
[843ee7b]1836bool GfxCore::HasErrorInformation() const
[d4650b3]1837{
[843ee7b]1838    return m_Parent->HasErrorInformation();
[d4650b3]1839}
1840
[843ee7b]1841bool GfxCore::HasDateInformation() const
[c61aa79]1842{
[843ee7b]1843    return m_Parent->GetDateMin() >= 0;
[c61aa79]1844}
1845
[14acdae]1846bool GfxCore::ShowingPlan() const
[5876fcb]1847{
1848    // Determine if the survey is in plan view.
[f433fda]1849
[7a57dc7]1850    return (m_TiltAngle == -90.0);
[2effbf1]1851}
1852
[14acdae]1853bool GfxCore::ShowingElevation() const
[8000d8f]1854{
[5876fcb]1855    // Determine if the survey is in elevation view.
[f433fda]1856
[5876fcb]1857    return (m_TiltAngle == 0.0);
[8000d8f]1858}
1859
[14acdae]1860bool GfxCore::ShowingMeasuringLine() const
[8000d8f]1861{
[5876fcb]1862    // Determine if the measuring line is being shown.
[f433fda]1863
[c00c6713]1864    return (m_there.IsValid() && m_here.IsValid());
[8000d8f]1865}
1866
[eff44b9]1867void GfxCore::ToggleFlag(bool* flag, int update)
[5876fcb]1868{
1869    *flag = !*flag;
[6747314]1870    if (update == UPDATE_BLOBS) {
[eff44b9]1871        UpdateBlobs();
[ef1870d]1872    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
1873        UpdateBlobs();
1874        InvalidateList(LIST_CROSSES);
[6cd6bbe]1875    }
[eff44b9]1876    ForceRefresh();
[5876fcb]1877}
[93744a5]1878
[14acdae]1879int GfxCore::GetNumEntrances() const
[4b1fc48]1880{
[5876fcb]1881    return m_Parent->GetNumEntrances();
1882}
[bd7a61b]1883
[14acdae]1884int GfxCore::GetNumFixedPts() const
[5876fcb]1885{
1886    return m_Parent->GetNumFixedPts();
1887}
[7757a4ed]1888
[14acdae]1889int GfxCore::GetNumExportedPts() const
[5876fcb]1890{
1891    return m_Parent->GetNumExportedPts();
1892}
1893
1894void GfxCore::ClearTreeSelection()
1895{
1896    m_Parent->ClearTreeSelection();
1897}
1898
[82c3731]1899void GfxCore::CentreOn(const Point &p)
[5876fcb]1900{
[d67450e]1901    SetTranslation(-p);
[00a68e0]1902    m_HitTestGridValid = false;
[f433fda]1903
[5876fcb]1904    ForceRefresh();
[4b1fc48]1905}
[5876fcb]1906
[33b2094]1907void GfxCore::ForceRefresh()
1908{
1909    Refresh(false);
1910}
1911
[d2fcc9b]1912void GfxCore::GenerateList(unsigned int l)
[33b2094]1913{
[9eb58d0]1914    assert(m_HaveData);
[3ddcad8]1915
[d2fcc9b]1916    switch (l) {
[fe665c4]1917        case LIST_COMPASS:
1918            DrawCompass();
1919            break;
1920        case LIST_CLINO:
1921            DrawClino();
1922            break;
1923        case LIST_CLINO_BACK:
1924            DrawClinoBack();
1925            break;
[9c37beb]1926        case LIST_SCALE_BAR:
1927            DrawScaleBar();
1928            break;
[e2ea75a]1929        case LIST_DEPTH_KEY:
1930            DrawDepthKey();
[252d759]1931            break;
[e2ea75a]1932        case LIST_DATE_KEY:
1933            DrawDateKey();
[d4650b3]1934            break;
[e2ea75a]1935        case LIST_ERROR_KEY:
1936            DrawErrorKey();
[c61aa79]1937            break;
[d2fcc9b]1938        case LIST_UNDERGROUND_LEGS:
1939            GenerateDisplayList();
1940            break;
1941        case LIST_TUBES:
1942            GenerateDisplayListTubes();
1943            break;
1944        case LIST_SURFACE_LEGS:
1945            GenerateDisplayListSurface();
1946            break;
[86fe6e4]1947        case LIST_BLOBS:
1948            GenerateBlobsDisplayList();
[37d7084]1949            break;
[86fe6e4]1950        case LIST_CROSSES: {
1951            BeginCrosses();
1952            SetColour(col_LIGHT_GREY);
1953            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1954            while (pos != m_Parent->GetLabelsEnd()) {
1955                const LabelInfo* label = *pos++;
1956
1957                if ((m_Surface && label->IsSurface()) ||
1958                    (m_Legs && label->IsUnderground()) ||
1959                    (!label->IsSurface() && !label->IsUnderground())) {
1960                    // Check if this station should be displayed
1961                    // (last case is for stns with no legs attached)
1962                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
1963                }
1964            }
1965            EndCrosses();
1966            break;
1967        }
[37d7084]1968        case LIST_GRID:
1969            DrawGrid();
[d2fcc9b]1970            break;
[86fe6e4]1971        case LIST_SHADOW:
1972            GenerateDisplayListShadow();
[d2fcc9b]1973            break;
1974        default:
1975            assert(false);
1976            break;
1977    }
1978}
1979
[d67450e]1980void GfxCore::ToggleSmoothShading()
1981{
1982    GLACanvas::ToggleSmoothShading();
1983    InvalidateList(LIST_TUBES);
1984    ForceRefresh();
1985}
1986
[d2fcc9b]1987void GfxCore::GenerateDisplayList()
1988{
1989    // Generate the display list for the underground legs.
[c61aa79]1990    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
1991    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[3ddcad8]1992    while (trav != tend) {
1993        (this->*AddPoly)(*trav);
1994        ++trav;
1995    }
[33b2094]1996}
1997
[9eb58d0]1998void GfxCore::GenerateDisplayListTubes()
[33b2094]1999{
[9eb58d0]2000    // Generate the display list for the tubes.
[ee05463]2001    list<vector<XSect> >::const_iterator trav = m_Parent->tubes_begin();
2002    list<vector<XSect> >::const_iterator tend = m_Parent->tubes_end();
[3ddcad8]2003    while (trav != tend) {
2004        SkinPassage(*trav);
2005        ++trav;
2006    }
[9eb58d0]2007}
[33b2094]2008
[9eb58d0]2009void GfxCore::GenerateDisplayListSurface()
2010{
2011    // Generate the display list for the surface legs.
[3ddcad8]2012    EnableDashedLines();
[c61aa79]2013    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2014    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
[3ddcad8]2015    while (trav != tend) {
[c61aa79]2016        if (m_ColourBy == COLOUR_BY_ERROR) {
2017            AddPolylineError(*trav);
2018        } else {
2019            AddPolyline(*trav);
2020        }
[3ddcad8]2021        ++trav;
2022    }
2023    DisableDashedLines();
[d9b3270]2024}
[33b2094]2025
[37d7084]2026void GfxCore::GenerateDisplayListShadow()
[f4c5932]2027{
2028    SetColour(col_BLACK);
[c61aa79]2029    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2030    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[f4c5932]2031    while (trav != tend) {
2032        AddPolylineShadow(*trav);
2033        ++trav;
2034    }
2035}
2036
[d2fcc9b]2037// Plot blobs.
[d9b3270]2038void GfxCore::GenerateBlobsDisplayList()
2039{
[e633bb1]2040    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2041          m_Parent->GetNumHighlightedPts()))
2042        return;
[429465a]2043
[e633bb1]2044    // Plot blobs.
2045    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2046    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2047    BeginBlobs();
2048    while (pos != m_Parent->GetLabelsEnd()) {
[429465a]2049        const LabelInfo* label = *pos++;
2050
2051        // When more than one flag is set on a point:
2052        // search results take priority over entrance highlighting
2053        // which takes priority over fixed point
2054        // highlighting, which in turn takes priority over exported
2055        // point highlighting.
2056
2057        if (!((m_Surface && label->IsSurface()) ||
2058              (m_Legs && label->IsUnderground()) ||
2059              (!label->IsSurface() && !label->IsUnderground()))) {
2060            // if this station isn't to be displayed, skip to the next
2061            // (last case is for stns with no legs attached)
2062            continue;
2063        }
2064
[e633bb1]2065        gla_colour col;
2066
[429465a]2067        if (label->IsHighLighted()) {
2068            col = col_YELLOW;
2069        } else if (m_Entrances && label->IsEntrance()) {
2070            col = col_GREEN;
2071        } else if (m_FixedPts && label->IsFixedPt()) {
2072            col = col_RED;
2073        } else if (m_ExportedPts && label->IsExportedPt()) {
2074            col = col_TURQUOISE;
2075        } else {
2076            continue;
2077        }
2078
[e633bb1]2079        // Stations are sorted by blob type, so colour changes are infrequent.
2080        if (col != prev_col) {
[aa048c3]2081            SetColour(col);
[e633bb1]2082            prev_col = col;
[429465a]2083        }
[e633bb1]2084        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
[d9b3270]2085    }
[e633bb1]2086    EndBlobs();
[33b2094]2087}
2088
[6747314]2089void GfxCore::DrawIndicators()
[33b2094]2090{
[97ea48d]2091    // Draw colour key.
2092    if (m_ColourKey) {
[62c5fc6]2093        if (m_ColourBy == COLOUR_BY_DEPTH) {
[62da267]2094            DrawList2D(LIST_DEPTH_KEY, GetXSize() - KEY_OFFSET_X,
2095                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2096        } else if (m_ColourBy == COLOUR_BY_DATE) {
[62da267]2097            DrawList2D(LIST_DATE_KEY, GetXSize() - KEY_OFFSET_X,
2098                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2099        } else if (m_ColourBy == COLOUR_BY_ERROR) {
[62da267]2100            DrawList2D(LIST_ERROR_KEY, GetXSize() - KEY_OFFSET_X,
2101                       GetYSize() - KEY_OFFSET_Y, 0);
[1b164a0]2102        }
[33b2094]2103    }
[56da40e]2104
[203d2a7]2105    // Draw compass or elevation/heading indicators.
[eef68f9]2106    if (m_Compass || m_Clino) {
2107        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
[203d2a7]2108    }
[f433fda]2109
[56da40e]2110    // Draw scalebar.
2111    if (m_Scalebar) {
[9c37beb]2112        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
[56da40e]2113    }
[33b2094]2114}
2115
[f336ab9]2116void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2117                                    glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]2118                                    Double factor)
[f383708]2119{
[da6c802]2120    SetColour(GetSurfacePen(), factor); // FIXME : assumes surface pen is white!
[b839829]2121    PlaceVertex(v, tex_x, tex_y);
[da6c802]2122}
[f433fda]2123
[b839829]2124void GfxCore::SetDepthColour(Double z, Double factor) {
[da6c802]2125    // Set the drawing colour based on the altitude.
[78c67a6]2126    Double z_ext = m_Parent->GetDepthExtent();
[f383708]2127
[b839829]2128    z -= m_Parent->GetDepthMin();
[f383708]2129    // points arising from tubes may be slightly outside the limits...
[78c67a6]2130    if (z < 0) z = 0;
2131    if (z > z_ext) z = z_ext;
[a6f081c]2132
[2a9d2fa]2133    if (z == 0) {
2134        SetColour(GetPen(0), factor);
2135        return;
2136    }
2137
2138    assert(z_ext > 0.0);
[78c67a6]2139    Double how_far = z / z_ext;
[f383708]2140    assert(how_far >= 0.0);
2141    assert(how_far <= 1.0);
2142
[97ea48d]2143    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[0e69efe]2144    GLAPen pen1 = GetPen(band);
[97ea48d]2145    if (band < GetNumColourBands() - 1) {
[d4650b3]2146        const GLAPen& pen2 = GetPen(band + 1);
[f433fda]2147
[97ea48d]2148        Double interval = z_ext / (GetNumColourBands() - 1);
[78c67a6]2149        Double into_band = z / interval - band;
[f433fda]2150
[d4650b3]2151//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2152//             z_offset, interval, band);
2153        // FIXME: why do we need to clamp here?  Is it because the walls can
2154        // extend further up/down than the centre-line?
2155        if (into_band < 0.0) into_band = 0.0;
2156        if (into_band > 1.0) into_band = 1.0;
2157        assert(into_band >= 0.0);
2158        assert(into_band <= 1.0);
[f433fda]2159
[d4650b3]2160        pen1.Interpolate(pen2, into_band);
2161    }
[aa048c3]2162    SetColour(pen1, factor);
[b839829]2163}
[f383708]2164
[b839829]2165void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2166{
2167    SetDepthColour(v.GetZ(), factor);
[d67450e]2168    PlaceVertex(v);
[f383708]2169}
2170
[b839829]2171void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
[f336ab9]2172                                         glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]2173                                         Double factor)
2174{
2175    SetDepthColour(v.GetZ(), factor);
2176    PlaceVertex(v, tex_x, tex_y);
2177}
2178
[82f584f]2179void GfxCore::SplitLineAcrossBands(int band, int band2,
[4a0e6b35]2180                                   const Vector3 &p, const Vector3 &q,
[82f584f]2181                                   Double factor)
[b5d64e6]2182{
[4a0e6b35]2183    const int step = (band < band2) ? 1 : -1;
[b5d64e6]2184    for (int i = band; i != band2; i += step) {
[4a0e6b35]2185        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2186
2187        // Find the intersection point of the line p -> q
2188        // with the plane parallel to the xy-plane with z-axis intersection z.
[d67450e]2189        assert(q.GetZ() - p.GetZ() != 0.0);
[4a0e6b35]2190
[d67450e]2191        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
[4a0e6b35]2192//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2193
[d67450e]2194        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2195        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
[4a0e6b35]2196
[d67450e]2197        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
[b5d64e6]2198    }
2199}
2200
[14acdae]2201int GfxCore::GetDepthColour(Double z) const
[b5d64e6]2202{
[82f584f]2203    // Return the (0-based) depth colour band index for a z-coordinate.
[78c67a6]2204    Double z_ext = m_Parent->GetDepthExtent();
2205    z -= m_Parent->GetDepthMin();
[2ba3882]2206    // We seem to get rounding differences causing z to sometimes be slightly
[0a2aab8]2207    // less than GetDepthMin() here, and it can certainly be true for passage
2208    // tubes, so just clamp the value to 0.
[2ba3882]2209    if (z <= 0) return 0;
[2a9d2fa]2210    assert(z_ext > 0.0);
[6027220]2211    // We seem to get rounding differences causing z to sometimes exceed z_ext
[0a2aab8]2212    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2213    // can certainly be true for passage tubes, so just clamp the value.
2214    if (z >= z_ext) return GetNumColourBands() - 1;
[97ea48d]2215    return int(z / z_ext * (GetNumColourBands() - 1));
[b5d64e6]2216}
2217
[14acdae]2218Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
[b5d64e6]2219{
[82f584f]2220    // Return the z-coordinate of the depth colour boundary between
2221    // two adjacent depth colour bands (specified by 0-based indices).
2222
2223    assert((a == b - 1) || (a == b + 1));
[97ea48d]2224    if (GetNumColourBands() == 1) return 0;
[82f584f]2225
2226    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
[78c67a6]2227    Double z_ext = m_Parent->GetDepthExtent();
[2a9d2fa]2228    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
[b5d64e6]2229}
2230
[c61aa79]2231void GfxCore::AddPolyline(const traverse & centreline)
[da6c802]2232{
2233    BeginPolyline();
2234    SetColour(GetSurfacePen());
[d4650b3]2235    vector<PointInfo>::const_iterator i = centreline.begin();
[d67450e]2236    PlaceVertex(*i);
[da6c802]2237    ++i;
2238    while (i != centreline.end()) {
[d67450e]2239        PlaceVertex(*i);
[da6c802]2240        ++i;
2241    }
2242    EndPolyline();
2243}
[2a3d328]2244
[c61aa79]2245void GfxCore::AddPolylineShadow(const traverse & centreline)
[f4c5932]2246{
2247    BeginPolyline();
[78c67a6]2248    const double z = -0.5 * m_Parent->GetZExtent();
[d4650b3]2249    vector<PointInfo>::const_iterator i = centreline.begin();
[78c67a6]2250    PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]2251    ++i;
2252    while (i != centreline.end()) {
[78c67a6]2253        PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]2254        ++i;
2255    }
2256    EndPolyline();
2257}
2258
[c61aa79]2259void GfxCore::AddPolylineDepth(const traverse & centreline)
[da6c802]2260{
2261    BeginPolyline();
[d4650b3]2262    vector<PointInfo>::const_iterator i, prev_i;
[da6c802]2263    i = centreline.begin();
[ee7af72]2264    int band0 = GetDepthColour(i->GetZ());
[d67450e]2265    PlaceVertexWithDepthColour(*i);
[da6c802]2266    prev_i = i;
2267    ++i;
2268    while (i != centreline.end()) {
[ee7af72]2269        int band = GetDepthColour(i->GetZ());
[da6c802]2270        if (band != band0) {
[d67450e]2271            SplitLineAcrossBands(band0, band, *prev_i, *i);
[da6c802]2272            band0 = band;
2273        }
[d67450e]2274        PlaceVertexWithDepthColour(*i);
[da6c802]2275        prev_i = i;
2276        ++i;
2277    }
2278    EndPolyline();
2279}
2280
[f433fda]2281void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
[14acdae]2282                               const Vector3 &c, const Vector3 &d)
[da6c802]2283{
2284    Vector3 normal = (a - c) * (d - b);
2285    normal.normalise();
2286    Double factor = dot(normal, light) * .3 + .7;
[f336ab9]2287    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2288    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
[9b57c71b]2289    // FIXME: should plot triangles instead to avoid rendering glitches.
[da6c802]2290    BeginQuadrilaterals();
[b839829]2291    PlaceVertexWithColour(a, 0, 0, factor);
2292    PlaceVertexWithColour(b, w, 0, factor);
2293    PlaceVertexWithColour(c, w, h, factor);
2294    PlaceVertexWithColour(d, 0, h, factor);
[da6c802]2295    EndQuadrilaterals();
2296}
2297
2298void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2299                                    const Vector3 &c, const Vector3 &d)
[2b02270]2300{
2301    Vector3 normal = (a - c) * (d - b);
2302    normal.normalise();
2303    Double factor = dot(normal, light) * .3 + .7;
2304    int a_band, b_band, c_band, d_band;
[d67450e]2305    a_band = GetDepthColour(a.GetZ());
[97ea48d]2306    a_band = min(max(a_band, 0), GetNumColourBands());
[d67450e]2307    b_band = GetDepthColour(b.GetZ());
[97ea48d]2308    b_band = min(max(b_band, 0), GetNumColourBands());
[d67450e]2309    c_band = GetDepthColour(c.GetZ());
[97ea48d]2310    c_band = min(max(c_band, 0), GetNumColourBands());
[d67450e]2311    d_band = GetDepthColour(d.GetZ());
[97ea48d]2312    d_band = min(max(d_band, 0), GetNumColourBands());
[97fb83a]2313    // All this splitting is incorrect - we need to make a separate polygon
2314    // for each depth band...
[f336ab9]2315    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2316    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
[b5d64e6]2317    BeginPolygon();
[d67450e]2318////    PlaceNormal(normal);
[b839829]2319    PlaceVertexWithDepthColour(a, 0, 0, factor);
[2b02270]2320    if (a_band != b_band) {
[b5d64e6]2321        SplitLineAcrossBands(a_band, b_band, a, b, factor);
[2b02270]2322    }
[b839829]2323    PlaceVertexWithDepthColour(b, w, 0, factor);
[2b02270]2324    if (b_band != c_band) {
[b5d64e6]2325        SplitLineAcrossBands(b_band, c_band, b, c, factor);
[2b02270]2326    }
[b839829]2327    PlaceVertexWithDepthColour(c, w, h, factor);
[2b02270]2328    if (c_band != d_band) {
[b5d64e6]2329        SplitLineAcrossBands(c_band, d_band, c, d, factor);
[2b02270]2330    }
[b839829]2331    PlaceVertexWithDepthColour(d, 0, h, factor);
[2b02270]2332    if (d_band != a_band) {
[b5d64e6]2333        SplitLineAcrossBands(d_band, a_band, d, a, factor);
[2b02270]2334    }
[b5d64e6]2335    EndPolygon();
[2b02270]2336}
2337
[1ee204e]2338void GfxCore::SetColourFromDate(int date, Double factor)
[d4650b3]2339{
2340    // Set the drawing colour based on a date.
2341
[1ee204e]2342    if (date == -1) {
[2043961]2343        // Undated.
[d4650b3]2344        SetColour(GetSurfacePen(), factor);
2345        return;
2346    }
2347
[1ee204e]2348    int date_offset = date - m_Parent->GetDateMin();
[2043961]2349    if (date_offset == 0) {
2350        // Earliest date - handle as a special case for the single date case.
2351        SetColour(GetPen(0), factor);
2352        return;
2353    }
[d4650b3]2354
[2043961]2355    int date_ext = m_Parent->GetDateExtent();
[d4650b3]2356    Double how_far = (Double)date_offset / date_ext;
2357    assert(how_far >= 0.0);
2358    assert(how_far <= 1.0);
2359
[97ea48d]2360    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[d4650b3]2361    GLAPen pen1 = GetPen(band);
[97ea48d]2362    if (band < GetNumColourBands() - 1) {
[d4650b3]2363        const GLAPen& pen2 = GetPen(band + 1);
2364
[97ea48d]2365        Double interval = date_ext / (GetNumColourBands() - 1);
[d4650b3]2366        Double into_band = date_offset / interval - band;
2367
2368//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2369//             z_offset, interval, band);
2370        // FIXME: why do we need to clamp here?  Is it because the walls can
2371        // extend further up/down than the centre-line?
2372        if (into_band < 0.0) into_band = 0.0;
2373        if (into_band > 1.0) into_band = 1.0;
2374        assert(into_band >= 0.0);
2375        assert(into_band <= 1.0);
2376
2377        pen1.Interpolate(pen2, into_band);
2378    }
2379    SetColour(pen1, factor);
2380}
2381
[c61aa79]2382void GfxCore::AddPolylineDate(const traverse & centreline)
[d4650b3]2383{
2384    BeginPolyline();
2385    vector<PointInfo>::const_iterator i, prev_i;
2386    i = centreline.begin();
[1ee204e]2387    int date = i->GetDate();
[d4650b3]2388    SetColourFromDate(date, 1.0);
[d67450e]2389    PlaceVertex(*i);
[d4650b3]2390    prev_i = i;
2391    while (++i != centreline.end()) {
[1ee204e]2392        int newdate = i->GetDate();
[d4650b3]2393        if (newdate != date) {
2394            EndPolyline();
2395            BeginPolyline();
2396            date = newdate;
2397            SetColourFromDate(date, 1.0);
[d67450e]2398            PlaceVertex(*prev_i);
[d4650b3]2399        }
[d67450e]2400        PlaceVertex(*i);
[d4650b3]2401        prev_i = i;
2402    }
2403    EndPolyline();
2404}
2405
[1ee204e]2406static int static_date_hack; // FIXME
[d4650b3]2407
2408void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2409                                   const Vector3 &c, const Vector3 &d)
2410{
2411    Vector3 normal = (a - c) * (d - b);
2412    normal.normalise();
2413    Double factor = dot(normal, light) * .3 + .7;
2414    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2415    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2416    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2417    BeginQuadrilaterals();
[d67450e]2418////    PlaceNormal(normal);
[d4650b3]2419    SetColourFromDate(static_date_hack, factor);
[b839829]2420    PlaceVertex(a, 0, 0);
2421    PlaceVertex(b, w, 0);
2422    PlaceVertex(c, w, h);
2423    PlaceVertex(d, 0, h);
2424    EndQuadrilaterals();
[d4650b3]2425}
2426
[c61aa79]2427static double static_E_hack; // FIXME
2428
2429void GfxCore::SetColourFromError(double E, Double factor)
2430{
2431    // Set the drawing colour based on an error value.
2432
2433    if (E < 0) {
2434        SetColour(GetSurfacePen(), factor);
2435        return;
2436    }
2437
2438    Double how_far = E / MAX_ERROR;
2439    assert(how_far >= 0.0);
2440    if (how_far > 1.0) how_far = 1.0;
2441
[97ea48d]2442    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[c61aa79]2443    GLAPen pen1 = GetPen(band);
[97ea48d]2444    if (band < GetNumColourBands() - 1) {
[c61aa79]2445        const GLAPen& pen2 = GetPen(band + 1);
2446
[97ea48d]2447        Double interval = MAX_ERROR / (GetNumColourBands() - 1);
[c61aa79]2448        Double into_band = E / interval - band;
2449
2450//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2451//             z_offset, interval, band);
2452        // FIXME: why do we need to clamp here?  Is it because the walls can
2453        // extend further up/down than the centre-line?
2454        if (into_band < 0.0) into_band = 0.0;
2455        if (into_band > 1.0) into_band = 1.0;
2456        assert(into_band >= 0.0);
2457        assert(into_band <= 1.0);
2458
2459        pen1.Interpolate(pen2, into_band);
2460    }
2461    SetColour(pen1, factor);
2462}
2463
2464void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2465                                    const Vector3 &c, const Vector3 &d)
2466{
2467    Vector3 normal = (a - c) * (d - b);
2468    normal.normalise();
2469    Double factor = dot(normal, light) * .3 + .7;
2470    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2471    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2472    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2473    BeginQuadrilaterals();
[c61aa79]2474////    PlaceNormal(normal);
2475    SetColourFromError(static_E_hack, factor);
[b839829]2476    PlaceVertex(a, 0, 0);
2477    PlaceVertex(b, w, 0);
2478    PlaceVertex(c, w, h);
2479    PlaceVertex(d, 0, h);
2480    EndQuadrilaterals();
[c61aa79]2481}
2482
2483void GfxCore::AddPolylineError(const traverse & centreline)
2484{
2485    BeginPolyline();
2486    SetColourFromError(centreline.E, 1.0);
2487    vector<PointInfo>::const_iterator i;
2488    for(i = centreline.begin(); i != centreline.end(); ++i) {
2489        PlaceVertex(*i);
2490    }
2491    EndPolyline();
2492}
2493
[da6c802]2494void
[ee05463]2495GfxCore::SkinPassage(const vector<XSect> & centreline)
[3ddcad8]2496{
[b3852b5]2497    assert(centreline.size() > 1);
[3ddcad8]2498    Vector3 U[4];
[ee05463]2499    XSect prev_pt_v;
[3ddcad8]2500    Vector3 last_right(1.0, 0.0, 0.0);
2501
[c61aa79]2502//  FIXME: it's not simple to set the colour of a tube based on error...
2503//    static_E_hack = something...
[ee05463]2504    vector<XSect>::const_iterator i = centreline.begin();
2505    vector<XSect>::size_type segment = 0;
[3ddcad8]2506    while (i != centreline.end()) {
2507        // get the coordinates of this vertex
[ee05463]2508        const XSect & pt_v = *i++;
[3ddcad8]2509
2510        double z_pitch_adjust = 0.0;
2511        bool cover_end = false;
2512
2513        Vector3 right, up;
2514
2515        const Vector3 up_v(0.0, 0.0, 1.0);
2516
2517        if (segment == 0) {
2518            assert(i != centreline.end());
2519            // first segment
2520
2521            // get the coordinates of the next vertex
[ee05463]2522            const XSect & next_pt_v = *i;
[3ddcad8]2523
2524            // calculate vector from this pt to the next one
[d67450e]2525            Vector3 leg_v = next_pt_v - pt_v;
[3ddcad8]2526
2527            // obtain a vector in the LRUD plane
2528            right = leg_v * up_v;
2529            if (right.magnitude() == 0) {
2530                right = last_right;
2531                // Obtain a second vector in the LRUD plane,
2532                // perpendicular to the first.
[760ad29d]2533                //up = right * leg_v;
2534                up = up_v;
[3ddcad8]2535            } else {
2536                last_right = right;
2537                up = up_v;
[da6c802]2538            }
2539
[3ddcad8]2540            cover_end = true;
[d4650b3]2541            static_date_hack = next_pt_v.GetDate();
[3ddcad8]2542        } else if (segment + 1 == centreline.size()) {
2543            // last segment
2544
2545            // Calculate vector from the previous pt to this one.
[d67450e]2546            Vector3 leg_v = pt_v - prev_pt_v;
[3ddcad8]2547
2548            // Obtain a horizontal vector in the LRUD plane.
2549            right = leg_v * up_v;
2550            if (right.magnitude() == 0) {
[d67450e]2551                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
[3ddcad8]2552                // Obtain a second vector in the LRUD plane,
2553                // perpendicular to the first.
[760ad29d]2554                //up = right * leg_v;
2555                up = up_v;
[3ddcad8]2556            } else {
2557                last_right = right;
2558                up = up_v;
2559            }
[da6c802]2560
[3ddcad8]2561            cover_end = true;
[d4650b3]2562            static_date_hack = pt_v.GetDate();
[3ddcad8]2563        } else {
2564            assert(i != centreline.end());
2565            // Intermediate segment.
2566
2567            // Get the coordinates of the next vertex.
[ee05463]2568            const XSect & next_pt_v = *i;
[3ddcad8]2569
2570            // Calculate vectors from this vertex to the
2571            // next vertex, and from the previous vertex to
2572            // this one.
[d67450e]2573            Vector3 leg1_v = pt_v - prev_pt_v;
2574            Vector3 leg2_v = next_pt_v - pt_v;
[3ddcad8]2575
2576            // Obtain horizontal vectors perpendicular to
2577            // both legs, then normalise and average to get
2578            // a horizontal bisector.
2579            Vector3 r1 = leg1_v * up_v;
2580            Vector3 r2 = leg2_v * up_v;
2581            r1.normalise();
2582            r2.normalise();
2583            right = r1 + r2;
2584            if (right.magnitude() == 0) {
2585                // This is the "mid-pitch" case...
2586                right = last_right;
2587            }
2588            if (r1.magnitude() == 0) {
2589                Vector3 n = leg1_v;
2590                n.normalise();
[d67450e]2591                z_pitch_adjust = n.GetZ();
2592                //up = Vector3(0, 0, leg1_v.GetZ());
[760ad29d]2593                //up = right * up;
2594                up = up_v;
[3ddcad8]2595
2596                // Rotate pitch section to minimise the
2597                // "tortional stress" - FIXME: use
2598                // triangles instead of rectangles?
2599                int shift = 0;
2600                Double maxdotp = 0;
2601
2602                // Scale to unit vectors in the LRUD plane.
2603                right.normalise();
2604                up.normalise();
2605                Vector3 vec = up - right;
2606                for (int orient = 0; orient <= 3; ++orient) {
[d67450e]2607                    Vector3 tmp = U[orient] - prev_pt_v;
[3ddcad8]2608                    tmp.normalise();
2609                    Double dotp = dot(vec, tmp);
2610                    if (dotp > maxdotp) {
2611                        maxdotp = dotp;
2612                        shift = orient;
2613                    }
2614                }
2615                if (shift) {
2616                    if (shift != 2) {
2617                        Vector3 temp(U[0]);
[b3852b5]2618                        U[0] = U[shift];
2619                        U[shift] = U[2];
2620                        U[2] = U[shift ^ 2];
2621                        U[shift ^ 2] = temp;
[ee7af72]2622                    } else {
[3ddcad8]2623                        swap(U[0], U[2]);
2624                        swap(U[1], U[3]);
[ee7af72]2625                    }
[3ddcad8]2626                }
2627#if 0
2628                // Check that the above code actually permuted
2629                // the vertices correctly.
2630                shift = 0;
2631                maxdotp = 0;
[b3852b5]2632                for (int j = 0; j <= 3; ++j) {
[d67450e]2633                    Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]2634                    tmp.normalise();
2635                    Double dotp = dot(vec, tmp);
2636                    if (dotp > maxdotp) {
2637                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
[b3852b5]2638                        shift = j;
[da6c802]2639                    }
[3ddcad8]2640                }
2641                if (shift) {
2642                    printf("New shift = %d!\n", shift);
2643                    shift = 0;
2644                    maxdotp = 0;
[b3852b5]2645                    for (int j = 0; j <= 3; ++j) {
[d67450e]2646                        Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]2647                        tmp.normalise();
2648                        Double dotp = dot(vec, tmp);
[b3852b5]2649                        printf("    %d : %.8f\n", j, dotp);
[da6c802]2650                    }
2651                }
[3ddcad8]2652#endif
2653            } else if (r2.magnitude() == 0) {
2654                Vector3 n = leg2_v;
2655                n.normalise();
[d67450e]2656                z_pitch_adjust = n.GetZ();
2657                //up = Vector3(0, 0, leg2_v.GetZ());
[760ad29d]2658                //up = right * up;
2659                up = up_v;
[3ddcad8]2660            } else {
2661                up = up_v;
[da6c802]2662            }
[3ddcad8]2663            last_right = right;
[d4650b3]2664            static_date_hack = pt_v.GetDate();
[da6c802]2665        }
2666
[3ddcad8]2667        // Scale to unit vectors in the LRUD plane.
2668        right.normalise();
2669        up.normalise();
[33b2094]2670
[3ddcad8]2671        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
[ce2f3ce]2672
[57a3cd4]2673        Double l = fabs(pt_v.GetL());
2674        Double r = fabs(pt_v.GetR());
2675        Double u = fabs(pt_v.GetU());
2676        Double d = fabs(pt_v.GetD());
[3ddcad8]2677
2678        // Produce coordinates of the corners of the LRUD "plane".
2679        Vector3 v[4];
[d67450e]2680        v[0] = pt_v - right * l + up * u;
2681        v[1] = pt_v + right * r + up * u;
2682        v[2] = pt_v + right * r - up * d;
2683        v[3] = pt_v - right * l - up * d;
[3ddcad8]2684
2685        if (segment > 0) {
2686            (this->*AddQuad)(v[0], v[1], U[1], U[0]);
2687            (this->*AddQuad)(v[2], v[3], U[3], U[2]);
2688            (this->*AddQuad)(v[1], v[2], U[2], U[1]);
2689            (this->*AddQuad)(v[3], v[0], U[0], U[3]);
[9eb58d0]2690        }
2691
[3ddcad8]2692        if (cover_end) {
2693            (this->*AddQuad)(v[3], v[2], v[1], v[0]);
2694        }
[9eb58d0]2695
[3ddcad8]2696        prev_pt_v = pt_v;
2697        U[0] = v[0];
2698        U[1] = v[1];
2699        U[2] = v[2];
2700        U[3] = v[3];
[9eb58d0]2701
[3ddcad8]2702        ++segment;
2703    }
[33b2094]2704}
[b13aee4]2705
2706void GfxCore::FullScreenMode()
2707{
[ea940373]2708    m_Parent->ViewFullScreen();
[b13aee4]2709}
[fdfa926]2710
2711bool GfxCore::IsFullScreen() const
2712{
2713    return m_Parent->IsFullScreen();
2714}
[1690fa9]2715
[46361bc]2716void
2717GfxCore::MoveViewer(double forward, double up, double right)
2718{
[e577f89]2719    double cT = cos(rad(m_TiltAngle));
2720    double sT = sin(rad(m_TiltAngle));
2721    double cP = cos(rad(m_PanAngle));
2722    double sP = sin(rad(m_PanAngle));
[7a57dc7]2723    Vector3 v_forward(cT * sP, cT * cP, sT);
2724    Vector3 v_up(sT * sP, sT * cP, -cT);
[867a1141]2725    Vector3 v_right(-cP, sP, 0);
[d4a5aaf]2726    assert(fabs(dot(v_forward, v_up)) < 1e-6);
2727    assert(fabs(dot(v_forward, v_right)) < 1e-6);
2728    assert(fabs(dot(v_right, v_up)) < 1e-6);
[46361bc]2729    Vector3 move = v_forward * forward + v_up * up + v_right * right;
[d67450e]2730    AddTranslation(-move);
[d877aa2]2731    // Show current position.
[d67450e]2732    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
[46361bc]2733    ForceRefresh();
2734}
2735
[1690fa9]2736PresentationMark GfxCore::GetView() const
2737{
[d67450e]2738    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
[7a57dc7]2739                            m_PanAngle, -m_TiltAngle, m_Scale);
[1690fa9]2740}
2741
2742void GfxCore::SetView(const PresentationMark & p)
2743{
2744    m_SwitchingTo = 0;
[d67450e]2745    SetTranslation(p - m_Parent->GetOffset());
[1690fa9]2746    m_PanAngle = p.angle;
[7a57dc7]2747    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
[08253d9]2748    SetRotation(m_PanAngle, m_TiltAngle);
[1690fa9]2749    SetScale(p.scale);
2750    ForceRefresh();
2751}
2752
[128fac4]2753void GfxCore::PlayPres(double speed, bool change_speed) {
2754    if (!change_speed || presentation_mode == 0) {
2755        if (speed == 0.0) {
2756            presentation_mode = 0;
2757            return;
2758        }
2759        presentation_mode = PLAYING;
2760        next_mark = m_Parent->GetPresMark(MARK_FIRST);
2761        SetView(next_mark);
2762        next_mark_time = 0; // There already!
2763        this_mark_total = 0;
2764        pres_reverse = (speed < 0);
2765    }
2766
[d67450e]2767    if (change_speed) pres_speed = speed;
2768
[128fac4]2769    if (speed != 0.0) {
2770        bool new_pres_reverse = (speed < 0);
2771        if (new_pres_reverse != pres_reverse) {
2772            pres_reverse = new_pres_reverse;
2773            if (pres_reverse) {
2774                next_mark = m_Parent->GetPresMark(MARK_PREV);
2775            } else {
2776                next_mark = m_Parent->GetPresMark(MARK_NEXT);
2777            }
2778            swap(this_mark_total, next_mark_time);
2779        }
2780    }
[1690fa9]2781}
[6a4cdcb6]2782
[da6c802]2783void GfxCore::SetColourBy(int colour_by) {
2784    m_ColourBy = colour_by;
2785    switch (colour_by) {
2786        case COLOUR_BY_DEPTH:
2787            AddQuad = &GfxCore::AddQuadrilateralDepth;
2788            AddPoly = &GfxCore::AddPolylineDepth;
2789            break;
[d4650b3]2790        case COLOUR_BY_DATE:
2791            AddQuad = &GfxCore::AddQuadrilateralDate;
2792            AddPoly = &GfxCore::AddPolylineDate;
2793            break;
[c61aa79]2794        case COLOUR_BY_ERROR:
2795            AddQuad = &GfxCore::AddQuadrilateralError;
2796            AddPoly = &GfxCore::AddPolylineError;
2797            break;
[da6c802]2798        default: // case COLOUR_BY_NONE:
2799            AddQuad = &GfxCore::AddQuadrilateral;
2800            AddPoly = &GfxCore::AddPolyline;
2801            break;
2802    }
2803
[d2fcc9b]2804    InvalidateList(LIST_UNDERGROUND_LEGS);
[c61aa79]2805    InvalidateList(LIST_SURFACE_LEGS);
[d2fcc9b]2806    InvalidateList(LIST_TUBES);
[da6c802]2807
2808    ForceRefresh();
2809}
2810
[6a4cdcb6]2811bool GfxCore::ExportMovie(const wxString & fnm)
2812{
2813    int width;
2814    int height;
2815    GetSize(&width, &height);
[028829f]2816    // Round up to next multiple of 2 (required by ffmpeg).
2817    width += (width & 1);
[6a4cdcb6]2818    height += (height & 1);
2819
[75d4a2b]2820    movie = new MovieMaker();
[6a4cdcb6]2821
[98a3786]2822    // FIXME: This should really use fn_str() - currently we probably can't
2823    // save to a Unicode path on wxmsw.
[75d4a2b]2824    if (!movie->Open(fnm.mb_str(), width, height)) {
[091069f]2825        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
[75d4a2b]2826        delete movie;
[81f1266]2827        movie = NULL;
[6a4cdcb6]2828        return false;
2829    }
[f433fda]2830
[d10d369]2831    PlayPres(1);
[6a4cdcb6]2832    return true;
2833}
[223f1ad]2834
[ce403f1]2835void
2836GfxCore::OnPrint(const wxString &filename, const wxString &title,
2837                 const wxString &datestamp)
2838{
2839    svxPrintDlg * p;
2840    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
2841                        m_PanAngle, m_TiltAngle,
[5940815]2842                        m_Names, m_Crosses, m_Legs, m_Surface,
2843                        true);
[6d1bc83]2844    p->Show(true);
[ce403f1]2845}
2846
[5940815]2847void
[223f1ad]2848GfxCore::OnExport(const wxString &filename, const wxString &title)
2849{
[5940815]2850    svxPrintDlg * p;
[5627cbb]2851    p = new svxPrintDlg(m_Parent, filename, title, wxString(),
[5940815]2852                        m_PanAngle, m_TiltAngle,
2853                        m_Names, m_Crosses, m_Legs, m_Surface,
2854                        false);
[6d1bc83]2855    p->Show(true);
[223f1ad]2856}
[e2c1671]2857
2858static wxCursor
2859make_cursor(const unsigned char * bits, const unsigned char * mask,
2860            int hotx, int hoty)
2861{
[b72f4b5]2862#if defined __WXMSW__ || defined __WXMAC__
[7f3fe6d]2863    wxBitmap cursor_bitmap(reinterpret_cast<const char *>(bits), 32, 32);
2864    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
[4dc4384]2865    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
[e2c1671]2866    wxImage cursor_image = cursor_bitmap.ConvertToImage();
2867    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
2868    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
[7f3fe6d]2869    return wxCursor(cursor_image);
[e2c1671]2870#else
2871    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
[4dc4384]2872                    (const char *)mask, wxBLACK, wxWHITE);
[e2c1671]2873#endif
2874}
2875
2876const
2877#include "hand.xbm"
2878const
2879#include "handmask.xbm"
2880
2881const
2882#include "brotate.xbm"
2883const
2884#include "brotatemask.xbm"
2885
2886const
2887#include "vrotate.xbm"
2888const
2889#include "vrotatemask.xbm"
2890
2891const
2892#include "rotate.xbm"
2893const
2894#include "rotatemask.xbm"
2895
[ecf2d23]2896const
2897#include "rotatezoom.xbm"
2898const
2899#include "rotatezoommask.xbm"
2900
[e2c1671]2901void
2902GfxCore::SetCursor(GfxCore::cursor new_cursor)
2903{
2904    // Check if we're already showing that cursor.
2905    if (current_cursor == new_cursor) return;
2906
2907    current_cursor = new_cursor;
2908    switch (current_cursor) {
2909        case GfxCore::CURSOR_DEFAULT:
2910            GLACanvas::SetCursor(wxNullCursor);
2911            break;
2912        case GfxCore::CURSOR_POINTING_HAND:
2913            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
2914            break;
2915        case GfxCore::CURSOR_DRAGGING_HAND:
2916            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
2917            break;
2918        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
2919            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
2920            break;
2921        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
2922            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
2923            break;
2924        case GfxCore::CURSOR_ROTATE_VERTICALLY:
2925            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
2926            break;
2927        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
2928            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
2929            break;
2930        case GfxCore::CURSOR_ZOOM:
2931            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
2932            break;
[ecf2d23]2933        case GfxCore::CURSOR_ZOOM_ROTATE:
2934            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
2935            break;
[e2c1671]2936    }
2937}
[6b061db]2938
2939bool GfxCore::MeasuringLineActive() const
2940{
2941    if (Animating()) return false;
2942    return (m_here.IsValid() && !m_here_is_temporary) || m_there.IsValid();
2943}
[acdb8aa]2944
2945bool GfxCore::HandleRClick(wxPoint point)
2946{
2947    if (PointWithinCompass(point)) {
2948        // Pop up menu.
2949        wxMenu menu;
[055bfc58]2950        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
2951        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
2952        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
2953        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
2954        menu.AppendSeparator();
[4d2301e]2955        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
[acdb8aa]2956        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]2957        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]2958        PopupMenu(&menu);
2959        return true;
2960    }
2961
2962    if (PointWithinClino(point)) {
2963        // Pop up menu.
2964        wxMenu menu;
[055bfc58]2965        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
2966        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
2967        menu.AppendSeparator();
[acdb8aa]2968        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
2969        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]2970        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
2971        PopupMenu(&menu);
[acdb8aa]2972        return true;
2973    }
2974
2975    if (PointWithinScaleBar(point)) {
2976        // Pop up menu.
2977        wxMenu menu;
2978        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
2979        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]2980        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]2981        PopupMenu(&menu);
2982        return true;
2983    }
2984
2985    if (PointWithinColourKey(point)) {
2986        // Pop up menu.
2987        wxMenu menu;
[d43fa84]2988        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
2989        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
2990        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
2991        menu.AppendSeparator();
[97ea48d]2992        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
[d43fa84]2993        if (m_ColourBy == COLOUR_BY_DEPTH)
2994            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]2995        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]2996        PopupMenu(&menu);
2997        return true;
2998    }
2999
3000    return false;
3001}
Note: See TracBrowser for help on using the repository browser.