source: git/src/gfxcore.cc @ 11c7eb6

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

src/gfxcore.cc,src/gfxcore.h: No need to dynamically allocate
m_Pens.

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