source: git/src/gfxcore.cc @ 46acc71

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

src/gfxcore.cc,src/gla-gl.cc,src/gla.h: Remove
GLACanvas::SetBackgroundColour?() since we only ever set it to black
and opaque.

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

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