source: git/src/gla-gl.cc @ 6616cdbf

stereo
Last change on this file since 6616cdbf was 6616cdbf, checked in by Olly Betts <olly@…>, 7 years ago

Push stereo OpenGL code down to gla layer

  • Property mode set to 100644
File size: 50.7 KB
RevLine 
[56da40e]1//
2//  gla-gl.cc
3//
4//  OpenGL implementation for the GLA abstraction layer.
5//
[f4c5932]6//  Copyright (C) 2002-2003,2005 Mark R. Shinwell
[522e0bd]7//  Copyright (C) 2003,2004,2005,2006,2007,2010,2011,2012,2013,2014,2015,2017,2018 Olly Betts
[56da40e]8//
9//  This program is free software; you can redistribute it and/or modify
10//  it under the terms of the GNU General Public License as published by
11//  the Free Software Foundation; either version 2 of the License, or
12//  (at your option) any later version.
13//
14//  This program is distributed in the hope that it will be useful,
15//  but WITHOUT ANY WARRANTY; without even the implied warranty of
16//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17//  GNU General Public License for more details.
18//
19//  You should have received a copy of the GNU General Public License
20//  along with this program; if not, write to the Free Software
[ecbc6c18]21//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
[56da40e]22//
23
[cbfa50d]24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
[bd551c0]28#include <wx/confbase.h>
[ee41e88]29#include <wx/image.h>
[bd551c0]30
[87cab10]31#include <algorithm>
32
[78924eb]33#include "aven.h"
[56da40e]34#include "gla.h"
[bd551c0]35#include "message.h"
[e577f89]36#include "useful.h"
[1eeb55a]37
[ee63994]38#ifdef HAVE_GL_GL_H
39# include <GL/gl.h>
40#elif defined HAVE_OPENGL_GL_H
41# include <OpenGL/gl.h>
42#endif
43
[de4b099]44#ifdef HAVE_GL_GLEXT_H
45# include <GL/glext.h>
46#elif defined HAVE_OPENGL_GLEXT_H
[ee63994]47# include <OpenGL/glext.h>
[b72f4b5]48#endif
[f960f23]49
[b05f516]50#ifndef GL_POINT_SIZE_MAX
51#define GL_POINT_SIZE_MAX 0x8127
52#endif
[9baa53a]53#ifndef GL_POINT_SPRITE
54#define GL_POINT_SPRITE 0x8861
[f960f23]55#endif
[9baa53a]56#ifndef GL_COORD_REPLACE
57#define GL_COORD_REPLACE 0x8862
[f960f23]58#endif
[04bf822]59// GL_POINT_SIZE_RANGE is deprecated in OpenGL 1.2 and later, and replaced by
60// GL_SMOOTH_POINT_SIZE_RANGE.
61#ifndef GL_SMOOTH_POINT_SIZE_RANGE
62#define GL_SMOOTH_POINT_SIZE_RANGE GL_POINT_SIZE_RANGE
63#endif
64// GL_POINT_SIZE_GRANULARITY is deprecated in OpenGL 1.2 and later, and
65// replaced by GL_SMOOTH_POINT_SIZE_GRANULARITY.
66#ifndef GL_SMOOTH_POINT_SIZE_GRANULARITY
67#define GL_SMOOTH_POINT_SIZE_GRANULARITY GL_POINT_SIZE_GRANULARITY
68#endif
69// GL_ALIASED_POINT_SIZE_RANGE was added in OpenGL 1.2.
70#ifndef GL_ALIASED_POINT_SIZE_RANGE
71#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
72#endif
[f960f23]73
[87cab10]74using namespace std;
75
[bde8c9a]76const int BLOB_DIAMETER = 5;
[4ba80e0]77
[edfaf35]78#define BLOB_TEXTURE \
79            o, o, o, o, o, o, o, o,\
80            o, o, o, o, o, o, o, o,\
81            o, o, I, I, I, o, o, o,\
82            o, I, I, I, I, I, o, o,\
83            o, I, I, I, I, I, o, o,\
84            o, I, I, I, I, I, o, o,\
85            o, o, I, I, I, o, o, o,\
86            o, o, o, o, o, o, o, o
87
88#define CROSS_TEXTURE \
89            o, o, o, o, o, o, o, o,\
90            I, o, o, o, o, o, I, o,\
91            o, I, o, o, o, I, o, o,\
92            o, o, I, o, I, o, o, o,\
93            o, o, o, I, o, o, o, o,\
94            o, o, I, o, I, o, o, o,\
95            o, I, o, o, o, I, o, o,\
96            I, o, o, o, o, o, I, o
97
[4f3e5d1]98static bool opengl_initialised = false;
99
[caa5fda]100static bool double_buffered = false;
101
[236a1b1]102static stereo_mode_type stereo_mode_static = STEREO_MONO;
103
[caa5fda]104static const int* wx_gl_attribs = NULL;
105
106bool
107GLACanvas::check_visual()
108{
109    static const int wx_gl_attribs_full[] = {
110        WX_GL_DOUBLEBUFFER,
111        WX_GL_RGBA,
[236a1b1]112        WX_GL_DEPTH_SIZE, 16,
113        0
114    };
115
116    static const int wx_gl_stereo_attribs_full[] = {
117        WX_GL_DOUBLEBUFFER,
118        WX_GL_RGBA,
[36da3f6]119        WX_GL_STEREO,
[caa5fda]120        WX_GL_DEPTH_SIZE, 16,
121        0
122    };
123
124    // Use a double-buffered visual if available, as it will give much smoother
125    // animation.
126    double_buffered = true;
[236a1b1]127    if (stereo_mode_static == STEREO_BUFFERS) {
128       wx_gl_attribs = wx_gl_stereo_attribs_full;
129    } else {
130       wx_gl_attribs = wx_gl_attribs_full;
131    }
[caa5fda]132    if (!IsDisplaySupported(wx_gl_attribs)) {
133        ++wx_gl_attribs;
134        if (!IsDisplaySupported(wx_gl_attribs)) {
135            return false;
136        }
137        double_buffered = false;
138    }
139    return true;
140}
141
[236a1b1]142void GLACanvas::SetStereoMode(stereo_mode_type mode)
143{
144    stereo_mode_static = mode;
145}
146
[5627cbb]147string GetGLSystemDescription()
[cc1a1d9]148{
[4f3e5d1]149    // If OpenGL isn't initialised we may get a SEGV from glGetString.
150    if (!opengl_initialised)
151        return "No OpenGL information available yet - try opening a file.";
[cc1a1d9]152    const char *p = (const char*)glGetString(GL_VERSION);
[4f3e5d1]153    if (!p)
154        return "Couldn't read OpenGL version!";
[cc1a1d9]155
[5627cbb]156    string info;
[cc1a1d9]157    info += "OpenGL ";
158    info += p;
159    info += '\n';
160    info += (const char*)glGetString(GL_VENDOR);
161    info += '\n';
162    info += (const char*)glGetString(GL_RENDERER);
[90688f5]163#if defined __WXGTK__ || defined __WXX11__ || defined __WXMOTIF__
[c293aa9]164    info += string_format("\nGLX %0.1f\n", wxGLCanvas::GetGLXVersion() * 0.1);
[a6c5ffb]165#else
166    info += '\n';
[90688f5]167#endif
[cc1a1d9]168
169    GLint red, green, blue;
170    glGetIntegerv(GL_RED_BITS, &red);
171    glGetIntegerv(GL_GREEN_BITS, &green);
172    glGetIntegerv(GL_BLUE_BITS, &blue);
173    GLint max_texture_size;
174    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
175    GLint max_viewport[2];
176    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, max_viewport);
177    GLdouble point_size_range[2];
[04bf822]178    glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
[cc1a1d9]179    GLdouble point_size_granularity;
[04bf822]180    glGetDoublev(GL_SMOOTH_POINT_SIZE_GRANULARITY, &point_size_granularity);
[5627cbb]181    info += string_format("R%dG%dB%d\n"
[cc1a1d9]182             "Max Texture size: %dx%d\n"
183             "Max Viewport size: %dx%d\n"
[04bf822]184             "Smooth Point Size %.3f-%.3f (granularity %.3f)",
[cc1a1d9]185             (int)red, (int)green, (int)blue,
186             (int)max_texture_size, (int)max_texture_size,
187             (int)max_viewport[0], (int)max_viewport[1],
188             point_size_range[0], point_size_range[1],
189             point_size_granularity);
[04bf822]190    glGetDoublev(GL_ALIASED_POINT_SIZE_RANGE, point_size_range);
191    if (glGetError() != GL_INVALID_ENUM) {
192        info += string_format("\nAliased point size %.3f-%.3f",
193                              point_size_range[0], point_size_range[1]);
194    }
[5627cbb]195
[c293aa9]196    info += "\nDouble buffered: ";
197    if (double_buffered)
198        info += "true";
199    else
200        info += "false";
201
[5627cbb]202    const GLubyte* gl_extensions = glGetString(GL_EXTENSIONS);
203    if (*gl_extensions) {
204        info += '\n';
205        info += (const char*)gl_extensions;
206    }
[cc1a1d9]207    return info;
208}
209
[fc5f476]210static bool
211glpoint_sprite_works()
212{
213    // Point sprites provide an easy, fast way for us to draw crosses by
214    // texture mapping GL points.
215    //
216    // If we have OpenGL >= 2.0 then we definitely have GL_POINT_SPRITE.
217    // Otherwise see if we have the GL_ARB_point_sprite or GL_NV_point_sprite
218    // extensions.
219    //
220    // The symbolic constants GL_POINT_SPRITE, GL_POINT_SPRITE_ARB, and
221    // GL_POINT_SPRITE_NV all give the same number so it doesn't matter
222    // which we use.
223    static bool glpoint_sprite = false;
224    static bool checked = false;
225    if (!checked) {
226        float maxSize = 0.0f;
227        glGetFloatv(GL_POINT_SIZE_MAX, &maxSize);
228        if (maxSize >= 8) {
229            glpoint_sprite = (atoi((const char *)glGetString(GL_VERSION)) >= 2);
230            if (!glpoint_sprite) {
231                const char * p = (const char *)glGetString(GL_EXTENSIONS);
232                while (true) {
233                    size_t l = 0;
234                    if (memcmp(p, "GL_ARB_point_sprite", 19) == 0) {
235                        l = 19;
236                    } else if (memcmp(p, "GL_NV_point_sprite", 18) == 0) {
237                        l = 18;
238                    }
239                    if (l) {
240                        p += l;
241                        if (*p == '\0' || *p == ' ') {
242                            glpoint_sprite = true;
243                            break;
244                        }
245                    }
246                    p = strchr(p + 1, ' ');
247                    if (!p) break;
248                    ++p;
249                }
250            }
251        }
252        checked = true;
253    }
254    return glpoint_sprite;
255}
256
[963e611]257static void
258log_gl_error(const wxChar * str, GLenum error_code)
259{
260    const char * e = reinterpret_cast<const char *>(gluErrorString(error_code));
261    wxLogError(str, wxString(e, wxConvUTF8).c_str());
262}
263
[1b12b82]264// Important: CHECK_GL_ERROR must not be called within a glBegin()/glEnd() pair
265//            (thus it must not be called from BeginLines(), etc., or within a
266//             BeginLines()/EndLines() block etc.)
[335a9be]267#define CHECK_GL_ERROR(M, F) do { \
[19b2f99]268    if (!opengl_initialised) { \
[1c55fb5]269        wxLogError(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL not initialised before (call " F " in method " M ")")); \
[19b2f99]270    } \
[335a9be]271    GLenum error_code_ = glGetError(); \
[19bbc1fc]272    if (error_code_ != GL_NO_ERROR) { \
[1c55fb5]273        log_gl_error(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL error: %s " \
274                         "(call " F " in method " M ")"), error_code_); \
[19bbc1fc]275    } \
[335a9be]276} while (0)
[1897247]277
[56da40e]278//
279//  GLAPen
[096e56c]280//
[56da40e]281
[aa048c3]282GLAPen::GLAPen()
[56da40e]283{
[aa048c3]284    components[0] = components[1] = components[2] = 0.0;
[56da40e]285}
286
287void GLAPen::SetColour(double red, double green, double blue)
288{
[aa048c3]289    components[0] = red;
290    components[1] = green;
291    components[2] = blue;
[56da40e]292}
293
[f7ea0e1]294double GLAPen::GetRed() const
[56da40e]295{
[aa048c3]296    return components[0];
[56da40e]297}
298
[f7ea0e1]299double GLAPen::GetGreen() const
[56da40e]300{
[aa048c3]301    return components[1];
[56da40e]302}
303
[f7ea0e1]304double GLAPen::GetBlue() const
[56da40e]305{
[aa048c3]306    return components[2];
[56da40e]307}
308
[f383708]309void GLAPen::Interpolate(const GLAPen& pen, double how_far)
310{
[588ff16]311    components[0] += how_far * (pen.GetRed() - components[0]);
312    components[1] += how_far * (pen.GetGreen() - components[1]);
313    components[2] += how_far * (pen.GetBlue() - components[2]);
[aa048c3]314}
315
316struct ColourTriple {
317    // RGB triple: values are from 0-255 inclusive for each component.
318    unsigned char r, g, b;
319};
320
321// These must be in the same order as the entries in COLOURS[] below.
322const ColourTriple COLOURS[] = {
323    { 0, 0, 0 },       // black
324    { 100, 100, 100 }, // grey
325    { 180, 180, 180 }, // light grey
326    { 140, 140, 140 }, // light grey 2
327    { 90, 90, 90 },    // dark grey
328    { 255, 255, 255 }, // white
329    { 0, 100, 255},    // turquoise
330    { 0, 255, 40 },    // green
331    { 150, 205, 224 }, // indicator 1
332    { 114, 149, 160 }, // indicator 2
333    { 255, 255, 0 },   // yellow
334    { 255, 0, 0 },     // red
[f4c5932]335    { 40, 40, 255 },   // blue
[aa048c3]336};
[f383708]337
[620c0c9]338bool GLAList::need_to_generate() {
339    // Bail out if the list is already cached, or can't usefully be cached.
340    if (flags & (GLACanvas::CACHED|GLACanvas::NEVER_CACHE))
341        return false;
342
343    // Create a new OpenGL list to hold this sequence of drawing
344    // operations.
345    if (gl_list == 0) {
346        gl_list = glGenLists(1);
347        CHECK_GL_ERROR("GLAList::need_to_generate", "glGenLists");
348#ifdef GLA_DEBUG
349        printf("glGenLists(1) returned %u\n", (unsigned)gl_list);
350#endif
351        if (gl_list == 0) {
352            // If we can't create a list for any reason, fall back to just
[b3f1bbe]353            // drawing directly, and flag the list as NEVER_CACHE as there's
354            // unlikely to be much point calling glGenLists() again.
355            flags = GLACanvas::NEVER_CACHE;
[620c0c9]356            return false;
357        }
358
359        // We should have 256 lists for font drawing and a dozen or so for 2D
360        // and 3D lists.  So something is amiss if we've generated 1000 lists,
361        // probably a infinite loop in the lazy list mechanism.
362        assert(gl_list < 1000);
363    }
[2c1c52e]364    // https://www.opengl.org/resources/faq/technical/displaylist.htm advises:
[620c0c9]365    //
366    // "Stay away from GL_COMPILE_AND_EXECUTE mode. Instead, create the
367    // list using GL_COMPILE mode, then execute it with glCallList()."
368    glNewList(gl_list, GL_COMPILE);
369    CHECK_GL_ERROR("GLAList::need_to_generate", "glNewList");
370    return true;
371}
372
373void GLAList::finalise(unsigned int list_flags)
374{
375    glEndList();
376    CHECK_GL_ERROR("GLAList::finalise", "glEndList");
377    if (list_flags & GLACanvas::NEVER_CACHE) {
378        glDeleteLists(gl_list, 1);
379        CHECK_GL_ERROR("GLAList::finalise", "glDeleteLists");
380        gl_list = 0;
381        flags = GLACanvas::NEVER_CACHE;
382    } else {
383        flags = list_flags | GLACanvas::CACHED;
384    }
385}
386
387bool GLAList::DrawList() const {
388    if ((flags & GLACanvas::CACHED) == 0)
389        return false;
[db59b02]390    glCallList(gl_list);
391    CHECK_GL_ERROR("GLAList::DrawList", "glCallList");
[620c0c9]392    return true;
[db59b02]393}
394
[56da40e]395//
396//  GLACanvas
[096e56c]397//
[56da40e]398
[9071cf5]399BEGIN_EVENT_TABLE(GLACanvas, wxGLCanvas)
400    EVT_SIZE(GLACanvas::OnSize)
401END_EVENT_TABLE()
402
[84f1ed1]403// Pass wxWANTS_CHARS so that the window gets cursor keys on MS Windows.
404GLACanvas::GLACanvas(wxWindow* parent, int id)
[caa5fda]405    : wxGLCanvas(parent, id, wx_gl_attribs, wxDefaultPosition,
[cbd9829]406                 wxDefaultSize, wxWANTS_CHARS),
[8c048fa]407      ctx(this), m_Translation(), blob_method(UNKNOWN), cross_method(UNKNOWN),
[236a1b1]408      x_size(0), y_size(0), stereo_mode(stereo_mode_static)
[56da40e]409{
410    // Constructor.
411
[1b12b82]412    m_Quadric = NULL;
[08253d9]413    m_Pan = 0.0;
414    m_Tilt = 0.0;
[9eb58d0]415    m_Scale = 0.0;
[c5fc8eb]416    m_VolumeDiameter = 1.0;
[d67450e]417    m_SmoothShading = false;
[a517825]418    m_Texture = 0;
419    m_Textured = false;
[6abab84]420    m_Perspective = false;
[c60062d]421    m_Fog = false;
[db452ae]422    m_AntiAlias = false;
[db59b02]423    list_flags = 0;
[4a1cede]424    alpha = 1.0;
[56da40e]425}
426
427GLACanvas::~GLACanvas()
428{
429    // Destructor.
430
[1b12b82]431    if (m_Quadric) {
[b49ac56]432        gluDeleteQuadric(m_Quadric);
433        CHECK_GL_ERROR("~GLACanvas", "gluDeleteQuadric");
[1b12b82]434    }
435}
436
437void GLACanvas::FirstShow()
438{
[90430f2]439    // Update our record of the client area size and centre.
440    GetClientSize(&x_size, &y_size);
[6cf4daa]441    if (x_size < 1) x_size = 1;
442    if (y_size < 1) y_size = 1;
[90430f2]443
[8c048fa]444    ctx.SetCurrent(*this);
[4f3e5d1]445    opengl_initialised = true;
[19b2f99]446
447    // Set the background colour of the canvas to black.
448    glClearColor(0.0, 0.0, 0.0, 1.0);
449    CHECK_GL_ERROR("FirstShow", "glClearColor");
450
451    // Set viewport.
452    glViewport(0, 0, x_size, y_size);
453    CHECK_GL_ERROR("FirstShow", "glViewport");
454
[807f9dd]455    save_hints = false;
[5846a74]456
[807f9dd]457    vendor = wxString((const char *)glGetString(GL_VENDOR), wxConvUTF8);
458    renderer = wxString((const char *)glGetString(GL_RENDERER), wxConvUTF8);
[fe075d7]459    {
[5846a74]460        wxConfigBase * cfg = wxConfigBase::Get();
[fe075d7]461        wxString s;
[5846a74]462        if (cfg->Read(wxT("opengl_survex"), &s, wxString()) && s == wxT(VERSION) &&
463            cfg->Read(wxT("opengl_vendor"), &s, wxString()) && s == vendor &&
[fe075d7]464            cfg->Read(wxT("opengl_renderer"), &s, wxString()) && s == renderer) {
[5846a74]465            // The survex version, vendor and renderer are the same as those
466            // we cached hints for, so use those hints.
[fe075d7]467            int v;
468            if (cfg->Read(wxT("blob_method"), &v, 0) &&
[1ecdc29]469                (v == SPRITE || v == POINT || v == LINES)) {
[fe075d7]470                // How to draw blobs.
471                blob_method = v;
472            }
473            if (cfg->Read(wxT("cross_method"), &v, 0) &&
474                (v == SPRITE || v == LINES)) {
475                // How to draw crosses.
476                cross_method = v;
477            }
478        }
479    }
[db59b02]480
[4f3e5d1]481    if (m_Quadric) return;
482    // One time initialisation follows.
[657402d]483
[1b12b82]484    m_Quadric = gluNewQuadric();
[bb1f293]485    CHECK_GL_ERROR("FirstShow", "gluNewQuadric");
[1b12b82]486    if (!m_Quadric) {
487        abort(); // FIXME need to cope somehow
488    }
[096e56c]489
[203d2a7]490    glShadeModel(GL_FLAT);
[dde4fe7]491    CHECK_GL_ERROR("FirstShow", "glShadeModel");
[d67450e]492    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // So text works.
[dde4fe7]493    CHECK_GL_ERROR("FirstShow", "glPolygonMode");
[e633bb1]494    //glAlphaFunc(GL_GREATER, 0.5f);
495    //CHECK_GL_ERROR("FirstShow", "glAlphaFunc");
[096e56c]496
[c8f449c3]497    // We want glReadPixels() to read from the front buffer (which is the
498    // default for single-buffered displays).
499    if (double_buffered) {
500        glReadBuffer(GL_FRONT);
501        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
502    }
503
[c60062d]504    // Grey fog effect.
505    GLfloat fogcolour[4] = { 0.5, 0.5, 0.5, 1.0 };
506    glFogfv(GL_FOG_COLOR, fogcolour);
[9baa53a]507    CHECK_GL_ERROR("FirstShow", "glFogfv");
[c60062d]508
509    // Linear fogging.
510    glFogi(GL_FOG_MODE, GL_LINEAR);
[9baa53a]511    CHECK_GL_ERROR("FirstShow", "glFogi");
[c60062d]512
513    // Optimise for speed (compute fog per vertex).
514    glHint(GL_FOG_HINT, GL_FASTEST);
[9baa53a]515    CHECK_GL_ERROR("FirstShow", "glHint");
[1eeb55a]516
[a517825]517    // No padding on pixel packing and unpacking (default is to pad each
518    // line to a multiple of 4 bytes).
519    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // For setting texture maps.
[028829f]520    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_UNPACK_ALIGNMENT");
[a517825]521    glPixelStorei(GL_PACK_ALIGNMENT, 1); // For screengrabs and movies.
[028829f]522    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_PACK_ALIGNMENT");
523
[1eeb55a]524    // Load font
[8a05a7a]525    wxString path = wmsg_cfgpth();
[bd551c0]526    path += wxCONFIG_PATH_SEPARATOR;
[1aa3fb7]527    path += wxT("unifont.pixelfont");
528    if (!m_Font.load(path)) {
529        // FIXME: do something better.
[17c483d]530        // We have this message available: Error in format of font file “%s”
[df3e1a0c]531        fprintf(stderr, "Failed to parse compiled-in font data\n");
[1aa3fb7]532        exit(1);
533    }
[4ba80e0]534
[fe075d7]535    if (blob_method == UNKNOWN) {
536        // Check if we can use GL_POINTS to plot blobs at stations.
537        GLdouble point_size_range[2];
538        glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
539        CHECK_GL_ERROR("FirstShow", "glGetDoublev GL_SMOOTH_POINT_SIZE_RANGE");
540        if (point_size_range[0] <= BLOB_DIAMETER &&
541            point_size_range[1] >= BLOB_DIAMETER) {
542            blob_method = POINT;
543        } else {
[cab6f11]544            blob_method = glpoint_sprite_works() ? SPRITE : LINES;
[fe075d7]545        }
546        save_hints = true;
547    }
548
549    if (blob_method == POINT) {
[4ba80e0]550        glPointSize(BLOB_DIAMETER);
551        CHECK_GL_ERROR("FirstShow", "glPointSize");
552    }
[95ce35f]553
[fe075d7]554    if (cross_method == UNKNOWN) {
[fc5f476]555        cross_method = glpoint_sprite_works() ? SPRITE : LINES;
[fe075d7]556        save_hints = true;
[95ce35f]557    }
[185d793]558
[fe075d7]559    if (cross_method == SPRITE) {
[95ce35f]560        glGenTextures(1, &m_CrossTexture);
[9baa53a]561        CHECK_GL_ERROR("FirstShow", "glGenTextures");
[95ce35f]562        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
[9baa53a]563        CHECK_GL_ERROR("FirstShow", "glBindTexture");
[fe075d7]564        // Cross image for drawing crosses using texture mapped point sprites.
[95ce35f]565        const unsigned char crossteximage[128] = {
[edfaf35]566#define o 0,0
567#define I 255,255
568            CROSS_TEXTURE
569#undef o
570#undef I
[95ce35f]571        };
572        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
[9baa53a]573        CHECK_GL_ERROR("FirstShow", "glPixelStorei");
[95ce35f]574        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
[9baa53a]575        CHECK_GL_ERROR("FirstShow", "glTexEnvi");
[95ce35f]576        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
[9baa53a]577        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
[95ce35f]578        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
[9baa53a]579        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
[95ce35f]580        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)crossteximage);
[9baa53a]581        CHECK_GL_ERROR("FirstShow", "glTexImage2D");
[95ce35f]582        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
[9baa53a]583        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
[95ce35f]584        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
[9baa53a]585        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
[95ce35f]586    }
[cab6f11]587
588    if (blob_method == SPRITE) {
589        glGenTextures(1, &m_BlobTexture);
590        CHECK_GL_ERROR("FirstShow", "glGenTextures");
591        glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
592        CHECK_GL_ERROR("FirstShow", "glBindTexture");
593        // Image for drawing blobs using texture mapped point sprites.
594        const unsigned char blobteximage[128] = {
595#define o 0,0
596#define I 255,255
597            BLOB_TEXTURE
598#undef o
599#undef I
600        };
601        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
602        CHECK_GL_ERROR("FirstShow", "glPixelStorei");
603        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
604        CHECK_GL_ERROR("FirstShow", "glTexEnvi");
605        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
606        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
607        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
608        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
609        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)blobteximage);
610        CHECK_GL_ERROR("FirstShow", "glTexImage2D");
611        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
612        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
613        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
614        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
615    }
[ca8c864]616}
617
[56da40e]618void GLACanvas::Clear()
619{
620    // Clear the canvas.
[d727368]621
[56da40e]622    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[1897247]623    CHECK_GL_ERROR("Clear", "glClear");
[56da40e]624}
625
626void GLACanvas::SetScale(Double scale)
627{
[db59b02]628    if (scale != m_Scale) {
629        vector<GLAList>::iterator i;
630        for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
[b3f1bbe]631            i->invalidate_if(INVALIDATE_ON_SCALE);
[db59b02]632        }
633
634        m_Scale = scale;
635    }
[56da40e]636}
637
[90430f2]638void GLACanvas::OnSize(wxSizeEvent & event)
639{
640    wxSize size = event.GetSize();
641
642    unsigned int mask = 0;
643    if (size.GetWidth() != x_size) mask |= INVALIDATE_ON_X_RESIZE;
644    if (size.GetHeight() != y_size) mask |= INVALIDATE_ON_Y_RESIZE;
645    if (mask) {
646        vector<GLAList>::iterator i;
647        for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
[b3f1bbe]648            i->invalidate_if(mask);
[90430f2]649        }
650
[6cf4daa]651        // The width and height go to zero when the panel is dragged right
652        // across so we clamp them to be at least 1 to avoid problems.
[90430f2]653        x_size = size.GetWidth();
654        y_size = size.GetHeight();
[6cf4daa]655        if (x_size < 1) x_size = 1;
656        if (y_size < 1) y_size = 1;
[90430f2]657    }
658
[9071cf5]659    event.Skip();
[6cf4daa]660
[19b2f99]661    if (!opengl_initialised) return;
662
[6cf4daa]663    // Set viewport.
664    glViewport(0, 0, x_size, y_size);
[92678b5]665    CHECK_GL_ERROR("OnSize", "glViewport");
[90430f2]666}
667
[56da40e]668void GLACanvas::AddTranslationScreenCoordinates(int dx, int dy)
669{
670    // Translate the data by a given amount, specified in screen coordinates.
[096e56c]671
[56da40e]672    // Find out how far the translation takes us in data coordinates.
673    SetDataTransform();
674
[f6d8375]675    double x0, y0, z0;
676    double x, y, z;
[1b12b82]677    gluUnProject(0.0, 0.0, 0.0, modelview_matrix, projection_matrix, viewport,
[b49ac56]678                 &x0, &y0, &z0);
[bb1f293]679    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject");
[1b12b82]680    gluUnProject(dx, -dy, 0.0, modelview_matrix, projection_matrix, viewport,
[b49ac56]681                 &x, &y, &z);
[bb1f293]682    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject (2)");
[56da40e]683
684    // Apply the translation.
[d67450e]685    AddTranslation(Vector3(x - x0, y - y0, z - z0));
[56da40e]686}
687
[c5fc8eb]688void GLACanvas::SetVolumeDiameter(glaCoord diameter)
[56da40e]689{
[c5fc8eb]690    // Set the size of the data drawing volume by giving the diameter of the
691    // smallest sphere containing it.
[56da40e]692
[f6d8375]693    m_VolumeDiameter = max(glaCoord(1.0), diameter);
[56da40e]694}
695
696void GLACanvas::StartDrawing()
697{
698    // Prepare for a redraw operation.
[096e56c]699
[8c048fa]700    ctx.SetCurrent(*this);
[236a1b1]701    if (stereo_mode == STEREO_BUFFERS) {
[6616cdbf]702        if (m_Eye == 0) {
[236a1b1]703            glDrawBuffer(GL_BACK_LEFT);
704        } else {
705            glDrawBuffer(GL_BACK_RIGHT);
706        }
[e9c9ce0f]707    }
[12ec820]708    glDepthMask(GL_TRUE);
[807f9dd]709
[6616cdbf]710    if (m_Eye == 0) {
711        // Clear the background.
712        Clear();
713
714        if (stereo_mode == STEREO_ANAGLYPH) {
715            // Left is red.
716            glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
717        }
718    } else {
719        if (stereo_mode == STEREO_ANAGLYPH) {
720            // Clear alpha and the depth buffer.
721            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
722            Clear();
723
724            // Right is green and blue.
725            glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
726        } else if (stereo_mode != STEREO_2UP) {
727            // Clear the background.
728            Clear();
729        }
730    }
731
[807f9dd]732    if (!save_hints) return;
733
734    // We want to check on the second redraw.
735    static int draw_count = 2;
736    if (--draw_count != 0) return;
737
738    if (cross_method != LINES) {
739        SetColour(col_WHITE);
740        Clear();
741        SetDataTransform();
742        BeginCrosses();
743        DrawCross(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
744        EndCrosses();
745        static const unsigned char expected_cross[64 * 3] = {
746#define o 0,0,0
747#define I 255,255,255
[edfaf35]748            CROSS_TEXTURE
[dd64a45]749#undef o
750#undef I
[807f9dd]751        };
752        if (!CheckVisualFidelity(expected_cross)) {
753            cross_method = LINES;
754            save_hints = true;
755        }
756    }
757
758    if (blob_method != LINES) {
759        SetColour(col_WHITE);
760        SetDataTransform();
761        BeginBlobs();
762        DrawBlob(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
763        EndBlobs();
764        static const unsigned char expected_blob[64 * 3] = {
765#define o 0,0,0
766#define I 255,255,255
[edfaf35]767            BLOB_TEXTURE
[dd64a45]768#undef o
769#undef I
[807f9dd]770        };
771        if (!CheckVisualFidelity(expected_blob)) {
772            blob_method = LINES;
773            save_hints = true;
774        }
[6616cdbf]775        Clear();
[807f9dd]776    }
777
778    wxConfigBase * cfg = wxConfigBase::Get();
[5846a74]779    cfg->Write(wxT("opengl_survex"), wxT(VERSION));
[807f9dd]780    cfg->Write(wxT("opengl_vendor"), vendor);
781    cfg->Write(wxT("opengl_renderer"), renderer);
782    cfg->Write(wxT("blob_method"), blob_method);
783    cfg->Write(wxT("cross_method"), cross_method);
784    cfg->Flush();
785    save_hints = false;
[56da40e]786}
787
[d67450e]788void GLACanvas::EnableSmoothPolygons(bool filled)
[1b12b82]789{
790    // Prepare for drawing smoothly-shaded polygons.
791    // Only use this when required (in particular lines in lists may not be
792    // coloured correctly when this is enabled).
[096e56c]793
[d67450e]794    glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT|GL_POLYGON_BIT);
795    if (filled) {
796        glShadeModel(GL_SMOOTH);
797        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
798    } else {
799        glDisable(GL_LINE_SMOOTH);
800        glDisable(GL_TEXTURE_2D);
801        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
802    }
803    CHECK_GL_ERROR("EnableSmoothPolygons", "glPolygonMode");
804
805    if (filled && m_SmoothShading) {
806        static const GLfloat mat_specular[] = { 0.2, 0.2, 0.2, 1.0 };
807        static const GLfloat light_position[] = { -1.0, -1.0, -1.0, 0.0 };
808        static const GLfloat light_ambient[] = { 0.3, 0.3, 0.3, 1.0 };
809        static const GLfloat light_diffuse[] = { 0.7, 0.7, 0.7, 1.0 };
810        glEnable(GL_COLOR_MATERIAL);
811        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
812        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0);
813        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
814        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
815        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
816        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
817        glEnable(GL_LIGHTING);
818        glEnable(GL_LIGHT0);
819    }
[1b12b82]820}
821
822void GLACanvas::DisableSmoothPolygons()
823{
[d67450e]824    glPopAttrib();
[203d2a7]825}
826
[d67450e]827void GLACanvas::PlaceNormal(const Vector3 &v)
[203d2a7]828{
829    // Add a normal (for polygons etc.)
830
[d67450e]831    glNormal3d(v.GetX(), v.GetY(), v.GetZ());
[1b12b82]832}
833
[56da40e]834void GLACanvas::SetDataTransform()
835{
[236a1b1]836    double aspect = double(y_size) / double(x_size);
837    if (stereo_mode == STEREO_2UP) {
838        aspect *= 2;
839        // Set viewport.
840        if (m_Eye == 0) {
841            glViewport(0, 0, x_size / 2, y_size);
842            CHECK_GL_ERROR("SetDataTransform", "glViewport");
843        } else {
844            glViewport(x_size / 2, 0, x_size / 2, y_size);
845            CHECK_GL_ERROR("SetDataTransform", "glViewport");
846        }
847    }
848
[de24f93]849    // Set projection.
850    glMatrixMode(GL_PROJECTION);
851    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
852    glLoadIdentity();
853    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
854
[cf1368a]855    // 0.1 for mono?
[d877aa2]856    Double near_plane = 1.0;
[a214f04]857    const double APERTURE = 50.0;
858    const double FOCAL_LEN = 70.0;
859    const double EYE_SEP = FOCAL_LEN / 20.0;
[de24f93]860    if (m_Perspective) {
[cf1368a]861        near_plane = FOCAL_LEN / 5.0;
[236a1b1]862        Double stereo_adj = 0.0;
[e9c9ce0f]863        Double lr = near_plane * tan(rad(APERTURE * 0.5));
[d877aa2]864        Double far_plane = m_VolumeDiameter * 5 + near_plane; // FIXME: work out properly
865        Double tb = lr * aspect;
[236a1b1]866        if (stereo_mode) {
867            stereo_adj = 0.5 * EYE_SEP * near_plane / FOCAL_LEN;
868            if (m_Eye == 0) stereo_adj = -stereo_adj;
869        }
[e9c9ce0f]870        glFrustum(-lr + stereo_adj, lr + stereo_adj, -tb, tb, near_plane, far_plane);
[de24f93]871        CHECK_GL_ERROR("SetViewportAndProjection", "glFrustum");
872    } else {
[5092ee7]873        near_plane = 0.0;
[d877aa2]874        assert(m_Scale != 0.0);
875        Double lr = m_VolumeDiameter / m_Scale * 0.5;
876        Double far_plane = m_VolumeDiameter + near_plane;
[ea35995]877        Double tb = lr;
878        if (aspect >= 1.0) {
879            tb *= aspect;
880        } else {
881            lr /= aspect;
882        }
[de24f93]883        glOrtho(-lr, lr, -tb, tb, near_plane, far_plane);
884        CHECK_GL_ERROR("SetViewportAndProjection", "glOrtho");
885    }
886
[56da40e]887    // Set the modelview transform for drawing data.
888    glMatrixMode(GL_MODELVIEW);
[1897247]889    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
[56da40e]890    glLoadIdentity();
[1897247]891    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
[d877aa2]892    if (m_Perspective) {
[bb3d137]893        glTranslated(0.0, 0.0, -near_plane);
[d877aa2]894    } else {
895        glTranslated(0.0, 0.0, -0.5 * m_VolumeDiameter);
896    }
[1bbd9a8]897    CHECK_GL_ERROR("SetDataTransform", "glTranslated");
[2491b8c]898    // Get axes the correct way around (z upwards, y into screen)
899    glRotated(-90.0, 1.0, 0.0, 0.0);
900    CHECK_GL_ERROR("SetDataTransform", "glRotated");
[236a1b1]901    if (stereo_mode && m_Perspective) {
[bb3d137]902        glTranslated(m_Eye ? -0.5 * EYE_SEP : 0.5 * EYE_SEP, 0.0, 0.0);
903        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
904    }
[7a57dc7]905    glRotated(-m_Tilt, 1.0, 0.0, 0.0);
[08253d9]906    CHECK_GL_ERROR("SetDataTransform", "glRotated");
907    glRotated(m_Pan, 0.0, 0.0, 1.0);
[2491b8c]908    CHECK_GL_ERROR("SetDataTransform", "CopyToOpenGL");
[5092ee7]909    if (m_Perspective) {
[d67450e]910        glTranslated(m_Translation.GetX(),
911                     m_Translation.GetY(),
912                     m_Translation.GetZ());
[5092ee7]913        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
914    }
[dde4fe7]915
[de24f93]916    // Save projection matrix.
917    glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix);
918    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
919
920    // Save viewport coordinates.
921    glGetIntegerv(GL_VIEWPORT, viewport);
922    CHECK_GL_ERROR("SetDataTransform", "glGetIntegerv");
923
924    // Save modelview matrix.
[dde4fe7]925    glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
926    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
[de24f93]927
[5092ee7]928    if (!m_Perspective) {
929        // Adjust the translation so we don't change the Z position of the model
[f6d8375]930        double X, Y, Z;
[d67450e]931        gluProject(m_Translation.GetX(),
932                   m_Translation.GetY(),
933                   m_Translation.GetZ(),
[5092ee7]934                   modelview_matrix, projection_matrix, viewport,
935                   &X, &Y, &Z);
[f6d8375]936        double Tx, Ty, Tz;
[5092ee7]937        gluUnProject(X, Y, 0.5, modelview_matrix, projection_matrix, viewport,
938                     &Tx, &Ty, &Tz);
939        glTranslated(Tx, Ty, Tz);
940        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
941        glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
942    }
[096e56c]943
[de24f93]944    glEnable(GL_DEPTH_TEST);
945    CHECK_GL_ERROR("SetDataTransform", "glEnable GL_DEPTH_TEST");
[c60062d]946
[a517825]947    if (m_Textured) {
948        glBindTexture(GL_TEXTURE_2D, m_Texture);
949        glEnable(GL_TEXTURE_2D);
950        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
951        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_S");
952        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
953        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_T");
954        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
955        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MAG_FILTER");
[ecbdd96]956        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
957                        GL_LINEAR_MIPMAP_LINEAR);
[a517825]958        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MIN_FILTER");
959        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
960    } else {
961        glDisable(GL_TEXTURE_2D);
962    }
[c60062d]963    if (m_Fog) {
964        glFogf(GL_FOG_START, near_plane);
965        glFogf(GL_FOG_END, near_plane + m_VolumeDiameter);
966        glEnable(GL_FOG);
[db452ae]967    } else {
968        glDisable(GL_FOG);
969    }
970
[4a1cede]971    glEnable(GL_BLEND);
972    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
[db452ae]973    if (m_AntiAlias) {
974        glEnable(GL_LINE_SMOOTH);
975    } else {
976        glDisable(GL_LINE_SMOOTH);
[c60062d]977    }
[56da40e]978}
979
980void GLACanvas::SetIndicatorTransform()
981{
[db59b02]982    list_flags |= NEVER_CACHE;
983
[bb1f293]984    // Set the modelview transform and projection for drawing indicators.
[56da40e]985
[bb1f293]986    glDisable(GL_DEPTH_TEST);
987    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_DEPTH_TEST");
[c60062d]988    glDisable(GL_FOG);
989    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_FOG");
[bb1f293]990
[78924eb]991    // Just a simple 2D projection.
[bb1f293]992    glMatrixMode(GL_PROJECTION);
993    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
994    glLoadIdentity();
995    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity (2)");
[236a1b1]996    if (stereo_mode == STEREO_2UP) {
997        gluOrtho2D(0, x_size / 2, 0, y_size);
998    } else {
999        gluOrtho2D(0, x_size, 0, y_size);
1000    }
[bb1f293]1001    CHECK_GL_ERROR("SetIndicatorTransform", "gluOrtho2D");
[a517825]1002
[78924eb]1003    // No modelview transform.
1004    glMatrixMode(GL_MODELVIEW);
1005    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
1006    glLoadIdentity();
1007    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity");
1008
[a517825]1009    glDisable(GL_TEXTURE_2D);
[6adffadf]1010    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_TEXTURE_2D");
[e4d40792]1011    glDisable(GL_BLEND);
[6adffadf]1012    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_BLEND");
[36c3285]1013    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
[9baa53a]1014    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_S");
[36c3285]1015    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
[9baa53a]1016    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_T");
[36c3285]1017    glAlphaFunc(GL_GREATER, 0.5f);
[9baa53a]1018    CHECK_GL_ERROR("SetIndicatorTransform", "glAlphaFunc");
[096e56c]1019    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
[9baa53a]1020    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MAG_FILTER");
[36c3285]1021    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
[9baa53a]1022    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MIN_FILTER");
[36c3285]1023    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
[9baa53a]1024    CHECK_GL_ERROR("SetIndicatorTransform", "glHint");
[56da40e]1025}
1026
1027void GLACanvas::FinishDrawing()
1028{
1029    // Complete a redraw operation.
[6616cdbf]1030    if (stereo_mode != STEREO_MONO && m_Eye == 0) {
1031        return;
1032    }
1033
1034    if (stereo_mode == STEREO_ANAGLYPH) {
1035        // Reset colour mask.
1036        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1037    }
[096e56c]1038
[c293aa9]1039    if (double_buffered) {
1040        SwapBuffers();
1041    } else {
1042        glFlush();
1043        CHECK_GL_ERROR("FinishDrawing", "glFlush");
1044    }
[56da40e]1045}
1046
[d2fcc9b]1047void GLACanvas::DrawList(unsigned int l)
[56da40e]1048{
[4ba80e0]1049    // FIXME: uncomment to disable use of lists for debugging:
1050    // GenerateList(l); return;
[d2fcc9b]1051    if (l >= drawing_lists.size()) drawing_lists.resize(l + 1);
[bae6a7c]1052
[d2fcc9b]1053    // We generate the OpenGL lists lazily to minimise delays on startup.
1054    // So check if we need to generate the OpenGL list now.
[620c0c9]1055    if (drawing_lists[l].need_to_generate()) {
[db59b02]1056        // Clear list_flags so that we can note what conditions to invalidate
1057        // the cached OpenGL list on.
1058        list_flags = 0;
[620c0c9]1059
1060#ifdef GLA_DEBUG
1061        printf("generating list #%u... ", l);
1062        m_Vertices = 0;
1063#endif
[d2fcc9b]1064        GenerateList(l);
[edb6576]1065#ifdef GLA_DEBUG
[bae6a7c]1066        printf("done (%d vertices)\n", m_Vertices);
[edb6576]1067#endif
[620c0c9]1068        drawing_lists[l].finalise(list_flags);
[bae6a7c]1069    }
[ee78822]1070
[620c0c9]1071    if (!drawing_lists[l].DrawList()) {
1072        // That list isn't cached (which means it probably can't usefully be
1073        // cached).
[db59b02]1074        GenerateList(l);
1075    }
[56da40e]1076}
1077
[11fe902]1078void GLACanvas::DrawListZPrepass(unsigned int l)
1079{
1080    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1081    DrawList(l);
1082    glDepthMask(GL_FALSE);
1083    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1084    glDepthFunc(GL_EQUAL);
1085    DrawList(l);
1086    glDepthMask(GL_TRUE);
1087    glDepthFunc(GL_LESS);
1088}
1089
[76dd228]1090void GLACanvas::DrawList2D(unsigned int l, glaCoord x, glaCoord y, Double rotation)
1091{
1092    glMatrixMode(GL_PROJECTION);
1093    CHECK_GL_ERROR("DrawList2D", "glMatrixMode");
1094    glPushMatrix();
1095    CHECK_GL_ERROR("DrawList2D", "glPushMatrix");
1096    glTranslated(x, y, 0);
1097    CHECK_GL_ERROR("DrawList2D", "glTranslated");
1098    if (rotation != 0.0) {
1099        glRotated(rotation, 0, 0, -1);
1100        CHECK_GL_ERROR("DrawList2D", "glRotated");
1101    }
1102    DrawList(l);
1103    glMatrixMode(GL_PROJECTION);
1104    CHECK_GL_ERROR("DrawList2D", "glMatrixMode 2");
1105    glPopMatrix();
1106    CHECK_GL_ERROR("DrawList2D", "glPopMatrix");
1107}
1108
[aa048c3]1109void GLACanvas::SetColour(const GLAPen& pen, double rgb_scale)
[56da40e]1110{
1111    // Set the colour for subsequent operations.
[4a1cede]1112    glColor4f(pen.GetRed() * rgb_scale, pen.GetGreen() * rgb_scale,
1113              pen.GetBlue() * rgb_scale, alpha);
[56da40e]1114}
1115
[aa048c3]1116void GLACanvas::SetColour(const GLAPen& pen)
[f383708]1117{
[aa048c3]1118    // Set the colour for subsequent operations.
[4a1cede]1119    glColor4d(pen.components[0], pen.components[1], pen.components[2], alpha);
[f383708]1120}
1121
[d1ce9bd]1122void GLACanvas::SetColour(gla_colour colour, double rgb_scale)
1123{
1124    // Set the colour for subsequent operations.
1125    rgb_scale /= 255.0;
1126    glColor4f(COLOURS[colour].r * rgb_scale,
1127              COLOURS[colour].g * rgb_scale,
1128              COLOURS[colour].b * rgb_scale,
1129              alpha);
1130}
1131
[aa048c3]1132void GLACanvas::SetColour(gla_colour colour)
[56da40e]1133{
[aa048c3]1134    // Set the colour for subsequent operations.
[4943ae8]1135    if (alpha == 1.0) {
1136        glColor3ubv(&COLOURS[colour].r);
1137    } else {
1138        glColor4ub(COLOURS[colour].r,
1139                   COLOURS[colour].g,
1140                   COLOURS[colour].b,
1141                   (unsigned char)(255 * alpha));
1142    }
[56da40e]1143}
1144
1145void GLACanvas::DrawText(glaCoord x, glaCoord y, glaCoord z, const wxString& str)
1146{
1147    // Draw a text string on the current buffer in the current font.
1148    glRasterPos3d(x, y, z);
[1897247]1149    CHECK_GL_ERROR("DrawText", "glRasterPos3d");
[1aa3fb7]1150    m_Font.write_string(str.data(), str.size());
[56da40e]1151}
1152
[1eeb55a]1153void GLACanvas::DrawIndicatorText(int x, int y, const wxString& str)
[56da40e]1154{
[1aa3fb7]1155    glRasterPos2d(x, y);
1156    CHECK_GL_ERROR("DrawIndicatorText", "glRasterPos2d");
1157    m_Font.write_string(str.data(), str.size());
[56da40e]1158}
1159
[dbd50e2]1160void GLACanvas::GetTextExtent(const wxString& str, int * x_ext, int * y_ext) const
[56da40e]1161{
[1aa3fb7]1162    m_Font.get_text_extent(str.data(), str.size(), x_ext, y_ext);
[56da40e]1163}
1164
1165void GLACanvas::BeginQuadrilaterals()
1166{
1167    // Commence drawing of quadrilaterals.
[096e56c]1168
[56da40e]1169    glBegin(GL_QUADS);
1170}
1171
1172void GLACanvas::EndQuadrilaterals()
1173{
1174    // Finish drawing of quadrilaterals.
[096e56c]1175
[56da40e]1176    glEnd();
[9baa53a]1177    CHECK_GL_ERROR("EndQuadrilaterals", "glEnd GL_QUADS");
[56da40e]1178}
1179
1180void GLACanvas::BeginLines()
1181{
1182    // Commence drawing of a set of lines.
1183
1184    glBegin(GL_LINES);
1185}
1186
1187void GLACanvas::EndLines()
1188{
1189    // Finish drawing of a set of lines.
1190
1191    glEnd();
[9baa53a]1192    CHECK_GL_ERROR("EndLines", "glEnd GL_LINES");
[56da40e]1193}
1194
1195void GLACanvas::BeginTriangles()
1196{
1197    // Commence drawing of a set of triangles.
1198
1199    glBegin(GL_TRIANGLES);
1200}
1201
1202void GLACanvas::EndTriangles()
1203{
1204    // Finish drawing of a set of triangles.
1205
1206    glEnd();
[9baa53a]1207    CHECK_GL_ERROR("EndTriangles", "glEnd GL_TRIANGLES");
[56da40e]1208}
1209
[dde4fe7]1210void GLACanvas::BeginTriangleStrip()
1211{
1212    // Commence drawing of a triangle strip.
1213
1214    glBegin(GL_TRIANGLE_STRIP);
1215}
1216
1217void GLACanvas::EndTriangleStrip()
1218{
1219    // Finish drawing of a triangle strip.
1220
1221    glEnd();
[9baa53a]1222    CHECK_GL_ERROR("EndTriangleStrip", "glEnd GL_TRIANGLE_STRIP");
[dde4fe7]1223}
1224
[56da40e]1225void GLACanvas::BeginPolyline()
1226{
1227    // Commence drawing of a polyline.
1228
1229    glBegin(GL_LINE_STRIP);
1230}
1231
1232void GLACanvas::EndPolyline()
1233{
1234    // Finish drawing of a polyline.
[096e56c]1235
[56da40e]1236    glEnd();
[9baa53a]1237    CHECK_GL_ERROR("EndPolyline", "glEnd GL_LINE_STRIP");
[56da40e]1238}
1239
[45aa1d6]1240void GLACanvas::BeginPolygon()
1241{
1242    // Commence drawing of a polygon.
1243
1244    glBegin(GL_POLYGON);
1245}
1246
1247void GLACanvas::EndPolygon()
1248{
1249    // Finish drawing of a polygon.
[096e56c]1250
[45aa1d6]1251    glEnd();
[9baa53a]1252    CHECK_GL_ERROR("EndPolygon", "glEnd GL_POLYGON");
[45aa1d6]1253}
1254
[56da40e]1255void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z)
1256{
1257    // Place a vertex for the current object being drawn.
1258
[edb6576]1259#ifdef GLA_DEBUG
1260    m_Vertices++;
1261#endif
[56da40e]1262    glVertex3d(x, y, z);
1263}
1264
[f336ab9]1265void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z,
1266                            glaTexCoord tex_x, glaTexCoord tex_y)
[b839829]1267{
1268    // Place a vertex for the current object being drawn.
1269
1270#ifdef GLA_DEBUG
1271    m_Vertices++;
1272#endif
[ba828d4]1273    glTexCoord2f(tex_x, tex_y);
[b839829]1274    glVertex3d(x, y, z);
1275}
1276
[56da40e]1277void GLACanvas::PlaceIndicatorVertex(glaCoord x, glaCoord y)
1278{
1279    // Place a vertex for the current indicator object being drawn.
1280
[087bc72]1281    PlaceVertex(x, y, 0.0);
[56da40e]1282}
1283
[e633bb1]1284void GLACanvas::BeginBlobs()
[d9b3270]1285{
[fe075d7]1286    // Commence drawing of a set of blobs.
[cab6f11]1287    if (blob_method == SPRITE) {
1288        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1289        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1290        glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
1291        CHECK_GL_ERROR("BeginBlobs", "glBindTexture");
1292        glEnable(GL_ALPHA_TEST);
1293        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1294        glPointSize(8);
1295        CHECK_GL_ERROR("BeginBlobs", "glPointSize");
1296        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1297        CHECK_GL_ERROR("BeginBlobs", "glTexEnvi GL_POINT_SPRITE");
1298        glEnable(GL_TEXTURE_2D);
1299        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_TEXTURE_2D");
1300        glEnable(GL_POINT_SPRITE);
1301        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SPRITE");
1302        glBegin(GL_POINTS);
1303    } else if (blob_method == POINT) {
[78924eb]1304        glPushAttrib(GL_ENABLE_BIT);
1305        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
[4ba80e0]1306        glEnable(GL_ALPHA_TEST);
1307        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1308        glEnable(GL_POINT_SMOOTH);
1309        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SMOOTH");
1310        glBegin(GL_POINTS);
1311    } else {
[6662d02]1312        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
[4ba80e0]1313        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1314        SetIndicatorTransform();
[6f5f9e5]1315        glEnable(GL_DEPTH_TEST);
1316        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_DEPTH_TEST");
[bde8c9a]1317        glBegin(GL_LINES);
[4ba80e0]1318    }
[e633bb1]1319}
[d9b3270]1320
[e633bb1]1321void GLACanvas::EndBlobs()
1322{
[bde8c9a]1323    // Finish drawing of a set of blobs.
1324    glEnd();
[cab6f11]1325    if (blob_method != LINES) {
[bde8c9a]1326        CHECK_GL_ERROR("EndBlobs", "glEnd GL_POINTS");
1327    } else {
1328        CHECK_GL_ERROR("EndBlobs", "glEnd GL_LINES");
[4ba80e0]1329    }
[78924eb]1330    glPopAttrib();
1331    CHECK_GL_ERROR("EndBlobs", "glPopAttrib");
[e633bb1]1332}
[d9b3270]1333
[e633bb1]1334void GLACanvas::DrawBlob(glaCoord x, glaCoord y, glaCoord z)
1335{
[cab6f11]1336    if (blob_method != LINES) {
[4ba80e0]1337        // Draw a marker.
1338        PlaceVertex(x, y, z);
1339    } else {
[f6d8375]1340        double X, Y, Z;
[d67450e]1341        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
[4ba80e0]1342            printf("bad transform\n");
1343            return;
1344        }
1345        // Stuff behind us (in perspective view) will get clipped,
1346        // but we can save effort with a cheap check here.
1347        if (Z <= 0) return;
1348
[bde8c9a]1349        X -= BLOB_DIAMETER * 0.5;
1350        Y -= BLOB_DIAMETER * 0.5;
1351
1352        PlaceVertex(X, Y + 1, Z);
1353        PlaceVertex(X, Y + (BLOB_DIAMETER - 1), Z);
1354
1355        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1356            PlaceVertex(X + i, Y, Z);
1357            PlaceVertex(X + i, Y + BLOB_DIAMETER, Z);
1358        }
1359
1360        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + 1, Z);
1361        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + (BLOB_DIAMETER - 1), Z);
[78924eb]1362    }
[95ce35f]1363#ifdef GLA_DEBUG
[78924eb]1364    m_Vertices++;
[95ce35f]1365#endif
[429465a]1366}
1367
[81aea4e]1368void GLACanvas::DrawBlob(glaCoord x, glaCoord y)
1369{
[cab6f11]1370    if (blob_method != LINES) {
[81aea4e]1371        // Draw a marker.
1372        PlaceVertex(x, y, 0);
1373    } else {
[bde8c9a]1374        x -= BLOB_DIAMETER * 0.5;
1375        y -= BLOB_DIAMETER * 0.5;
1376
1377        PlaceVertex(x, y + 1, 0);
1378        PlaceVertex(x, y + (BLOB_DIAMETER - 1), 0);
1379
1380        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1381            PlaceVertex(x + i, y, 0);
1382            PlaceVertex(x + i, y + BLOB_DIAMETER, 0);
1383        }
1384
1385        PlaceVertex(x + (BLOB_DIAMETER - 1), y + 1, 0);
1386        PlaceVertex(x + (BLOB_DIAMETER - 1), y + (BLOB_DIAMETER - 1), 0);
[81aea4e]1387    }
1388#ifdef GLA_DEBUG
1389    m_Vertices++;
1390#endif
1391}
1392
[86fe6e4]1393void GLACanvas::BeginCrosses()
1394{
[95ce35f]1395    // Plot crosses.
[fe075d7]1396    if (cross_method == SPRITE) {
[95ce35f]1397        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
[9baa53a]1398        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib");
[95ce35f]1399        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
[9baa53a]1400        CHECK_GL_ERROR("BeginCrosses", "glBindTexture");
[95ce35f]1401        glEnable(GL_ALPHA_TEST);
[9baa53a]1402        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_ALPHA_TEST");
[95ce35f]1403        glPointSize(8);
[9baa53a]1404        CHECK_GL_ERROR("BeginCrosses", "glPointSize");
1405        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1406        CHECK_GL_ERROR("BeginCrosses", "glTexEnvi GL_POINT_SPRITE");
[95ce35f]1407        glEnable(GL_TEXTURE_2D);
[9baa53a]1408        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_TEXTURE_2D");
1409        glEnable(GL_POINT_SPRITE);
1410        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_POINT_SPRITE");
[95ce35f]1411        glBegin(GL_POINTS);
1412    } else {
1413        // To get the crosses to appear at a constant size and orientation on
1414        // screen, we plot them in the Indicator transform coordinates (which
1415        // unfortunately means they can't be usefully put in an opengl display
1416        // list).
[6662d02]1417        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
[9baa53a]1418        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib 2");
[95ce35f]1419        SetIndicatorTransform();
[200eca7]1420        // Align line drawing to pixel centres to get pixel-perfect rendering
1421        // (graphics card and driver bugs aside).
1422        glTranslated(-0.5, -0.5, 0);
1423        CHECK_GL_ERROR("BeginCrosses", "glTranslated");
[6f5f9e5]1424        glEnable(GL_DEPTH_TEST);
[9baa53a]1425        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_DEPTH_TEST");
[95ce35f]1426        glBegin(GL_LINES);
1427    }
[86fe6e4]1428}
1429
1430void GLACanvas::EndCrosses()
1431{
[95ce35f]1432    glEnd();
[fe075d7]1433    if (cross_method == SPRITE) {
[9baa53a]1434        CHECK_GL_ERROR("EndCrosses", "glEnd GL_POINTS");
1435    } else {
1436        CHECK_GL_ERROR("EndCrosses", "glEnd GL_LINES");
1437    }
[86fe6e4]1438    glPopAttrib();
1439    CHECK_GL_ERROR("EndCrosses", "glPopAttrib");
1440}
1441
1442void GLACanvas::DrawCross(glaCoord x, glaCoord y, glaCoord z)
1443{
[fe075d7]1444    if (cross_method == SPRITE) {
[7e1da12]1445        // Draw a marker.
[95ce35f]1446        PlaceVertex(x, y, z);
1447    } else {
[f6d8375]1448        double X, Y, Z;
[d67450e]1449        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
[95ce35f]1450            printf("bad transform\n");
1451            return;
1452        }
1453        // Stuff behind us (in perspective view) will get clipped,
1454        // but we can save effort with a cheap check here.
[7e1da12]1455        if (Z <= 0) return;
1456
1457        // Round to integers before adding on the offsets for the
1458        // cross arms to avoid uneven crosses.
1459        X = rint(X);
1460        Y = rint(Y);
[200eca7]1461        // Need to extend lines by an extra pixel (which shouldn't get drawn by
1462        // the diamond-exit rule).
[7e1da12]1463        PlaceVertex(X - 3, Y - 3, Z);
[200eca7]1464        PlaceVertex(X + 4, Y + 4, Z);
[7e1da12]1465        PlaceVertex(X - 3, Y + 3, Z);
[200eca7]1466        PlaceVertex(X + 4, Y - 4, Z);
[86fe6e4]1467    }
[78924eb]1468#ifdef GLA_DEBUG
1469    m_Vertices++;
1470#endif
[86fe6e4]1471}
1472
[e633bb1]1473void GLACanvas::DrawRing(glaCoord x, glaCoord y)
[429465a]1474{
1475    // Draw an unfilled circle
[096e56c]1476    const Double radius = 4;
[429465a]1477    assert(m_Quadric);
[78924eb]1478    glMatrixMode(GL_MODELVIEW);
1479    CHECK_GL_ERROR("DrawRing", "glMatrixMode");
1480    glPushMatrix();
1481    CHECK_GL_ERROR("DrawRing", "glPushMatrix");
[429465a]1482    glTranslated(x, y, 0.0);
1483    CHECK_GL_ERROR("DrawRing", "glTranslated");
1484    gluDisk(m_Quadric, radius - 1.0, radius, 12, 1);
1485    CHECK_GL_ERROR("DrawRing", "gluDisk");
[78924eb]1486    glPopMatrix();
1487    CHECK_GL_ERROR("DrawRing", "glPopMatrix");
[d9b3270]1488}
1489
[522e0bd]1490void GLACanvas::DrawRectangle(gla_colour fill, gla_colour edge,
[b49ac56]1491                              glaCoord x0, glaCoord y0, glaCoord w, glaCoord h)
[56da40e]1492{
1493    // Draw a filled rectangle with an edge in the indicator plane.
[ca8c864]1494    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1495    // size.
[56da40e]1496
[c10dd28]1497    SetColour(fill);
[aa048c3]1498    BeginQuadrilaterals();
[56da40e]1499    PlaceIndicatorVertex(x0, y0);
1500    PlaceIndicatorVertex(x0 + w, y0);
1501    PlaceIndicatorVertex(x0 + w, y0 + h);
1502    PlaceIndicatorVertex(x0, y0 + h);
1503    EndQuadrilaterals();
1504
[aa048c3]1505    if (edge != fill) {
[b49ac56]1506        SetColour(edge);
[522e0bd]1507        BeginPolyline();
[b49ac56]1508        PlaceIndicatorVertex(x0, y0);
1509        PlaceIndicatorVertex(x0 + w, y0);
1510        PlaceIndicatorVertex(x0 + w, y0 + h);
1511        PlaceIndicatorVertex(x0, y0 + h);
[522e0bd]1512        PlaceIndicatorVertex(x0, y0);
[b49ac56]1513        EndLines();
[c10dd28]1514    }
[56da40e]1515}
1516
[aa048c3]1517void
1518GLACanvas::DrawShadedRectangle(const GLAPen & fill_bot, const GLAPen & fill_top,
1519                               glaCoord x0, glaCoord y0,
1520                               glaCoord w, glaCoord h)
1521{
1522    // Draw a graduated filled rectangle in the indicator plane.
1523    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1524    // size.
1525
[02aa4d4]1526    glShadeModel(GL_SMOOTH);
[9baa53a]1527    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_SMOOTH");
[aa048c3]1528    BeginQuadrilaterals();
1529    SetColour(fill_bot);
1530    PlaceIndicatorVertex(x0, y0);
1531    PlaceIndicatorVertex(x0 + w, y0);
1532    SetColour(fill_top);
1533    PlaceIndicatorVertex(x0 + w, y0 + h);
1534    PlaceIndicatorVertex(x0, y0 + h);
1535    EndQuadrilaterals();
[02aa4d4]1536    glShadeModel(GL_FLAT);
[9baa53a]1537    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_FLAT");
[aa048c3]1538}
1539
1540void GLACanvas::DrawCircle(gla_colour edge, gla_colour fill,
1541                           glaCoord cx, glaCoord cy, glaCoord radius)
[56da40e]1542{
[087bc72]1543    // Draw a filled circle with an edge.
[56da40e]1544    SetColour(fill);
[78924eb]1545    glMatrixMode(GL_MODELVIEW);
1546    CHECK_GL_ERROR("DrawCircle", "glMatrixMode");
1547    glPushMatrix();
1548    CHECK_GL_ERROR("DrawCircle", "glPushMatrix");
[56da40e]1549    glTranslated(cx, cy, 0.0);
[8326157]1550    CHECK_GL_ERROR("DrawCircle", "glTranslated");
[1b12b82]1551    assert(m_Quadric);
1552    gluDisk(m_Quadric, 0.0, radius, 36, 1);
[8326157]1553    CHECK_GL_ERROR("DrawCircle", "gluDisk");
[56da40e]1554    SetColour(edge);
[1b12b82]1555    gluDisk(m_Quadric, radius - 1.0, radius, 36, 1);
[8326157]1556    CHECK_GL_ERROR("DrawCircle", "gluDisk (2)");
[78924eb]1557    glPopMatrix();
1558    CHECK_GL_ERROR("DrawCircle", "glPopMatrix");
[56da40e]1559}
1560
[aa048c3]1561void GLACanvas::DrawSemicircle(gla_colour edge, gla_colour fill,
[b49ac56]1562                               glaCoord cx, glaCoord cy,
1563                               glaCoord radius, glaCoord start)
[56da40e]1564{
1565    // Draw a filled semicircle with an edge.
[ca8c864]1566    // The semicircle extends from "start" deg to "start"+180 deg (increasing
1567    // clockwise, 0 deg upwards).
[56da40e]1568    SetColour(fill);
[78924eb]1569    glMatrixMode(GL_MODELVIEW);
1570    CHECK_GL_ERROR("DrawSemicircle", "glMatrixMode");
1571    glPushMatrix();
1572    CHECK_GL_ERROR("DrawSemicircle", "glPushMatrix");
[56da40e]1573    glTranslated(cx, cy, 0.0);
[78924eb]1574    CHECK_GL_ERROR("DrawSemicircle", "glTranslated");
[1b12b82]1575    assert(m_Quadric);
1576    gluPartialDisk(m_Quadric, 0.0, radius, 36, 1, start, 180.0);
[78924eb]1577    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk");
[56da40e]1578    SetColour(edge);
[1b12b82]1579    gluPartialDisk(m_Quadric, radius - 1.0, radius, 36, 1, start, 180.0);
[78924eb]1580    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk (2)");
1581    glPopMatrix();
1582    CHECK_GL_ERROR("DrawSemicircle", "glPopMatrix");
[56da40e]1583}
1584
[d67450e]1585void
1586GLACanvas::DrawTriangle(gla_colour edge, gla_colour fill,
1587                        const Vector3 &p0, const Vector3 &p1, const Vector3 &p2)
[56da40e]1588{
[ca8c864]1589    // Draw a filled triangle with an edge.
[096e56c]1590
[56da40e]1591    SetColour(fill);
1592    BeginTriangles();
[d67450e]1593    PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1594    PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1595    PlaceIndicatorVertex(p2.GetX(), p2.GetY());
[56da40e]1596    EndTriangles();
1597
1598    SetColour(edge);
[d67450e]1599    glBegin(GL_LINE_STRIP);
1600    PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1601    PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1602    PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1603    glEnd();
[9baa53a]1604    CHECK_GL_ERROR("DrawTriangle", "glEnd GL_LINE_STRIP");
[56da40e]1605}
1606
1607void GLACanvas::EnableDashedLines()
1608{
1609    // Enable dashed lines, and start drawing in them.
1610
[9eb58d0]1611    glLineStipple(1, 0x3333);
[8326157]1612    CHECK_GL_ERROR("EnableDashedLines", "glLineStipple");
[56da40e]1613    glEnable(GL_LINE_STIPPLE);
[bb1f293]1614    CHECK_GL_ERROR("EnableDashedLines", "glEnable GL_LINE_STIPPLE");
[56da40e]1615}
1616
1617void GLACanvas::DisableDashedLines()
1618{
1619    glDisable(GL_LINE_STIPPLE);
[bb1f293]1620    CHECK_GL_ERROR("DisableDashedLines", "glDisable GL_LINE_STIPPLE");
[56da40e]1621}
1622
[d67450e]1623bool GLACanvas::Transform(const Vector3 & v,
[f6d8375]1624                          double* x_out, double* y_out, double* z_out) const
[56da40e]1625{
1626    // Convert from data coordinates to screen coordinates.
[096e56c]1627
[087bc72]1628    // Perform the projection.
[d67450e]1629    return gluProject(v.GetX(), v.GetY(), v.GetZ(),
1630                      modelview_matrix, projection_matrix, viewport,
[6adffadf]1631                      x_out, y_out, z_out);
[56da40e]1632}
1633
[1b12b82]1634void GLACanvas::ReverseTransform(Double x, Double y,
[f6d8375]1635                                 double* x_out, double* y_out, double* z_out) const
[a2b3d62]1636{
1637    // Convert from screen coordinates to data coordinates.
[096e56c]1638
[a2b3d62]1639    // Perform the projection.
[1b12b82]1640    gluUnProject(x, y, 0.0, modelview_matrix, projection_matrix, viewport,
[b49ac56]1641                 x_out, y_out, z_out);
[8326157]1642    CHECK_GL_ERROR("ReverseTransform", "gluUnProject");
[a2b3d62]1643}
1644
[e7f9e99]1645Double GLACanvas::SurveyUnitsAcrossViewport() const
[087bc72]1646{
[8326157]1647    // Measure the current viewport in survey units, taking into account the
1648    // current display scale.
[087bc72]1649
[9eb58d0]1650    assert(m_Scale != 0.0);
[db59b02]1651    list_flags |= INVALIDATE_ON_SCALE;
[ea35995]1652    Double result = m_VolumeDiameter / m_Scale;
1653    if (y_size < x_size) {
1654        result = result * x_size / y_size;
1655    }
1656    return result;
[087bc72]1657}
[045e2af]1658
[d67450e]1659void GLACanvas::ToggleSmoothShading()
1660{
1661    m_SmoothShading = !m_SmoothShading;
1662}
1663
[a517825]1664void GLACanvas::ToggleTextured()
1665{
1666    m_Textured = !m_Textured;
1667    if (m_Textured && m_Texture == 0) {
1668        glGenTextures(1, &m_Texture);
1669        CHECK_GL_ERROR("ToggleTextured", "glGenTextures");
1670
1671        glBindTexture(GL_TEXTURE_2D, m_Texture);
1672        CHECK_GL_ERROR("ToggleTextured", "glBindTexture");
1673
1674        ::wxInitAllImageHandlers();
[5627cbb]1675
[a517825]1676        wxImage img;
[8a05a7a]1677        wxString texture(wmsg_cfgpth());
[5627cbb]1678        texture += wxCONFIG_PATH_SEPARATOR;
[09dfd18]1679        texture += wxT("images");
[5627cbb]1680        texture += wxCONFIG_PATH_SEPARATOR;
1681        texture += wxT("texture.png");
1682        if (!img.LoadFile(texture, wxBITMAP_TYPE_PNG)) {
[a517825]1683            // FIXME
1684            fprintf(stderr, "Couldn't load image.\n");
1685            exit(1);
1686        }
[5627cbb]1687
[ecbdd96]1688        // Generate mipmaps.
[7c18431]1689        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, // was GL_LUMINANCE
[ecbdd96]1690                          img.GetWidth(), img.GetHeight(),
1691                          GL_RGB, GL_UNSIGNED_BYTE, img.GetData());
1692        CHECK_GL_ERROR("ToggleTextured", "gluBuild2DMipmaps");
[a517825]1693
1694        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1695        CHECK_GL_ERROR("ToggleTextured", "glTexEnvi");
1696    }
1697}
1698
[1ada489]1699bool GLACanvas::SaveScreenshot(const wxString & fnm, wxBitmapType type) const
[045e2af]1700{
[6cf4daa]1701    const int width = x_size;
1702    const int height = y_size;
[1bd4841]1703    unsigned char *pixels = (unsigned char *)malloc(3 * width * (height + 1));
[045e2af]1704    if (!pixels) return false;
1705    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
[a106530]1706    CHECK_GL_ERROR("SaveScreenshot", "glReadPixels");
[1bd4841]1707    unsigned char * tmp_row = pixels + 3 * width * height;
1708    // We need to flip the image vertically - this approach should be more
1709    // efficient than using wxImage::Mirror(false) as that creates a new
1710    // wxImage object.
1711    for (int y = height / 2 - 1; y >= 0; --y) {
1712        unsigned char * upper = pixels + 3 * width * y;
1713        unsigned char * lower = pixels + 3 * width * (height - y - 1);
1714        memcpy(tmp_row, upper, 3 * width);
1715        memcpy(upper, lower, 3 * width);
1716        memcpy(lower, tmp_row, 3 * width);
1717    }
1718    // NB wxImage constructor calls free(pixels) for us.
[045e2af]1719    wxImage grab(width, height, pixels);
[1bd4841]1720    return grab.SaveFile(fnm, type);
[045e2af]1721}
[807f9dd]1722
1723bool GLACanvas::CheckVisualFidelity(const unsigned char * target) const
1724{
1725    unsigned char pixels[3 * 8 * 8];
[c8f449c3]1726    if (double_buffered) {
1727        glReadBuffer(GL_BACK);
1728        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1729    }
[edfaf35]1730    glReadPixels(x_size / 2 - 4, y_size / 2 - 5, 8, 8,
[6cf4daa]1731                 GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
[a106530]1732    CHECK_GL_ERROR("CheckVisualFidelity", "glReadPixels");
[c8f449c3]1733    if (double_buffered) {
1734        glReadBuffer(GL_FRONT);
1735        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1736    }
[4f7f965]1737#if 0
1738    // Show what got drawn and what was expected for debugging.
1739    for (int y = 0; y < 8; ++y) {
1740        for (int x = 0; x < 8; ++x) {
1741            int o = (y * 8 + x) * 3;
1742            printf("%c", pixels[o] ? 'X' : '.');
1743        }
1744        printf(" ");
1745        for (int x = 0; x < 8; ++x) {
1746            int o = (y * 8 + x) * 3;
1747            printf("%c", target[o] ? 'X' : '.');
1748        }
1749        printf("\n");
1750    }
1751#endif
[807f9dd]1752    return (memcmp(pixels, target, sizeof(pixels)) == 0);
1753}
[aea4f8b]1754
1755void GLACanvas::ReadPixels(int width, int height, unsigned char * buf) const
1756{
[a106530]1757    CHECK_GL_ERROR("ReadPixels", "glReadPixels");
[aea4f8b]1758    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)buf);
1759}
[f9ca87c]1760
1761void GLACanvas::PolygonOffset(bool on) const
1762{
1763    if (on) {
1764        glPolygonOffset(1.0, 1.0);
1765        glEnable(GL_POLYGON_OFFSET_FILL);
1766    } else {
1767        glDisable(GL_POLYGON_OFFSET_FILL);
1768    }
1769}
Note: See TracBrowser for help on using the repository browser.