source: git/src/gfxcore.cc @ 880b954

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

doc/manual.sgml,src/aventreectrl.cc,src/gfxcore.cc,src/mainfrm.h:
Correctly capitalise "GTK".

git-svn-id: file:///home/survex-svn/survex/branches/survex-1_1@3451 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

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