source: git/src/gfxcore.cc @ 3585243

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

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

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

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