source: git/src/gfxcore.cc @ 2a9d2fa

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

src/gfxcore.cc: Don't segfault on a flat survey. Fix incorrect
addition and corresponding subtraction of GetDepthExtent?() when
calculating splits over depth band boundaries.

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

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