source: git/src/gfxcore.cc @ f9ca87c

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

doc/TODO.htm,src/gfxcore.cc,src/gla-gl.cc,src/gla.h: Eliminate the
last few OpenGL calls from gfxcore.cc.

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

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