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

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

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

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

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