source: git/src/gfxcore.cc @ 70acad9

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

src/gfxcore.cc,src/gla.h: Fix zoom in limit to be the same distance
regardless of the extent of the survey.

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

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