source: git/src/gfxcore.cc @ 2779338f

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

src/gfxcore.cc: Remove the dark grey background from the colour key
and just put a single pixel black border around the colours. This
is more in keeping with the other controls, and means the colours
are now on a black background so more visually similar to the survey
legs.

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

  • Property mode set to 100644
File size: 78.4 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
801    int y = bottom;
802
803    if (!other.empty()) {
804        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
805                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
806        SetColour(col_BLACK);
807        BeginPolyline();
808        PlaceIndicatorVertex(left, y);
809        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
810        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y + KEY_BLOCK_HEIGHT);
811        PlaceIndicatorVertex(left, y + KEY_BLOCK_HEIGHT);
812        PlaceIndicatorVertex(left, y);
813        EndPolyline();
814        y += KEY_BLOCK_HEIGHT * 2;
815    }
816
817    int start = y;
818    if (num_bands == 1) {
819        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
820                            KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
821        y += KEY_BLOCK_HEIGHT;
822    } else {
823        for (band = 0; band < num_bands - 1; ++band) {
824            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
825                                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
826            y += KEY_BLOCK_HEIGHT;
827        }
828    }
829
830    SetColour(col_BLACK);
831    BeginPolyline();
832    PlaceIndicatorVertex(left, y);
833    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
834    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
835    PlaceIndicatorVertex(left, start);
836    PlaceIndicatorVertex(left, y);
837    EndPolyline();
838
839    y = bottom - GetFontSize() / 2;
840    left += KEY_BLOCK_WIDTH + 5;
841
842    SetColour(TEXT_COLOUR);
843    if (!other.empty()) {
844        y += KEY_BLOCK_HEIGHT / 2;
845        DrawIndicatorText(left, y, other);
846        y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
847    }
848
849    if (num_bands == 1) {
850        y += KEY_BLOCK_HEIGHT / 2;
851        DrawIndicatorText(left, y, key_legends[0]);
852    } else {
853        for (band = 0; band < GetNumColourBands(); ++band) {
854            DrawIndicatorText(left, y, key_legends[band]);
855            y += KEY_BLOCK_HEIGHT;
856        }
857    }
858}
859
860void GfxCore::DrawDepthKey()
861{
862    for (int band = 0; band < GetNumColourBands(); ++band) {
863        Double z = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ() +
864                   m_Parent->GetDepthExtent() * band / (GetNumColourBands() - 1);
865        key_legends[band] = FormatLength(z, false);
866    }
867
868    DrawColourKey(GetNumColourBands(), wxString());
869}
870
871void GfxCore::DrawDateKey()
872{
873    int num_bands;
874    if (m_Parent->GetDateExtent() == 0) {
875        num_bands = 1;
876    } else {
877        num_bands = GetNumColourBands();
878    }
879    for (int band = 0; band < num_bands; ++band) {
880        int y, m, d;
881        int days = m_Parent->GetDateMin();
882        if (band)
883            days += m_Parent->GetDateExtent() * band / (num_bands - 1);
884        ymd_from_days_since_1900(days, &y, &m, &d);
885        key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
886    }
887    wxString other;
888    if (!m_Parent->HasCompleteDateInfo()) {
889        other = wmsg(/*Undated*/221);
890    }
891
892    DrawColourKey(num_bands, other);
893}
894
895void GfxCore::DrawErrorKey()
896{
897    for (int band = 0; band < GetNumColourBands(); ++band) {
898        double E = MAX_ERROR * band / (GetNumColourBands() - 1);
899        key_legends[band].Printf(wxT("%.2f"), E);
900    }
901
902    // Always show the "Not in loop" legend for now (FIXME).
903    DrawColourKey(GetNumColourBands(), wmsg(/*Not in loop*/290));
904}
905
906wxString GfxCore::FormatLength(Double size_snap, bool scalebar)
907{
908    wxString str;
909    bool negative = (size_snap < 0.0);
910
911    if (negative) {
912        size_snap = -size_snap;
913    }
914
915    if (size_snap == 0.0) {
916        str = wxT("0");
917    } else if (m_Metric) {
918#ifdef SILLY_UNITS
919        if (size_snap < 1e-12) {
920            str.Printf(wxT("%.3gpm"), size_snap * 1e12);
921        } else if (size_snap < 1e-9) {
922            str.Printf(wxT("%.fpm"), size_snap * 1e12);
923        } else if (size_snap < 1e-6) {
924            str.Printf(wxT("%.fnm"), size_snap * 1e9);
925        } else if (size_snap < 1e-3) {
926            str.Printf(wxT("%.fum"), size_snap * 1e6);
927#else
928        if (size_snap < 1e-3) {
929            str.Printf(wxT("%.3gmm"), size_snap * 1e3);
930#endif
931        } else if (size_snap < 1e-2) {
932            str.Printf(wxT("%.fmm"), size_snap * 1e3);
933        } else if (size_snap < 1.0) {
934            str.Printf(wxT("%.fcm"), size_snap * 100.0);
935        } else if (size_snap < 1e3) {
936            str.Printf(wxT("%.fm"), size_snap);
937#ifdef SILLY_UNITS
938        } else if (size_snap < 1e6) {
939            str.Printf(wxT("%.fkm"), size_snap * 1e-3);
940        } else if (size_snap < 1e9) {
941            str.Printf(wxT("%.fMm"), size_snap * 1e-6);
942        } else {
943            str.Printf(wxT("%.fGm"), size_snap * 1e-9);
944#else
945        } else {
946            str.Printf(scalebar ? wxT("%.fkm") : wxT("%.2fkm"), size_snap * 1e-3);
947#endif
948        }
949    } else {
950        size_snap /= METRES_PER_FOOT;
951        if (scalebar) {
952            Double inches = size_snap * 12;
953            if (inches < 1.0) {
954                str.Printf(wxT("%.3gin"), inches);
955            } else if (size_snap < 1.0) {
956                str.Printf(wxT("%.fin"), inches);
957            } else if (size_snap < 5279.5) {
958                str.Printf(wxT("%.fft"), size_snap);
959            } else {
960                str.Printf(wxT("%.f miles"), size_snap / 5280.0);
961            }
962        } else {
963            str.Printf(wxT("%.fft"), size_snap);
964        }
965    }
966
967    return negative ? wxString(wxT("-")) + str : str;
968}
969
970void GfxCore::DrawScaleBar()
971{
972    // Draw the scalebar.
973    if (GetPerspective()) return;
974
975    // Calculate how many metres of survey are currently displayed across the
976    // screen.
977    Double across_screen = SurveyUnitsAcrossViewport();
978
979    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
980    if (f > 0.75) {
981        f = 0.75;
982    } else if (f < 0.5) {
983        // Stop it getting squeezed to nothing.
984        // FIXME: In this case we should probably move the compass and clino up
985        // to make room rather than letting stuff overlap.
986        f = 0.5;
987    }
988
989    // Convert to imperial measurements if required.
990    Double multiplier = 1.0;
991    if (!m_Metric) {
992        across_screen /= METRES_PER_FOOT;
993        multiplier = METRES_PER_FOOT;
994        if (across_screen >= 5280.0 / f) {
995            across_screen /= 5280.0;
996            multiplier *= 5280.0;
997        }
998    }
999
1000    // Calculate the length of the scale bar.
1001    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1002    Double t = across_screen * f / size_snap;
1003    if (t >= 5.0) {
1004        size_snap *= 5.0;
1005    } else if (t >= 2.0) {
1006        size_snap *= 2.0;
1007    }
1008
1009    if (!m_Metric) size_snap *= multiplier;
1010
1011    // Actual size of the thing in pixels:
1012    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1013    m_ScaleBarWidth = size;
1014
1015    // Draw it...
1016    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1017    int interval = size / 10;
1018
1019    gla_colour col = col_WHITE;
1020    for (int ix = 0; ix < 10; ix++) {
1021        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1022
1023        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1024
1025        col = (col == col_WHITE) ? col_GREY : col_WHITE;
1026    }
1027
1028    // Add labels.
1029    wxString str = FormatLength(size_snap);
1030
1031    int text_width, text_height;
1032    GetTextExtent(str, &text_width, &text_height);
1033    const int text_y = end_y - text_height + 1;
1034    SetColour(TEXT_COLOUR);
1035    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1036    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1037}
1038
1039bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1040{
1041    if (Animating()) return false;
1042
1043    if (point.x < 0 || point.x >= GetXSize() ||
1044        point.y < 0 || point.y >= GetYSize()) {
1045        return false;
1046    }
1047
1048    SetDataTransform();
1049
1050    if (!m_HitTestGridValid) CreateHitTestGrid();
1051
1052    int grid_x = (point.x * (HITTEST_SIZE - 1)) / GetXSize();
1053    int grid_y = (point.y * (HITTEST_SIZE - 1)) / GetYSize();
1054
1055    LabelInfo *best = NULL;
1056    int dist_sqrd = 25;
1057    int square = grid_x + grid_y * HITTEST_SIZE;
1058    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1059
1060    while (iter != m_PointGrid[square].end()) {
1061        LabelInfo *pt = *iter++;
1062
1063        double cx, cy, cz;
1064
1065        Transform(*pt, &cx, &cy, &cz);
1066
1067        cy = GetYSize() - cy;
1068
1069        int dx = point.x - int(cx);
1070        int ds = dx * dx;
1071        if (ds >= dist_sqrd) continue;
1072        int dy = point.y - int(cy);
1073
1074        ds += dy * dy;
1075        if (ds >= dist_sqrd) continue;
1076
1077        dist_sqrd = ds;
1078        best = pt;
1079
1080        if (ds == 0) break;
1081    }
1082
1083    if (best) {
1084        m_Parent->ShowInfo(best);
1085        if (centre) {
1086            // FIXME: allow Ctrl-Click to not set there or something?
1087            CentreOn(*best);
1088            WarpPointer(GetXSize() / 2, GetYSize() / 2);
1089            SetThere(*best);
1090            m_Parent->SelectTreeItem(best);
1091        }
1092    } else {
1093        // Left-clicking not on a survey cancels the measuring line.
1094        if (centre) {
1095            ClearTreeSelection();
1096        } else {
1097            m_Parent->ShowInfo(best);
1098            double x, y, z;
1099            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1100            SetHere(Point(Vector3(x, y, z)));
1101            m_here_is_temporary = true;
1102        }
1103    }
1104
1105    return best;
1106}
1107
1108void GfxCore::OnSize(wxSizeEvent& event)
1109{
1110    // Handle a change in window size.
1111    wxSize size = event.GetSize();
1112
1113    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1114        // Before things are fully initialised, we sometimes get a bogus
1115        // resize message...
1116        // FIXME have changes in MainFrm cured this?  It still happens with
1117        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1118        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1119        // is resized such that the GfxCore window isn't visible.
1120        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1121        return;
1122    }
1123
1124    GLACanvas::OnSize(event);
1125
1126    if (m_DoneFirstShow) {
1127        TryToFreeArrays();
1128
1129        m_HitTestGridValid = false;
1130
1131        ForceRefresh();
1132    }
1133}
1134
1135void GfxCore::DefaultParameters()
1136{
1137    // Set default viewing parameters.
1138
1139    m_Surface = false;
1140    if (!m_Parent->HasUndergroundLegs()) {
1141        if (m_Parent->HasSurfaceLegs()) {
1142            // If there are surface legs, but no underground legs, turn
1143            // surface surveys on.
1144            m_Surface = true;
1145        } else {
1146            // If there are no legs (e.g. after loading a .pos file), turn
1147            // crosses on.
1148            m_Crosses = true;
1149        }
1150    }
1151
1152    m_PanAngle = 0.0;
1153    if (m_Parent->IsExtendedElevation()) {
1154        m_TiltAngle = 0.0;
1155    } else {
1156        m_TiltAngle = 90.0;
1157    }
1158
1159    SetRotation(m_PanAngle, m_TiltAngle);
1160    SetTranslation(Vector3());
1161
1162    m_RotationStep = 30.0;
1163    m_Rotating = false;
1164    m_SwitchingTo = 0;
1165    m_Entrances = false;
1166    m_FixedPts = false;
1167    m_ExportedPts = false;
1168    m_Grid = false;
1169    m_BoundingBox = false;
1170    m_Tubes = false;
1171    if (GetPerspective()) TogglePerspective();
1172}
1173
1174void GfxCore::Defaults()
1175{
1176    // Restore default scale, rotation and translation parameters.
1177    DefaultParameters();
1178    SetScale(1.0);
1179
1180    // Invalidate all the cached lists.
1181    GLACanvas::FirstShow();
1182
1183    ForceRefresh();
1184}
1185
1186// return: true if animation occured (and ForceRefresh() needs to be called)
1187bool GfxCore::Animate()
1188{
1189    if (!Animating()) return false;
1190
1191    // Don't show pointer coordinates while animating.
1192    // FIXME : only do this when we *START* animating!  Use a static copy
1193    // of the value of "Animating()" last time we were here to track this?
1194    // MainFrm now checks if we're trying to clear already cleared labels
1195    // and just returns, but it might be simpler to check here!
1196    ClearCoords();
1197    m_Parent->ShowInfo(NULL);
1198
1199    static double last_t = 0;
1200    double t;
1201    if (movie) {
1202        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1203        movie->AddFrame();
1204        t = 1.0 / 25.0; // 25 frames per second
1205    } else {
1206        t = timer.Time() * 1.0e-3;
1207        if (t == 0) t = 0.001;
1208        else if (t > 1.0) t = 1.0;
1209        if (last_t > 0) t = (t + last_t) / 2;
1210        last_t = t;
1211    }
1212
1213    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1214        t *= fabs(pres_speed);
1215        while (t >= next_mark_time) {
1216            t -= next_mark_time;
1217            this_mark_total = 0;
1218            PresentationMark prev_mark = next_mark;
1219            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1220            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1221            if (pres_reverse)
1222                next_mark = m_Parent->GetPresMark(MARK_PREV);
1223            else
1224                next_mark = m_Parent->GetPresMark(MARK_NEXT);
1225            if (!next_mark.is_valid()) {
1226                SetView(prev_mark);
1227                presentation_mode = 0;
1228                delete movie;
1229                movie = NULL;
1230                break;
1231            }
1232
1233            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1234            if (tmp > 0) {
1235                next_mark_time = tmp;
1236            } else {
1237                double d = (next_mark - prev_mark).magnitude();
1238                // FIXME: should ignore component of d which is unseen in
1239                // non-perspective mode?
1240                next_mark_time = sqrd(d / 30.0);
1241                double a = next_mark.angle - prev_mark.angle;
1242                if (a > 180.0) {
1243                    next_mark.angle -= 360.0;
1244                    a = 360.0 - a;
1245                } else if (a < -180.0) {
1246                    next_mark.angle += 360.0;
1247                    a += 360.0;
1248                } else {
1249                    a = fabs(a);
1250                }
1251                next_mark_time += sqrd(a / 60.0);
1252                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1253                next_mark_time += sqrd(ta / 60.0);
1254                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1255                next_mark_time += sqrd(s / 2.0);
1256                next_mark_time = sqrt(next_mark_time);
1257                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1258                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1259                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1260                if (tmp < 0) next_mark_time /= -tmp;
1261            }
1262        }
1263
1264        if (presentation_mode) {
1265            // Advance position towards next_mark
1266            double p = t / next_mark_time;
1267            double q = 1 - p;
1268            PresentationMark here = GetView();
1269            if (next_mark.angle < 0) {
1270                if (here.angle >= next_mark.angle + 360.0)
1271                    here.angle -= 360.0;
1272            } else if (next_mark.angle >= 360.0) {
1273                if (here.angle <= next_mark.angle - 360.0)
1274                    here.angle += 360.0;
1275            }
1276            here.assign(q * here + p * next_mark);
1277            here.angle = q * here.angle + p * next_mark.angle;
1278            if (here.angle < 0) here.angle += 360.0;
1279            else if (here.angle >= 360.0) here.angle -= 360.0;
1280            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1281            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1282            SetView(here);
1283            this_mark_total += t;
1284            next_mark_time -= t;
1285        }
1286    }
1287
1288    // When rotating...
1289    if (m_Rotating) {
1290        TurnCave(m_RotationStep * t);
1291    }
1292
1293    if (m_SwitchingTo == PLAN) {
1294        // When switching to plan view...
1295        TiltCave(90.0 * t);
1296        if (m_TiltAngle == 90.0) {
1297            m_SwitchingTo = 0;
1298        }
1299    } else if (m_SwitchingTo == ELEVATION) {
1300        // When switching to elevation view...
1301        if (fabs(m_TiltAngle) < 90.0 * t) {
1302            m_SwitchingTo = 0;
1303            TiltCave(-m_TiltAngle);
1304        } else if (m_TiltAngle < 0.0) {
1305            TiltCave(90.0 * t);
1306        } else {
1307            TiltCave(-90.0 * t);
1308        }
1309    } else if (m_SwitchingTo) {
1310        int angle = (m_SwitchingTo - NORTH) * 90;
1311        double diff = angle - m_PanAngle;
1312        if (diff < -180) diff += 360;
1313        if (diff > 180) diff -= 360;
1314        double move = 90.0 * t;
1315        if (move >= fabs(diff)) {
1316            TurnCave(diff);
1317            m_SwitchingTo = 0;
1318        } else if (diff < 0) {
1319            TurnCave(-move);
1320        } else {
1321            TurnCave(move);
1322        }
1323    }
1324
1325    return true;
1326}
1327
1328// How much to allow around the box - this is because of the ring shape
1329// at one end of the line.
1330static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1331#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1332void GfxCore::RefreshLine(const Point &a, const Point &b, const Point &c)
1333{
1334    // Best of all might be to copy the window contents before we draw the
1335    // line, then replace each time we redraw.
1336
1337    // Calculate the minimum rectangle which includes the old and new
1338    // measuring lines to minimise the redraw time
1339    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1340    double X, Y, Z;
1341    if (a.IsValid()) {
1342        if (!Transform(a, &X, &Y, &Z)) {
1343            printf("oops\n");
1344        } else {
1345            int x = int(X);
1346            int y = GetYSize() - 1 - int(Y);
1347            l = x - MARGIN;
1348            r = x + MARGIN;
1349            u = y + MARGIN;
1350            d = y - MARGIN;
1351        }
1352    }
1353    if (b.IsValid()) {
1354        if (!Transform(b, &X, &Y, &Z)) {
1355            printf("oops\n");
1356        } else {
1357            int x = int(X);
1358            int y = GetYSize() - 1 - int(Y);
1359            l = min(l, x - MARGIN);
1360            r = max(r, x + MARGIN);
1361            u = max(u, y + MARGIN);
1362            d = min(d, y - MARGIN);
1363        }
1364    }
1365    if (c.IsValid()) {
1366        if (!Transform(c, &X, &Y, &Z)) {
1367            printf("oops\n");
1368        } else {
1369            int x = int(X);
1370            int y = GetYSize() - 1 - int(Y);
1371            l = min(l, x - MARGIN);
1372            r = max(r, x + MARGIN);
1373            u = max(u, y + MARGIN);
1374            d = min(d, y - MARGIN);
1375        }
1376    }
1377    const wxRect R(l, d, r - l, u - d);
1378    Refresh(false, &R);
1379}
1380
1381void GfxCore::SetHere()
1382{
1383    if (!m_here.IsValid()) return;
1384    bool line_active = MeasuringLineActive();
1385    Point old = m_here;
1386    m_here.Invalidate();
1387    if (line_active || MeasuringLineActive())
1388        RefreshLine(old, m_there, m_here);
1389}
1390
1391void GfxCore::SetHere(const Point &p)
1392{
1393    bool line_active = MeasuringLineActive();
1394    Point old = m_here;
1395    m_here = p;
1396    if (line_active || MeasuringLineActive())
1397        RefreshLine(old, m_there, m_here);
1398    m_here_is_temporary = false;
1399}
1400
1401void GfxCore::SetThere()
1402{
1403    if (!m_there.IsValid()) return;
1404    Point old = m_there;
1405    m_there.Invalidate();
1406    RefreshLine(m_here, old, m_there);
1407}
1408
1409void GfxCore::SetThere(const Point &p)
1410{
1411    Point old = m_there;
1412    m_there = p;
1413    RefreshLine(m_here, old, m_there);
1414}
1415
1416void GfxCore::CreateHitTestGrid()
1417{
1418    // Clear hit-test grid.
1419    for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1420        m_PointGrid[i].clear();
1421    }
1422
1423    // Fill the grid.
1424    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1425    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1426    while (pos != end) {
1427        LabelInfo* label = *pos++;
1428
1429        if (!((m_Surface && label->IsSurface()) ||
1430              (m_Legs && label->IsUnderground()) ||
1431              (!label->IsSurface() && !label->IsUnderground()))) {
1432            // if this station isn't to be displayed, skip to the next
1433            // (last case is for stns with no legs attached)
1434            continue;
1435        }
1436
1437        // Calculate screen coordinates.
1438        double cx, cy, cz;
1439        Transform(*label, &cx, &cy, &cz);
1440        if (cx < 0 || cx >= GetXSize()) continue;
1441        if (cy < 0 || cy >= GetYSize()) continue;
1442
1443        cy = GetYSize() - cy;
1444
1445        // On-screen, so add to hit-test grid...
1446        int grid_x = int((cx * (HITTEST_SIZE - 1)) / GetXSize());
1447        int grid_y = int((cy * (HITTEST_SIZE - 1)) / GetYSize());
1448
1449        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1450    }
1451
1452    m_HitTestGridValid = true;
1453}
1454
1455//
1456//  Methods for controlling the orientation of the survey
1457//
1458
1459void GfxCore::TurnCave(Double angle)
1460{
1461    // Turn the cave around its z-axis by a given angle.
1462
1463    m_PanAngle += angle;
1464    if (m_PanAngle >= 360.0) {
1465        m_PanAngle -= 360.0;
1466    } else if (m_PanAngle < 0.0) {
1467        m_PanAngle += 360.0;
1468    }
1469
1470    m_HitTestGridValid = false;
1471    if (m_here_is_temporary) SetHere();
1472
1473    SetRotation(m_PanAngle, m_TiltAngle);
1474}
1475
1476void GfxCore::TurnCaveTo(Double angle)
1477{
1478    timer.Start(drawtime);
1479    int new_switching_to = ((int)angle) / 90 + NORTH;
1480    if (new_switching_to == m_SwitchingTo) {
1481        // A second order to switch takes us there right away
1482        TurnCave(angle - m_PanAngle);
1483        m_SwitchingTo = 0;
1484        ForceRefresh();
1485    } else {
1486        m_SwitchingTo = new_switching_to;
1487    }
1488}
1489
1490void GfxCore::TiltCave(Double tilt_angle)
1491{
1492    // Tilt the cave by a given angle.
1493    if (m_TiltAngle + tilt_angle > 90.0) {
1494        m_TiltAngle = 90.0;
1495    } else if (m_TiltAngle + tilt_angle < -90.0) {
1496        m_TiltAngle = -90.0;
1497    } else {
1498        m_TiltAngle += tilt_angle;
1499    }
1500
1501    m_HitTestGridValid = false;
1502    if (m_here_is_temporary) SetHere();
1503
1504    SetRotation(m_PanAngle, m_TiltAngle);
1505}
1506
1507void GfxCore::TranslateCave(int dx, int dy)
1508{
1509    AddTranslationScreenCoordinates(dx, dy);
1510    m_HitTestGridValid = false;
1511
1512    if (m_here_is_temporary) SetHere();
1513
1514    ForceRefresh();
1515}
1516
1517void GfxCore::DragFinished()
1518{
1519    m_MouseOutsideCompass = m_MouseOutsideElev = false;
1520    ForceRefresh();
1521}
1522
1523void GfxCore::ClearCoords()
1524{
1525    m_Parent->ClearCoords();
1526}
1527
1528void GfxCore::SetCoords(wxPoint point)
1529{
1530    // We can't work out 2D coordinates from a perspective view, and it
1531    // doesn't really make sense to show coordinates while we're animating.
1532    if (GetPerspective() || Animating()) return;
1533
1534    // Update the coordinate or altitude display, given the (x, y) position in
1535    // window coordinates.  The relevant display is updated depending on
1536    // whether we're in plan or elevation view.
1537
1538    double cx, cy, cz;
1539
1540    SetDataTransform();
1541    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
1542
1543    if (ShowingPlan()) {
1544        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1545                            cy + m_Parent->GetOffset().GetY());
1546    } else if (ShowingElevation()) {
1547        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ());
1548    } else {
1549        m_Parent->ClearCoords();
1550    }
1551}
1552
1553int GfxCore::GetCompassXPosition() const
1554{
1555    // Return the x-coordinate of the centre of the compass in window
1556    // coordinates.
1557    return GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
1558}
1559
1560int GfxCore::GetClinoXPosition() const
1561{
1562    // Return the x-coordinate of the centre of the compass in window
1563    // coordinates.
1564    return GetXSize() - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
1565}
1566
1567int GfxCore::GetIndicatorYPosition() const
1568{
1569    // Return the y-coordinate of the centre of the indicators in window
1570    // coordinates.
1571    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1572}
1573
1574int GfxCore::GetIndicatorRadius() const
1575{
1576    // Return the radius of each indicator.
1577    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1578}
1579
1580bool GfxCore::PointWithinCompass(wxPoint point) const
1581{
1582    // Determine whether a point (in window coordinates) lies within the
1583    // compass.
1584    if (!ShowingCompass()) return false;
1585
1586    glaCoord dx = point.x - GetCompassXPosition();
1587    glaCoord dy = point.y - GetIndicatorYPosition();
1588    glaCoord radius = GetIndicatorRadius();
1589
1590    return (dx * dx + dy * dy <= radius * radius);
1591}
1592
1593bool GfxCore::PointWithinClino(wxPoint point) const
1594{
1595    // Determine whether a point (in window coordinates) lies within the clino.
1596    if (!ShowingClino()) return false;
1597
1598    glaCoord dx = point.x - GetClinoXPosition();
1599    glaCoord dy = point.y - GetIndicatorYPosition();
1600    glaCoord radius = GetIndicatorRadius();
1601
1602    return (dx * dx + dy * dy <= radius * radius);
1603}
1604
1605bool GfxCore::PointWithinScaleBar(wxPoint point) const
1606{
1607    // Determine whether a point (in window coordinates) lies within the scale
1608    // bar.
1609    if (!ShowingScaleBar()) return false;
1610
1611    return (point.x >= SCALE_BAR_OFFSET_X &&
1612            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
1613            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1614            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
1615}
1616
1617bool GfxCore::PointWithinColourKey(wxPoint point) const
1618{
1619    // Determine whether a point (in window coordinates) lies within the key.
1620    point.x -= GetXSize() - KEY_OFFSET_X;
1621    point.y = KEY_OFFSET_Y - point.y;
1622    return (point.x >= key_lowerleft.x && point.x <= 0 &&
1623            point.y >= key_lowerleft.y && point.y <= 0);
1624}
1625
1626void GfxCore::SetCompassFromPoint(wxPoint point)
1627{
1628    // Given a point in window coordinates, set the heading of the survey.  If
1629    // the point is outside the compass, it snaps to 45 degree intervals;
1630    // otherwise it operates as normal.
1631
1632    wxCoord dx = point.x - GetCompassXPosition();
1633    wxCoord dy = point.y - GetIndicatorYPosition();
1634    wxCoord radius = GetIndicatorRadius();
1635
1636    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
1637    if (dx * dx + dy * dy <= radius * radius) {
1638        TurnCave(angle - m_PanAngle);
1639        m_MouseOutsideCompass = false;
1640    } else {
1641        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
1642        m_MouseOutsideCompass = true;
1643    }
1644
1645    ForceRefresh();
1646}
1647
1648void GfxCore::SetClinoFromPoint(wxPoint point)
1649{
1650    // Given a point in window coordinates, set the elevation of the survey.
1651    // If the point is outside the clino, it snaps to 90 degree intervals;
1652    // otherwise it operates as normal.
1653
1654    glaCoord dx = point.x - GetClinoXPosition();
1655    glaCoord dy = point.y - GetIndicatorYPosition();
1656    glaCoord radius = GetIndicatorRadius();
1657
1658    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
1659        TiltCave(deg(atan2(double(dy), double(dx))) - m_TiltAngle);
1660        m_MouseOutsideElev = false;
1661    } else if (dy >= INDICATOR_MARGIN) {
1662        TiltCave(90.0 - m_TiltAngle);
1663        m_MouseOutsideElev = true;
1664    } else if (dy <= -INDICATOR_MARGIN) {
1665        TiltCave(-90.0 - m_TiltAngle);
1666        m_MouseOutsideElev = true;
1667    } else {
1668        TiltCave(-m_TiltAngle);
1669        m_MouseOutsideElev = true;
1670    }
1671
1672    ForceRefresh();
1673}
1674
1675void GfxCore::SetScaleBarFromOffset(wxCoord dx)
1676{
1677    // Set the scale of the survey, given an offset as to how much the mouse has
1678    // been dragged over the scalebar since the last scale change.
1679
1680    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
1681    ForceRefresh();
1682}
1683
1684void GfxCore::RedrawIndicators()
1685{
1686    // Redraw the compass and clino indicators.
1687
1688    const wxRect r(GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
1689                     INDICATOR_GAP,
1690                   GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
1691                   INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1692                   INDICATOR_BOX_SIZE);
1693
1694    Refresh(false, &r);
1695}
1696
1697void GfxCore::StartRotation()
1698{
1699    // Start the survey rotating.
1700
1701    m_Rotating = true;
1702    timer.Start(drawtime);
1703}
1704
1705void GfxCore::ToggleRotation()
1706{
1707    // Toggle the survey rotation on/off.
1708
1709    if (m_Rotating) {
1710        StopRotation();
1711    } else {
1712        StartRotation();
1713    }
1714}
1715
1716void GfxCore::StopRotation()
1717{
1718    // Stop the survey rotating.
1719
1720    m_Rotating = false;
1721    ForceRefresh();
1722}
1723
1724bool GfxCore::IsExtendedElevation() const
1725{
1726    return m_Parent->IsExtendedElevation();
1727}
1728
1729void GfxCore::ReverseRotation()
1730{
1731    // Reverse the direction of rotation.
1732
1733    m_RotationStep = -m_RotationStep;
1734}
1735
1736void GfxCore::RotateSlower(bool accel)
1737{
1738    // Decrease the speed of rotation, optionally by an increased amount.
1739
1740    m_RotationStep /= accel ? 1.44 : 1.2;
1741    if (m_RotationStep < 1.0) {
1742        m_RotationStep = 1.0;
1743    }
1744}
1745
1746void GfxCore::RotateFaster(bool accel)
1747{
1748    // Increase the speed of rotation, optionally by an increased amount.
1749
1750    m_RotationStep *= accel ? 1.44 : 1.2;
1751    if (m_RotationStep > 450.0) {
1752        m_RotationStep = 450.0;
1753    }
1754}
1755
1756void GfxCore::SwitchToElevation()
1757{
1758    // Perform an animated switch to elevation view.
1759
1760    switch (m_SwitchingTo) {
1761        case 0:
1762            timer.Start(drawtime);
1763            m_SwitchingTo = ELEVATION;
1764            break;
1765
1766        case PLAN:
1767            m_SwitchingTo = ELEVATION;
1768            break;
1769
1770        case ELEVATION:
1771            // a second order to switch takes us there right away
1772            TiltCave(-m_TiltAngle);
1773            m_SwitchingTo = 0;
1774            ForceRefresh();
1775    }
1776}
1777
1778void GfxCore::SwitchToPlan()
1779{
1780    // Perform an animated switch to plan view.
1781
1782    switch (m_SwitchingTo) {
1783        case 0:
1784            timer.Start(drawtime);
1785            m_SwitchingTo = PLAN;
1786            break;
1787
1788        case ELEVATION:
1789            m_SwitchingTo = PLAN;
1790            break;
1791
1792        case PLAN:
1793            // A second order to switch takes us there right away
1794            TiltCave(90.0 - m_TiltAngle);
1795            m_SwitchingTo = 0;
1796            ForceRefresh();
1797    }
1798}
1799
1800void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
1801{
1802
1803    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
1804    Double scale = HUGE_VAL;
1805    const Vector3 ext = m_Parent->GetExtent();
1806    if (xmax > xmin) {
1807        Double s = ext.GetX() / (xmax - xmin);
1808        if (s < scale) scale = s;
1809    }
1810    if (ymax > ymin) {
1811        Double s = ext.GetY() / (ymax - ymin);
1812        if (s < scale) scale = s;
1813    }
1814    if (!ShowingPlan() && zmax > zmin) {
1815        Double s = ext.GetZ() / (zmax - zmin);
1816        if (s < scale) scale = s;
1817    }
1818    if (scale != HUGE_VAL) SetScale(scale);
1819    ForceRefresh();
1820}
1821
1822bool GfxCore::CanRaiseViewpoint() const
1823{
1824    // Determine if the survey can be viewed from a higher angle of elevation.
1825
1826    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
1827}
1828
1829bool GfxCore::CanLowerViewpoint() const
1830{
1831    // Determine if the survey can be viewed from a lower angle of elevation.
1832
1833    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
1834}
1835
1836bool GfxCore::HasDepth() const
1837{
1838    return m_Parent->GetDepthExtent() == 0.0;
1839}
1840
1841bool GfxCore::HasErrorInformation() const
1842{
1843    return m_Parent->HasErrorInformation();
1844}
1845
1846bool GfxCore::HasDateInformation() const
1847{
1848    return m_Parent->GetDateMin() >= 0;
1849}
1850
1851bool GfxCore::ShowingPlan() const
1852{
1853    // Determine if the survey is in plan view.
1854
1855    return (m_TiltAngle == 90.0);
1856}
1857
1858bool GfxCore::ShowingElevation() const
1859{
1860    // Determine if the survey is in elevation view.
1861
1862    return (m_TiltAngle == 0.0);
1863}
1864
1865bool GfxCore::ShowingMeasuringLine() const
1866{
1867    // Determine if the measuring line is being shown.
1868
1869    return (m_there.IsValid() && m_here.IsValid());
1870}
1871
1872void GfxCore::ToggleFlag(bool* flag, int update)
1873{
1874    *flag = !*flag;
1875    if (update == UPDATE_BLOBS) {
1876        UpdateBlobs();
1877    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
1878        UpdateBlobs();
1879        InvalidateList(LIST_CROSSES);
1880    }
1881    ForceRefresh();
1882}
1883
1884int GfxCore::GetNumEntrances() const
1885{
1886    return m_Parent->GetNumEntrances();
1887}
1888
1889int GfxCore::GetNumFixedPts() const
1890{
1891    return m_Parent->GetNumFixedPts();
1892}
1893
1894int GfxCore::GetNumExportedPts() const
1895{
1896    return m_Parent->GetNumExportedPts();
1897}
1898
1899void GfxCore::ClearTreeSelection()
1900{
1901    m_Parent->ClearTreeSelection();
1902}
1903
1904void GfxCore::CentreOn(const Point &p)
1905{
1906    SetTranslation(-p);
1907    m_HitTestGridValid = false;
1908
1909    ForceRefresh();
1910}
1911
1912void GfxCore::ForceRefresh()
1913{
1914    Refresh(false);
1915}
1916
1917void GfxCore::GenerateList(unsigned int l)
1918{
1919    assert(m_HaveData);
1920
1921    switch (l) {
1922        case LIST_COMPASS:
1923            DrawCompass();
1924            break;
1925        case LIST_CLINO:
1926            DrawClino();
1927            break;
1928        case LIST_CLINO_BACK:
1929            DrawClinoBack();
1930            break;
1931        case LIST_SCALE_BAR:
1932            DrawScaleBar();
1933            break;
1934        case LIST_DEPTH_KEY:
1935            DrawDepthKey();
1936            break;
1937        case LIST_DATE_KEY:
1938            DrawDateKey();
1939            break;
1940        case LIST_ERROR_KEY:
1941            DrawErrorKey();
1942            break;
1943        case LIST_UNDERGROUND_LEGS:
1944            GenerateDisplayList();
1945            break;
1946        case LIST_TUBES:
1947            GenerateDisplayListTubes();
1948            break;
1949        case LIST_SURFACE_LEGS:
1950            GenerateDisplayListSurface();
1951            break;
1952        case LIST_BLOBS:
1953            GenerateBlobsDisplayList();
1954            break;
1955        case LIST_CROSSES: {
1956            BeginCrosses();
1957            SetColour(col_LIGHT_GREY);
1958            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1959            while (pos != m_Parent->GetLabelsEnd()) {
1960                const LabelInfo* label = *pos++;
1961
1962                if ((m_Surface && label->IsSurface()) ||
1963                    (m_Legs && label->IsUnderground()) ||
1964                    (!label->IsSurface() && !label->IsUnderground())) {
1965                    // Check if this station should be displayed
1966                    // (last case is for stns with no legs attached)
1967                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
1968                }
1969            }
1970            EndCrosses();
1971            break;
1972        }
1973        case LIST_GRID:
1974            DrawGrid();
1975            break;
1976        case LIST_SHADOW:
1977            GenerateDisplayListShadow();
1978            break;
1979        default:
1980            assert(false);
1981            break;
1982    }
1983}
1984
1985void GfxCore::ToggleSmoothShading()
1986{
1987    GLACanvas::ToggleSmoothShading();
1988    InvalidateList(LIST_TUBES);
1989    ForceRefresh();
1990}
1991
1992void GfxCore::GenerateDisplayList()
1993{
1994    // Generate the display list for the underground legs.
1995    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
1996    list<traverse>::const_iterator tend = m_Parent->traverses_end();
1997    while (trav != tend) {
1998        (this->*AddPoly)(*trav);
1999        ++trav;
2000    }
2001}
2002
2003void GfxCore::GenerateDisplayListTubes()
2004{
2005    // Generate the display list for the tubes.
2006    list<vector<XSect> >::const_iterator trav = m_Parent->tubes_begin();
2007    list<vector<XSect> >::const_iterator tend = m_Parent->tubes_end();
2008    while (trav != tend) {
2009        SkinPassage(*trav);
2010        ++trav;
2011    }
2012}
2013
2014void GfxCore::GenerateDisplayListSurface()
2015{
2016    // Generate the display list for the surface legs.
2017    EnableDashedLines();
2018    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2019    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2020    while (trav != tend) {
2021        if (m_ColourBy == COLOUR_BY_ERROR) {
2022            AddPolylineError(*trav);
2023        } else {
2024            AddPolyline(*trav);
2025        }
2026        ++trav;
2027    }
2028    DisableDashedLines();
2029}
2030
2031void GfxCore::GenerateDisplayListShadow()
2032{
2033    SetColour(col_BLACK);
2034    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2035    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2036    while (trav != tend) {
2037        AddPolylineShadow(*trav);
2038        ++trav;
2039    }
2040}
2041
2042// Plot blobs.
2043void GfxCore::GenerateBlobsDisplayList()
2044{
2045    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2046          m_Parent->GetNumHighlightedPts()))
2047        return;
2048
2049    // Plot blobs.
2050    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2051    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2052    BeginBlobs();
2053    while (pos != m_Parent->GetLabelsEnd()) {
2054        const LabelInfo* label = *pos++;
2055
2056        // When more than one flag is set on a point:
2057        // search results take priority over entrance highlighting
2058        // which takes priority over fixed point
2059        // highlighting, which in turn takes priority over exported
2060        // point highlighting.
2061
2062        if (!((m_Surface && label->IsSurface()) ||
2063              (m_Legs && label->IsUnderground()) ||
2064              (!label->IsSurface() && !label->IsUnderground()))) {
2065            // if this station isn't to be displayed, skip to the next
2066            // (last case is for stns with no legs attached)
2067            continue;
2068        }
2069
2070        gla_colour col;
2071
2072        if (label->IsHighLighted()) {
2073            col = col_YELLOW;
2074        } else if (m_Entrances && label->IsEntrance()) {
2075            col = col_GREEN;
2076        } else if (m_FixedPts && label->IsFixedPt()) {
2077            col = col_RED;
2078        } else if (m_ExportedPts && label->IsExportedPt()) {
2079            col = col_TURQUOISE;
2080        } else {
2081            continue;
2082        }
2083
2084        // Stations are sorted by blob type, so colour changes are infrequent.
2085        if (col != prev_col) {
2086            SetColour(col);
2087            prev_col = col;
2088        }
2089        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2090    }
2091    EndBlobs();
2092}
2093
2094void GfxCore::DrawIndicators()
2095{
2096    // Draw colour key.
2097    if (m_ColourKey) {
2098        if (m_ColourBy == COLOUR_BY_DEPTH && m_Parent->GetDepthExtent() != 0.0) {
2099            DrawList2D(LIST_DEPTH_KEY, GetXSize() - KEY_OFFSET_X,
2100                       GetYSize() - KEY_OFFSET_Y, 0);
2101        } else if (m_ColourBy == COLOUR_BY_DATE && HasDateInformation()) {
2102            DrawList2D(LIST_DATE_KEY, GetXSize() - KEY_OFFSET_X,
2103                       GetYSize() - KEY_OFFSET_Y, 0);
2104        } else if (m_ColourBy == COLOUR_BY_ERROR && m_Parent->HasErrorInformation()) {
2105            DrawList2D(LIST_ERROR_KEY, GetXSize() - KEY_OFFSET_X,
2106                       GetYSize() - KEY_OFFSET_Y, 0);
2107        }
2108    }
2109
2110    // Draw compass or elevation/heading indicators.
2111    if (m_Compass || m_Clino) {
2112        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2113    }
2114
2115    // Draw scalebar.
2116    if (m_Scalebar) {
2117        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2118    }
2119}
2120
2121void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2122                                    glaTexCoord tex_x, glaTexCoord tex_y,
2123                                    Double factor)
2124{
2125    SetColour(GetSurfacePen(), factor); // FIXME : assumes surface pen is white!
2126    PlaceVertex(v, tex_x, tex_y);
2127}
2128
2129void GfxCore::SetDepthColour(Double z, Double factor) {
2130    // Set the drawing colour based on the altitude.
2131    Double z_ext = m_Parent->GetDepthExtent();
2132    assert(z_ext > 0);
2133
2134    z -= m_Parent->GetDepthMin();
2135    // points arising from tubes may be slightly outside the limits...
2136    if (z < 0) z = 0;
2137    if (z > z_ext) z = z_ext;
2138
2139    Double how_far = z / z_ext;
2140    assert(how_far >= 0.0);
2141    assert(how_far <= 1.0);
2142
2143    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2144    GLAPen pen1 = GetPen(band);
2145    if (band < GetNumColourBands() - 1) {
2146        const GLAPen& pen2 = GetPen(band + 1);
2147
2148        Double interval = z_ext / (GetNumColourBands() - 1);
2149        Double into_band = z / interval - band;
2150
2151//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2152//             z_offset, interval, band);
2153        // FIXME: why do we need to clamp here?  Is it because the walls can
2154        // extend further up/down than the centre-line?
2155        if (into_band < 0.0) into_band = 0.0;
2156        if (into_band > 1.0) into_band = 1.0;
2157        assert(into_band >= 0.0);
2158        assert(into_band <= 1.0);
2159
2160        pen1.Interpolate(pen2, into_band);
2161    }
2162    SetColour(pen1, factor);
2163}
2164
2165void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2166{
2167    SetDepthColour(v.GetZ(), factor);
2168    PlaceVertex(v);
2169}
2170
2171void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2172                                         glaTexCoord tex_x, glaTexCoord tex_y,
2173                                         Double factor)
2174{
2175    SetDepthColour(v.GetZ(), factor);
2176    PlaceVertex(v, tex_x, tex_y);
2177}
2178
2179void GfxCore::SplitLineAcrossBands(int band, int band2,
2180                                   const Vector3 &p, const Vector3 &q,
2181                                   Double factor)
2182{
2183    const int step = (band < band2) ? 1 : -1;
2184    for (int i = band; i != band2; i += step) {
2185        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2186
2187        // Find the intersection point of the line p -> q
2188        // with the plane parallel to the xy-plane with z-axis intersection z.
2189        assert(q.GetZ() - p.GetZ() != 0.0);
2190
2191        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2192//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2193
2194        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2195        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2196
2197        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2198    }
2199}
2200
2201int GfxCore::GetDepthColour(Double z) const
2202{
2203    // Return the (0-based) depth colour band index for a z-coordinate.
2204    Double z_ext = m_Parent->GetDepthExtent();
2205    assert(z_ext > 0);
2206    z -= m_Parent->GetDepthMin();
2207    z += z_ext / 2;
2208    return int(z / z_ext * (GetNumColourBands() - 1));
2209}
2210
2211Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2212{
2213    // Return the z-coordinate of the depth colour boundary between
2214    // two adjacent depth colour bands (specified by 0-based indices).
2215
2216    assert((a == b - 1) || (a == b + 1));
2217    if (GetNumColourBands() == 1) return 0;
2218
2219    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2220    Double z_ext = m_Parent->GetDepthExtent();
2221    return (z_ext * band / (GetNumColourBands() - 1)) - z_ext / 2
2222        + m_Parent->GetDepthMin();
2223}
2224
2225void GfxCore::AddPolyline(const traverse & centreline)
2226{
2227    BeginPolyline();
2228    SetColour(GetSurfacePen());
2229    vector<PointInfo>::const_iterator i = centreline.begin();
2230    PlaceVertex(*i);
2231    ++i;
2232    while (i != centreline.end()) {
2233        PlaceVertex(*i);
2234        ++i;
2235    }
2236    EndPolyline();
2237}
2238
2239void GfxCore::AddPolylineShadow(const traverse & centreline)
2240{
2241    BeginPolyline();
2242    const double z = -0.5 * m_Parent->GetZExtent();
2243    vector<PointInfo>::const_iterator i = centreline.begin();
2244    PlaceVertex(i->GetX(), i->GetY(), z);
2245    ++i;
2246    while (i != centreline.end()) {
2247        PlaceVertex(i->GetX(), i->GetY(), z);
2248        ++i;
2249    }
2250    EndPolyline();
2251}
2252
2253void GfxCore::AddPolylineDepth(const traverse & centreline)
2254{
2255    BeginPolyline();
2256    vector<PointInfo>::const_iterator i, prev_i;
2257    i = centreline.begin();
2258    int band0 = GetDepthColour(i->GetZ());
2259    PlaceVertexWithDepthColour(*i);
2260    prev_i = i;
2261    ++i;
2262    while (i != centreline.end()) {
2263        int band = GetDepthColour(i->GetZ());
2264        if (band != band0) {
2265            SplitLineAcrossBands(band0, band, *prev_i, *i);
2266            band0 = band;
2267        }
2268        PlaceVertexWithDepthColour(*i);
2269        prev_i = i;
2270        ++i;
2271    }
2272    EndPolyline();
2273}
2274
2275void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
2276                               const Vector3 &c, const Vector3 &d)
2277{
2278    Vector3 normal = (a - c) * (d - b);
2279    normal.normalise();
2280    Double factor = dot(normal, light) * .3 + .7;
2281    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2282    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2283    // FIXME: should plot triangles instead to avoid rendering glitches.
2284    BeginQuadrilaterals();
2285    PlaceVertexWithColour(a, 0, 0, factor);
2286    PlaceVertexWithColour(b, w, 0, factor);
2287    PlaceVertexWithColour(c, w, h, factor);
2288    PlaceVertexWithColour(d, 0, h, factor);
2289    EndQuadrilaterals();
2290}
2291
2292void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2293                                    const Vector3 &c, const Vector3 &d)
2294{
2295    Vector3 normal = (a - c) * (d - b);
2296    normal.normalise();
2297    Double factor = dot(normal, light) * .3 + .7;
2298    int a_band, b_band, c_band, d_band;
2299    a_band = GetDepthColour(a.GetZ());
2300    a_band = min(max(a_band, 0), GetNumColourBands());
2301    b_band = GetDepthColour(b.GetZ());
2302    b_band = min(max(b_band, 0), GetNumColourBands());
2303    c_band = GetDepthColour(c.GetZ());
2304    c_band = min(max(c_band, 0), GetNumColourBands());
2305    d_band = GetDepthColour(d.GetZ());
2306    d_band = min(max(d_band, 0), GetNumColourBands());
2307    // All this splitting is incorrect - we need to make a separate polygon
2308    // for each depth band...
2309    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2310    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2311    BeginPolygon();
2312////    PlaceNormal(normal);
2313    PlaceVertexWithDepthColour(a, 0, 0, factor);
2314    if (a_band != b_band) {
2315        SplitLineAcrossBands(a_band, b_band, a, b, factor);
2316    }
2317    PlaceVertexWithDepthColour(b, w, 0, factor);
2318    if (b_band != c_band) {
2319        SplitLineAcrossBands(b_band, c_band, b, c, factor);
2320    }
2321    PlaceVertexWithDepthColour(c, w, h, factor);
2322    if (c_band != d_band) {
2323        SplitLineAcrossBands(c_band, d_band, c, d, factor);
2324    }
2325    PlaceVertexWithDepthColour(d, 0, h, factor);
2326    if (d_band != a_band) {
2327        SplitLineAcrossBands(d_band, a_band, d, a, factor);
2328    }
2329    EndPolygon();
2330}
2331
2332void GfxCore::SetColourFromDate(int date, Double factor)
2333{
2334    // Set the drawing colour based on a date.
2335
2336    if (date == -1) {
2337        // Undated.
2338        SetColour(GetSurfacePen(), factor);
2339        return;
2340    }
2341
2342    int date_offset = date - m_Parent->GetDateMin();
2343    if (date_offset == 0) {
2344        // Earliest date - handle as a special case for the single date case.
2345        SetColour(GetPen(0), factor);
2346        return;
2347    }
2348
2349    int date_ext = m_Parent->GetDateExtent();
2350    Double how_far = (Double)date_offset / date_ext;
2351    assert(how_far >= 0.0);
2352    assert(how_far <= 1.0);
2353
2354    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2355    GLAPen pen1 = GetPen(band);
2356    if (band < GetNumColourBands() - 1) {
2357        const GLAPen& pen2 = GetPen(band + 1);
2358
2359        Double interval = date_ext / (GetNumColourBands() - 1);
2360        Double into_band = date_offset / interval - band;
2361
2362//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2363//             z_offset, interval, band);
2364        // FIXME: why do we need to clamp here?  Is it because the walls can
2365        // extend further up/down than the centre-line?
2366        if (into_band < 0.0) into_band = 0.0;
2367        if (into_band > 1.0) into_band = 1.0;
2368        assert(into_band >= 0.0);
2369        assert(into_band <= 1.0);
2370
2371        pen1.Interpolate(pen2, into_band);
2372    }
2373    SetColour(pen1, factor);
2374}
2375
2376void GfxCore::AddPolylineDate(const traverse & centreline)
2377{
2378    BeginPolyline();
2379    vector<PointInfo>::const_iterator i, prev_i;
2380    i = centreline.begin();
2381    int date = i->GetDate();
2382    SetColourFromDate(date, 1.0);
2383    PlaceVertex(*i);
2384    prev_i = i;
2385    while (++i != centreline.end()) {
2386        int newdate = i->GetDate();
2387        if (newdate != date) {
2388            EndPolyline();
2389            BeginPolyline();
2390            date = newdate;
2391            SetColourFromDate(date, 1.0);
2392            PlaceVertex(*prev_i);
2393        }
2394        PlaceVertex(*i);
2395        prev_i = i;
2396    }
2397    EndPolyline();
2398}
2399
2400static int static_date_hack; // FIXME
2401
2402void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2403                                   const Vector3 &c, const Vector3 &d)
2404{
2405    Vector3 normal = (a - c) * (d - b);
2406    normal.normalise();
2407    Double factor = dot(normal, light) * .3 + .7;
2408    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2409    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2410    // FIXME: should plot triangles instead to avoid rendering glitches.
2411    BeginQuadrilaterals();
2412////    PlaceNormal(normal);
2413    SetColourFromDate(static_date_hack, factor);
2414    PlaceVertex(a, 0, 0);
2415    PlaceVertex(b, w, 0);
2416    PlaceVertex(c, w, h);
2417    PlaceVertex(d, 0, h);
2418    EndQuadrilaterals();
2419}
2420
2421static double static_E_hack; // FIXME
2422
2423void GfxCore::SetColourFromError(double E, Double factor)
2424{
2425    // Set the drawing colour based on an error value.
2426
2427    if (E < 0) {
2428        SetColour(GetSurfacePen(), factor);
2429        return;
2430    }
2431
2432    Double how_far = E / MAX_ERROR;
2433    assert(how_far >= 0.0);
2434    if (how_far > 1.0) how_far = 1.0;
2435
2436    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2437    GLAPen pen1 = GetPen(band);
2438    if (band < GetNumColourBands() - 1) {
2439        const GLAPen& pen2 = GetPen(band + 1);
2440
2441        Double interval = MAX_ERROR / (GetNumColourBands() - 1);
2442        Double into_band = E / interval - band;
2443
2444//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2445//             z_offset, interval, band);
2446        // FIXME: why do we need to clamp here?  Is it because the walls can
2447        // extend further up/down than the centre-line?
2448        if (into_band < 0.0) into_band = 0.0;
2449        if (into_band > 1.0) into_band = 1.0;
2450        assert(into_band >= 0.0);
2451        assert(into_band <= 1.0);
2452
2453        pen1.Interpolate(pen2, into_band);
2454    }
2455    SetColour(pen1, factor);
2456}
2457
2458void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2459                                    const Vector3 &c, const Vector3 &d)
2460{
2461    Vector3 normal = (a - c) * (d - b);
2462    normal.normalise();
2463    Double factor = dot(normal, light) * .3 + .7;
2464    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2465    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2466    // FIXME: should plot triangles instead to avoid rendering glitches.
2467    BeginQuadrilaterals();
2468////    PlaceNormal(normal);
2469    SetColourFromError(static_E_hack, factor);
2470    PlaceVertex(a, 0, 0);
2471    PlaceVertex(b, w, 0);
2472    PlaceVertex(c, w, h);
2473    PlaceVertex(d, 0, h);
2474    EndQuadrilaterals();
2475}
2476
2477void GfxCore::AddPolylineError(const traverse & centreline)
2478{
2479    BeginPolyline();
2480    SetColourFromError(centreline.E, 1.0);
2481    vector<PointInfo>::const_iterator i;
2482    for(i = centreline.begin(); i != centreline.end(); ++i) {
2483        PlaceVertex(*i);
2484    }
2485    EndPolyline();
2486}
2487
2488void
2489GfxCore::SkinPassage(const vector<XSect> & centreline)
2490{
2491    assert(centreline.size() > 1);
2492    Vector3 U[4];
2493    XSect prev_pt_v;
2494    Vector3 last_right(1.0, 0.0, 0.0);
2495
2496//  FIXME: it's not simple to set the colour of a tube based on error...
2497//    static_E_hack = something...
2498    vector<XSect>::const_iterator i = centreline.begin();
2499    vector<XSect>::size_type segment = 0;
2500    while (i != centreline.end()) {
2501        // get the coordinates of this vertex
2502        const XSect & pt_v = *i++;
2503
2504        double z_pitch_adjust = 0.0;
2505        bool cover_end = false;
2506
2507        Vector3 right, up;
2508
2509        const Vector3 up_v(0.0, 0.0, 1.0);
2510
2511        if (segment == 0) {
2512            assert(i != centreline.end());
2513            // first segment
2514
2515            // get the coordinates of the next vertex
2516            const XSect & next_pt_v = *i;
2517
2518            // calculate vector from this pt to the next one
2519            Vector3 leg_v = next_pt_v - pt_v;
2520
2521            // obtain a vector in the LRUD plane
2522            right = leg_v * up_v;
2523            if (right.magnitude() == 0) {
2524                right = last_right;
2525                // Obtain a second vector in the LRUD plane,
2526                // perpendicular to the first.
2527                //up = right * leg_v;
2528                up = up_v;
2529            } else {
2530                last_right = right;
2531                up = up_v;
2532            }
2533
2534            cover_end = true;
2535            static_date_hack = next_pt_v.GetDate();
2536        } else if (segment + 1 == centreline.size()) {
2537            // last segment
2538
2539            // Calculate vector from the previous pt to this one.
2540            Vector3 leg_v = pt_v - prev_pt_v;
2541
2542            // Obtain a horizontal vector in the LRUD plane.
2543            right = leg_v * up_v;
2544            if (right.magnitude() == 0) {
2545                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
2546                // Obtain a second vector in the LRUD plane,
2547                // perpendicular to the first.
2548                //up = right * leg_v;
2549                up = up_v;
2550            } else {
2551                last_right = right;
2552                up = up_v;
2553            }
2554
2555            cover_end = true;
2556            static_date_hack = pt_v.GetDate();
2557        } else {
2558            assert(i != centreline.end());
2559            // Intermediate segment.
2560
2561            // Get the coordinates of the next vertex.
2562            const XSect & next_pt_v = *i;
2563
2564            // Calculate vectors from this vertex to the
2565            // next vertex, and from the previous vertex to
2566            // this one.
2567            Vector3 leg1_v = pt_v - prev_pt_v;
2568            Vector3 leg2_v = next_pt_v - pt_v;
2569
2570            // Obtain horizontal vectors perpendicular to
2571            // both legs, then normalise and average to get
2572            // a horizontal bisector.
2573            Vector3 r1 = leg1_v * up_v;
2574            Vector3 r2 = leg2_v * up_v;
2575            r1.normalise();
2576            r2.normalise();
2577            right = r1 + r2;
2578            if (right.magnitude() == 0) {
2579                // This is the "mid-pitch" case...
2580                right = last_right;
2581            }
2582            if (r1.magnitude() == 0) {
2583                Vector3 n = leg1_v;
2584                n.normalise();
2585                z_pitch_adjust = n.GetZ();
2586                //up = Vector3(0, 0, leg1_v.GetZ());
2587                //up = right * up;
2588                up = up_v;
2589
2590                // Rotate pitch section to minimise the
2591                // "tortional stress" - FIXME: use
2592                // triangles instead of rectangles?
2593                int shift = 0;
2594                Double maxdotp = 0;
2595
2596                // Scale to unit vectors in the LRUD plane.
2597                right.normalise();
2598                up.normalise();
2599                Vector3 vec = up - right;
2600                for (int orient = 0; orient <= 3; ++orient) {
2601                    Vector3 tmp = U[orient] - prev_pt_v;
2602                    tmp.normalise();
2603                    Double dotp = dot(vec, tmp);
2604                    if (dotp > maxdotp) {
2605                        maxdotp = dotp;
2606                        shift = orient;
2607                    }
2608                }
2609                if (shift) {
2610                    if (shift != 2) {
2611                        Vector3 temp(U[0]);
2612                        U[0] = U[shift];
2613                        U[shift] = U[2];
2614                        U[2] = U[shift ^ 2];
2615                        U[shift ^ 2] = temp;
2616                    } else {
2617                        swap(U[0], U[2]);
2618                        swap(U[1], U[3]);
2619                    }
2620                }
2621#if 0
2622                // Check that the above code actually permuted
2623                // the vertices correctly.
2624                shift = 0;
2625                maxdotp = 0;
2626                for (int j = 0; j <= 3; ++j) {
2627                    Vector3 tmp = U[j] - prev_pt_v;
2628                    tmp.normalise();
2629                    Double dotp = dot(vec, tmp);
2630                    if (dotp > maxdotp) {
2631                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
2632                        shift = j;
2633                    }
2634                }
2635                if (shift) {
2636                    printf("New shift = %d!\n", shift);
2637                    shift = 0;
2638                    maxdotp = 0;
2639                    for (int j = 0; j <= 3; ++j) {
2640                        Vector3 tmp = U[j] - prev_pt_v;
2641                        tmp.normalise();
2642                        Double dotp = dot(vec, tmp);
2643                        printf("    %d : %.8f\n", j, dotp);
2644                    }
2645                }
2646#endif
2647            } else if (r2.magnitude() == 0) {
2648                Vector3 n = leg2_v;
2649                n.normalise();
2650                z_pitch_adjust = n.GetZ();
2651                //up = Vector3(0, 0, leg2_v.GetZ());
2652                //up = right * up;
2653                up = up_v;
2654            } else {
2655                up = up_v;
2656            }
2657            last_right = right;
2658            static_date_hack = pt_v.GetDate();
2659        }
2660
2661        // Scale to unit vectors in the LRUD plane.
2662        right.normalise();
2663        up.normalise();
2664
2665        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
2666
2667        Double l = fabs(pt_v.GetL());
2668        Double r = fabs(pt_v.GetR());
2669        Double u = fabs(pt_v.GetU());
2670        Double d = fabs(pt_v.GetD());
2671
2672        // Produce coordinates of the corners of the LRUD "plane".
2673        Vector3 v[4];
2674        v[0] = pt_v - right * l + up * u;
2675        v[1] = pt_v + right * r + up * u;
2676        v[2] = pt_v + right * r - up * d;
2677        v[3] = pt_v - right * l - up * d;
2678
2679        if (segment > 0) {
2680            (this->*AddQuad)(v[0], v[1], U[1], U[0]);
2681            (this->*AddQuad)(v[2], v[3], U[3], U[2]);
2682            (this->*AddQuad)(v[1], v[2], U[2], U[1]);
2683            (this->*AddQuad)(v[3], v[0], U[0], U[3]);
2684        }
2685
2686        if (cover_end) {
2687            (this->*AddQuad)(v[3], v[2], v[1], v[0]);
2688        }
2689
2690        prev_pt_v = pt_v;
2691        U[0] = v[0];
2692        U[1] = v[1];
2693        U[2] = v[2];
2694        U[3] = v[3];
2695
2696        ++segment;
2697    }
2698}
2699
2700void GfxCore::FullScreenMode()
2701{
2702    m_Parent->ViewFullScreen();
2703}
2704
2705bool GfxCore::IsFullScreen() const
2706{
2707    return m_Parent->IsFullScreen();
2708}
2709
2710void
2711GfxCore::MoveViewer(double forward, double up, double right)
2712{
2713    double cT = cos(rad(m_TiltAngle));
2714    double sT = sin(rad(m_TiltAngle));
2715    double cP = cos(rad(m_PanAngle));
2716    double sP = sin(rad(m_PanAngle));
2717    Vector3 v_forward(cT * sP, cT * cP, -sT);
2718    Vector3 v_up(-sT * sP, -sT * cP, -cT);
2719    Vector3 v_right(-cP, sP, 0);
2720    assert(fabs(dot(v_forward, v_up)) < 1e-6);
2721    assert(fabs(dot(v_forward, v_right)) < 1e-6);
2722    assert(fabs(dot(v_right, v_up)) < 1e-6);
2723    Vector3 move = v_forward * forward + v_up * up + v_right * right;
2724    AddTranslation(-move);
2725    // Show current position.
2726    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
2727    ForceRefresh();
2728}
2729
2730PresentationMark GfxCore::GetView() const
2731{
2732    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
2733                            m_PanAngle, m_TiltAngle, m_Scale);
2734}
2735
2736void GfxCore::SetView(const PresentationMark & p)
2737{
2738    m_SwitchingTo = 0;
2739    SetTranslation(p - m_Parent->GetOffset());
2740    m_PanAngle = p.angle;
2741    m_TiltAngle = p.tilt_angle;
2742    SetRotation(m_PanAngle, m_TiltAngle);
2743    SetScale(p.scale);
2744    ForceRefresh();
2745}
2746
2747void GfxCore::PlayPres(double speed, bool change_speed) {
2748    if (!change_speed || presentation_mode == 0) {
2749        if (speed == 0.0) {
2750            presentation_mode = 0;
2751            return;
2752        }
2753        presentation_mode = PLAYING;
2754        next_mark = m_Parent->GetPresMark(MARK_FIRST);
2755        SetView(next_mark);
2756        next_mark_time = 0; // There already!
2757        this_mark_total = 0;
2758        pres_reverse = (speed < 0);
2759    }
2760
2761    if (change_speed) pres_speed = speed;
2762
2763    if (speed != 0.0) {
2764        bool new_pres_reverse = (speed < 0);
2765        if (new_pres_reverse != pres_reverse) {
2766            pres_reverse = new_pres_reverse;
2767            if (pres_reverse) {
2768                next_mark = m_Parent->GetPresMark(MARK_PREV);
2769            } else {
2770                next_mark = m_Parent->GetPresMark(MARK_NEXT);
2771            }
2772            swap(this_mark_total, next_mark_time);
2773        }
2774    }
2775}
2776
2777void GfxCore::SetColourBy(int colour_by) {
2778    m_ColourBy = colour_by;
2779    switch (colour_by) {
2780        case COLOUR_BY_DEPTH:
2781            AddQuad = &GfxCore::AddQuadrilateralDepth;
2782            AddPoly = &GfxCore::AddPolylineDepth;
2783            break;
2784        case COLOUR_BY_DATE:
2785            AddQuad = &GfxCore::AddQuadrilateralDate;
2786            AddPoly = &GfxCore::AddPolylineDate;
2787            break;
2788        case COLOUR_BY_ERROR:
2789            AddQuad = &GfxCore::AddQuadrilateralError;
2790            AddPoly = &GfxCore::AddPolylineError;
2791            break;
2792        default: // case COLOUR_BY_NONE:
2793            AddQuad = &GfxCore::AddQuadrilateral;
2794            AddPoly = &GfxCore::AddPolyline;
2795            break;
2796    }
2797
2798    InvalidateList(LIST_UNDERGROUND_LEGS);
2799    InvalidateList(LIST_SURFACE_LEGS);
2800    InvalidateList(LIST_TUBES);
2801
2802    ForceRefresh();
2803}
2804
2805bool GfxCore::ExportMovie(const wxString & fnm)
2806{
2807    int width;
2808    int height;
2809    GetSize(&width, &height);
2810    // Round up to next multiple of 2 (required by ffmpeg).
2811    width += (width & 1);
2812    height += (height & 1);
2813
2814    movie = new MovieMaker();
2815
2816    // FIXME: This should really use fn_str() - currently we probably can't
2817    // save to a Unicode path on wxmsw.
2818    if (!movie->Open(fnm.mb_str(), width, height)) {
2819        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
2820        delete movie;
2821        movie = NULL;
2822        return false;
2823    }
2824
2825    PlayPres(1);
2826    return true;
2827}
2828
2829void
2830GfxCore::OnPrint(const wxString &filename, const wxString &title,
2831                 const wxString &datestamp)
2832{
2833    svxPrintDlg * p;
2834    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
2835                        m_PanAngle, m_TiltAngle,
2836                        m_Names, m_Crosses, m_Legs, m_Surface,
2837                        true);
2838    p->Show(TRUE);
2839}
2840
2841void
2842GfxCore::OnExport(const wxString &filename, const wxString &title)
2843{
2844    svxPrintDlg * p;
2845    p = new svxPrintDlg(m_Parent, filename, title, wxString(),
2846                        m_PanAngle, m_TiltAngle,
2847                        m_Names, m_Crosses, m_Legs, m_Surface,
2848                        false);
2849    p->Show(TRUE);
2850}
2851
2852static wxCursor
2853make_cursor(const unsigned char * bits, const unsigned char * mask,
2854            int hotx, int hoty)
2855{
2856#if defined __WXMSW__ || defined __WXMAC__
2857    wxBitmap cursor_bitmap(reinterpret_cast<const char *>(bits), 32, 32);
2858    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
2859    cursor_bitmap.SetMask(new wxMask(mask_bitmap));
2860    wxImage cursor_image = cursor_bitmap.ConvertToImage();
2861    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
2862    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
2863    return wxCursor(cursor_image);
2864#else
2865    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
2866                    (const char *)mask, wxWHITE, wxBLACK);
2867#endif
2868}
2869
2870const
2871#include "hand.xbm"
2872const
2873#include "handmask.xbm"
2874
2875const
2876#include "brotate.xbm"
2877const
2878#include "brotatemask.xbm"
2879
2880const
2881#include "vrotate.xbm"
2882const
2883#include "vrotatemask.xbm"
2884
2885const
2886#include "rotate.xbm"
2887const
2888#include "rotatemask.xbm"
2889
2890const
2891#include "rotatezoom.xbm"
2892const
2893#include "rotatezoommask.xbm"
2894
2895void
2896GfxCore::SetCursor(GfxCore::cursor new_cursor)
2897{
2898    // Check if we're already showing that cursor.
2899    if (current_cursor == new_cursor) return;
2900
2901    current_cursor = new_cursor;
2902    switch (current_cursor) {
2903        case GfxCore::CURSOR_DEFAULT:
2904            GLACanvas::SetCursor(wxNullCursor);
2905            break;
2906        case GfxCore::CURSOR_POINTING_HAND:
2907            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
2908            break;
2909        case GfxCore::CURSOR_DRAGGING_HAND:
2910            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
2911            break;
2912        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
2913            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
2914            break;
2915        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
2916            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
2917            break;
2918        case GfxCore::CURSOR_ROTATE_VERTICALLY:
2919            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
2920            break;
2921        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
2922            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
2923            break;
2924        case GfxCore::CURSOR_ZOOM:
2925            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
2926            break;
2927        case GfxCore::CURSOR_ZOOM_ROTATE:
2928            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
2929            break;
2930    }
2931}
2932
2933bool GfxCore::MeasuringLineActive() const
2934{
2935    if (Animating()) return false;
2936    return (m_here.IsValid() && !m_here_is_temporary) || m_there.IsValid();
2937}
2938
2939bool GfxCore::HandleRClick(wxPoint point)
2940{
2941    if (PointWithinCompass(point)) {
2942        // Pop up menu.
2943        wxMenu menu;
2944        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
2945        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
2946        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
2947        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
2948        menu.AppendSeparator();
2949        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/344));
2950        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
2951        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
2952        PopupMenu(&menu);
2953        return true;
2954    }
2955
2956    if (PointWithinClino(point)) {
2957        // Pop up menu.
2958        wxMenu menu;
2959        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
2960        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
2961        menu.AppendSeparator();
2962        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
2963        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
2964        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
2965        PopupMenu(&menu);
2966        return true;
2967    }
2968
2969    if (PointWithinScaleBar(point)) {
2970        // Pop up menu.
2971        wxMenu menu;
2972        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
2973        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
2974        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
2975        PopupMenu(&menu);
2976        return true;
2977    }
2978
2979    if (PointWithinColourKey(point)) {
2980        // Pop up menu.
2981        wxMenu menu;
2982        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
2983        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
2984        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
2985        menu.AppendSeparator();
2986        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
2987        if (m_ColourBy == COLOUR_BY_DEPTH)
2988            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
2989        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
2990        PopupMenu(&menu);
2991        return true;
2992    }
2993
2994    return false;
2995}
Note: See TracBrowser for help on using the repository browser.