source: git/src/gfxcore.cc @ 3585243

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

src/gfxcore.cc: Now that we don't have the key background, just
remove KEY_MARGIN entirely.

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