source: git/src/gfxcore.cc @ edf0717

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

src/gfxcore.cc,src/printwx.cc,src/printwx.h: Default the export/print
settings for passage related things to the "tubes" setting in the
OpenGL view.

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