source: git/src/gfxcore.cc @ f15ca67f

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

src/gfxcore.cc,src/gfxcore.h: Update copyright years.

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

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