source: git/src/gfxcore.cc @ 457da16

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

src/gfxcore.cc: Upon loading a survey which lacks the information for
the current "Colour by" mode, don't change to "Colour by none" - we
already do no colouring and hide the key when there's nothing to
colour by, and it's annoying to have the actual mode changed if you
then load a survey which does have the information to colour by.

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

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