source: git/src/gfxcore.cc @ 1c448e1

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

src/gfxcore.cc: Simplify accounting for size of blobs on measuring
line.

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