source: git/src/gfxcore.cc @ 82277dd

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 82277dd was 82277dd, checked in by Olly Betts <olly@…>, 10 years ago

src/gfxcore.cc: Don't default to percent gradient.

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