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

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

Push stereo OpenGL code down to gla layer

  • Property mode set to 100644
File size: 50.7 KB
Line 
1//
2//  gla-gl.cc
3//
4//  OpenGL implementation for the GLA abstraction layer.
5//
6//  Copyright (C) 2002-2003,2005 Mark R. Shinwell
7//  Copyright (C) 2003,2004,2005,2006,2007,2010,2011,2012,2013,2014,2015,2017,2018 Olly Betts
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
21//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22//
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <wx/confbase.h>
29#include <wx/image.h>
30
31#include <algorithm>
32
33#include "aven.h"
34#include "gla.h"
35#include "message.h"
36#include "useful.h"
37
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
44#ifdef HAVE_GL_GLEXT_H
45# include <GL/glext.h>
46#elif defined HAVE_OPENGL_GLEXT_H
47# include <OpenGL/glext.h>
48#endif
49
50#ifndef GL_POINT_SIZE_MAX
51#define GL_POINT_SIZE_MAX 0x8127
52#endif
53#ifndef GL_POINT_SPRITE
54#define GL_POINT_SPRITE 0x8861
55#endif
56#ifndef GL_COORD_REPLACE
57#define GL_COORD_REPLACE 0x8862
58#endif
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
73
74using namespace std;
75
76const int BLOB_DIAMETER = 5;
77
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
98static bool opengl_initialised = false;
99
100static bool double_buffered = false;
101
102static stereo_mode_type stereo_mode_static = STEREO_MONO;
103
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,
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,
119        WX_GL_STEREO,
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;
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    }
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
142void GLACanvas::SetStereoMode(stereo_mode_type mode)
143{
144    stereo_mode_static = mode;
145}
146
147string GetGLSystemDescription()
148{
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.";
152    const char *p = (const char*)glGetString(GL_VERSION);
153    if (!p)
154        return "Couldn't read OpenGL version!";
155
156    string info;
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);
163#if defined __WXGTK__ || defined __WXX11__ || defined __WXMOTIF__
164    info += string_format("\nGLX %0.1f\n", wxGLCanvas::GetGLXVersion() * 0.1);
165#else
166    info += '\n';
167#endif
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];
178    glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
179    GLdouble point_size_granularity;
180    glGetDoublev(GL_SMOOTH_POINT_SIZE_GRANULARITY, &point_size_granularity);
181    info += string_format("R%dG%dB%d\n"
182             "Max Texture size: %dx%d\n"
183             "Max Viewport size: %dx%d\n"
184             "Smooth Point Size %.3f-%.3f (granularity %.3f)",
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);
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    }
195
196    info += "\nDouble buffered: ";
197    if (double_buffered)
198        info += "true";
199    else
200        info += "false";
201
202    const GLubyte* gl_extensions = glGetString(GL_EXTENSIONS);
203    if (*gl_extensions) {
204        info += '\n';
205        info += (const char*)gl_extensions;
206    }
207    return info;
208}
209
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
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
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.)
267#define CHECK_GL_ERROR(M, F) do { \
268    if (!opengl_initialised) { \
269        wxLogError(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL not initialised before (call " F " in method " M ")")); \
270    } \
271    GLenum error_code_ = glGetError(); \
272    if (error_code_ != GL_NO_ERROR) { \
273        log_gl_error(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL error: %s " \
274                         "(call " F " in method " M ")"), error_code_); \
275    } \
276} while (0)
277
278//
279//  GLAPen
280//
281
282GLAPen::GLAPen()
283{
284    components[0] = components[1] = components[2] = 0.0;
285}
286
287void GLAPen::SetColour(double red, double green, double blue)
288{
289    components[0] = red;
290    components[1] = green;
291    components[2] = blue;
292}
293
294double GLAPen::GetRed() const
295{
296    return components[0];
297}
298
299double GLAPen::GetGreen() const
300{
301    return components[1];
302}
303
304double GLAPen::GetBlue() const
305{
306    return components[2];
307}
308
309void GLAPen::Interpolate(const GLAPen& pen, double how_far)
310{
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]);
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
335    { 40, 40, 255 },   // blue
336};
337
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
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;
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    }
364    // https://www.opengl.org/resources/faq/technical/displaylist.htm advises:
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;
390    glCallList(gl_list);
391    CHECK_GL_ERROR("GLAList::DrawList", "glCallList");
392    return true;
393}
394
395//
396//  GLACanvas
397//
398
399BEGIN_EVENT_TABLE(GLACanvas, wxGLCanvas)
400    EVT_SIZE(GLACanvas::OnSize)
401END_EVENT_TABLE()
402
403// Pass wxWANTS_CHARS so that the window gets cursor keys on MS Windows.
404GLACanvas::GLACanvas(wxWindow* parent, int id)
405    : wxGLCanvas(parent, id, wx_gl_attribs, wxDefaultPosition,
406                 wxDefaultSize, wxWANTS_CHARS),
407      ctx(this), m_Translation(), blob_method(UNKNOWN), cross_method(UNKNOWN),
408      x_size(0), y_size(0), stereo_mode(stereo_mode_static)
409{
410    // Constructor.
411
412    m_Quadric = NULL;
413    m_Pan = 0.0;
414    m_Tilt = 0.0;
415    m_Scale = 0.0;
416    m_VolumeDiameter = 1.0;
417    m_SmoothShading = false;
418    m_Texture = 0;
419    m_Textured = false;
420    m_Perspective = false;
421    m_Fog = false;
422    m_AntiAlias = false;
423    list_flags = 0;
424    alpha = 1.0;
425}
426
427GLACanvas::~GLACanvas()
428{
429    // Destructor.
430
431    if (m_Quadric) {
432        gluDeleteQuadric(m_Quadric);
433        CHECK_GL_ERROR("~GLACanvas", "gluDeleteQuadric");
434    }
435}
436
437void GLACanvas::FirstShow()
438{
439    // Update our record of the client area size and centre.
440    GetClientSize(&x_size, &y_size);
441    if (x_size < 1) x_size = 1;
442    if (y_size < 1) y_size = 1;
443
444    ctx.SetCurrent(*this);
445    opengl_initialised = true;
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
455    save_hints = false;
456
457    vendor = wxString((const char *)glGetString(GL_VENDOR), wxConvUTF8);
458    renderer = wxString((const char *)glGetString(GL_RENDERER), wxConvUTF8);
459    {
460        wxConfigBase * cfg = wxConfigBase::Get();
461        wxString s;
462        if (cfg->Read(wxT("opengl_survex"), &s, wxString()) && s == wxT(VERSION) &&
463            cfg->Read(wxT("opengl_vendor"), &s, wxString()) && s == vendor &&
464            cfg->Read(wxT("opengl_renderer"), &s, wxString()) && s == renderer) {
465            // The survex version, vendor and renderer are the same as those
466            // we cached hints for, so use those hints.
467            int v;
468            if (cfg->Read(wxT("blob_method"), &v, 0) &&
469                (v == SPRITE || v == POINT || v == LINES)) {
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    }
480
481    if (m_Quadric) return;
482    // One time initialisation follows.
483
484    m_Quadric = gluNewQuadric();
485    CHECK_GL_ERROR("FirstShow", "gluNewQuadric");
486    if (!m_Quadric) {
487        abort(); // FIXME need to cope somehow
488    }
489
490    glShadeModel(GL_FLAT);
491    CHECK_GL_ERROR("FirstShow", "glShadeModel");
492    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // So text works.
493    CHECK_GL_ERROR("FirstShow", "glPolygonMode");
494    //glAlphaFunc(GL_GREATER, 0.5f);
495    //CHECK_GL_ERROR("FirstShow", "glAlphaFunc");
496
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
504    // Grey fog effect.
505    GLfloat fogcolour[4] = { 0.5, 0.5, 0.5, 1.0 };
506    glFogfv(GL_FOG_COLOR, fogcolour);
507    CHECK_GL_ERROR("FirstShow", "glFogfv");
508
509    // Linear fogging.
510    glFogi(GL_FOG_MODE, GL_LINEAR);
511    CHECK_GL_ERROR("FirstShow", "glFogi");
512
513    // Optimise for speed (compute fog per vertex).
514    glHint(GL_FOG_HINT, GL_FASTEST);
515    CHECK_GL_ERROR("FirstShow", "glHint");
516
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.
520    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_UNPACK_ALIGNMENT");
521    glPixelStorei(GL_PACK_ALIGNMENT, 1); // For screengrabs and movies.
522    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_PACK_ALIGNMENT");
523
524    // Load font
525    wxString path = wmsg_cfgpth();
526    path += wxCONFIG_PATH_SEPARATOR;
527    path += wxT("unifont.pixelfont");
528    if (!m_Font.load(path)) {
529        // FIXME: do something better.
530        // We have this message available: Error in format of font file “%s”
531        fprintf(stderr, "Failed to parse compiled-in font data\n");
532        exit(1);
533    }
534
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 {
544            blob_method = glpoint_sprite_works() ? SPRITE : LINES;
545        }
546        save_hints = true;
547    }
548
549    if (blob_method == POINT) {
550        glPointSize(BLOB_DIAMETER);
551        CHECK_GL_ERROR("FirstShow", "glPointSize");
552    }
553
554    if (cross_method == UNKNOWN) {
555        cross_method = glpoint_sprite_works() ? SPRITE : LINES;
556        save_hints = true;
557    }
558
559    if (cross_method == SPRITE) {
560        glGenTextures(1, &m_CrossTexture);
561        CHECK_GL_ERROR("FirstShow", "glGenTextures");
562        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
563        CHECK_GL_ERROR("FirstShow", "glBindTexture");
564        // Cross image for drawing crosses using texture mapped point sprites.
565        const unsigned char crossteximage[128] = {
566#define o 0,0
567#define I 255,255
568            CROSS_TEXTURE
569#undef o
570#undef I
571        };
572        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
573        CHECK_GL_ERROR("FirstShow", "glPixelStorei");
574        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
575        CHECK_GL_ERROR("FirstShow", "glTexEnvi");
576        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
577        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
578        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
579        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
580        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)crossteximage);
581        CHECK_GL_ERROR("FirstShow", "glTexImage2D");
582        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
583        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
584        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
585        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
586    }
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    }
616}
617
618void GLACanvas::Clear()
619{
620    // Clear the canvas.
621
622    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
623    CHECK_GL_ERROR("Clear", "glClear");
624}
625
626void GLACanvas::SetScale(Double scale)
627{
628    if (scale != m_Scale) {
629        vector<GLAList>::iterator i;
630        for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
631            i->invalidate_if(INVALIDATE_ON_SCALE);
632        }
633
634        m_Scale = scale;
635    }
636}
637
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) {
648            i->invalidate_if(mask);
649        }
650
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.
653        x_size = size.GetWidth();
654        y_size = size.GetHeight();
655        if (x_size < 1) x_size = 1;
656        if (y_size < 1) y_size = 1;
657    }
658
659    event.Skip();
660
661    if (!opengl_initialised) return;
662
663    // Set viewport.
664    glViewport(0, 0, x_size, y_size);
665    CHECK_GL_ERROR("OnSize", "glViewport");
666}
667
668void GLACanvas::AddTranslationScreenCoordinates(int dx, int dy)
669{
670    // Translate the data by a given amount, specified in screen coordinates.
671
672    // Find out how far the translation takes us in data coordinates.
673    SetDataTransform();
674
675    double x0, y0, z0;
676    double x, y, z;
677    gluUnProject(0.0, 0.0, 0.0, modelview_matrix, projection_matrix, viewport,
678                 &x0, &y0, &z0);
679    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject");
680    gluUnProject(dx, -dy, 0.0, modelview_matrix, projection_matrix, viewport,
681                 &x, &y, &z);
682    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject (2)");
683
684    // Apply the translation.
685    AddTranslation(Vector3(x - x0, y - y0, z - z0));
686}
687
688void GLACanvas::SetVolumeDiameter(glaCoord diameter)
689{
690    // Set the size of the data drawing volume by giving the diameter of the
691    // smallest sphere containing it.
692
693    m_VolumeDiameter = max(glaCoord(1.0), diameter);
694}
695
696void GLACanvas::StartDrawing()
697{
698    // Prepare for a redraw operation.
699
700    ctx.SetCurrent(*this);
701    if (stereo_mode == STEREO_BUFFERS) {
702        if (m_Eye == 0) {
703            glDrawBuffer(GL_BACK_LEFT);
704        } else {
705            glDrawBuffer(GL_BACK_RIGHT);
706        }
707    }
708    glDepthMask(GL_TRUE);
709
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
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
748            CROSS_TEXTURE
749#undef o
750#undef I
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
767            BLOB_TEXTURE
768#undef o
769#undef I
770        };
771        if (!CheckVisualFidelity(expected_blob)) {
772            blob_method = LINES;
773            save_hints = true;
774        }
775        Clear();
776    }
777
778    wxConfigBase * cfg = wxConfigBase::Get();
779    cfg->Write(wxT("opengl_survex"), wxT(VERSION));
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;
786}
787
788void GLACanvas::EnableSmoothPolygons(bool filled)
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).
793
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    }
820}
821
822void GLACanvas::DisableSmoothPolygons()
823{
824    glPopAttrib();
825}
826
827void GLACanvas::PlaceNormal(const Vector3 &v)
828{
829    // Add a normal (for polygons etc.)
830
831    glNormal3d(v.GetX(), v.GetY(), v.GetZ());
832}
833
834void GLACanvas::SetDataTransform()
835{
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
849    // Set projection.
850    glMatrixMode(GL_PROJECTION);
851    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
852    glLoadIdentity();
853    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
854
855    // 0.1 for mono?
856    Double near_plane = 1.0;
857    const double APERTURE = 50.0;
858    const double FOCAL_LEN = 70.0;
859    const double EYE_SEP = FOCAL_LEN / 20.0;
860    if (m_Perspective) {
861        near_plane = FOCAL_LEN / 5.0;
862        Double stereo_adj = 0.0;
863        Double lr = near_plane * tan(rad(APERTURE * 0.5));
864        Double far_plane = m_VolumeDiameter * 5 + near_plane; // FIXME: work out properly
865        Double tb = lr * aspect;
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        }
870        glFrustum(-lr + stereo_adj, lr + stereo_adj, -tb, tb, near_plane, far_plane);
871        CHECK_GL_ERROR("SetViewportAndProjection", "glFrustum");
872    } else {
873        near_plane = 0.0;
874        assert(m_Scale != 0.0);
875        Double lr = m_VolumeDiameter / m_Scale * 0.5;
876        Double far_plane = m_VolumeDiameter + near_plane;
877        Double tb = lr;
878        if (aspect >= 1.0) {
879            tb *= aspect;
880        } else {
881            lr /= aspect;
882        }
883        glOrtho(-lr, lr, -tb, tb, near_plane, far_plane);
884        CHECK_GL_ERROR("SetViewportAndProjection", "glOrtho");
885    }
886
887    // Set the modelview transform for drawing data.
888    glMatrixMode(GL_MODELVIEW);
889    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
890    glLoadIdentity();
891    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
892    if (m_Perspective) {
893        glTranslated(0.0, 0.0, -near_plane);
894    } else {
895        glTranslated(0.0, 0.0, -0.5 * m_VolumeDiameter);
896    }
897    CHECK_GL_ERROR("SetDataTransform", "glTranslated");
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");
901    if (stereo_mode && m_Perspective) {
902        glTranslated(m_Eye ? -0.5 * EYE_SEP : 0.5 * EYE_SEP, 0.0, 0.0);
903        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
904    }
905    glRotated(-m_Tilt, 1.0, 0.0, 0.0);
906    CHECK_GL_ERROR("SetDataTransform", "glRotated");
907    glRotated(m_Pan, 0.0, 0.0, 1.0);
908    CHECK_GL_ERROR("SetDataTransform", "CopyToOpenGL");
909    if (m_Perspective) {
910        glTranslated(m_Translation.GetX(),
911                     m_Translation.GetY(),
912                     m_Translation.GetZ());
913        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
914    }
915
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.
925    glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
926    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
927
928    if (!m_Perspective) {
929        // Adjust the translation so we don't change the Z position of the model
930        double X, Y, Z;
931        gluProject(m_Translation.GetX(),
932                   m_Translation.GetY(),
933                   m_Translation.GetZ(),
934                   modelview_matrix, projection_matrix, viewport,
935                   &X, &Y, &Z);
936        double Tx, Ty, Tz;
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    }
943
944    glEnable(GL_DEPTH_TEST);
945    CHECK_GL_ERROR("SetDataTransform", "glEnable GL_DEPTH_TEST");
946
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");
956        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
957                        GL_LINEAR_MIPMAP_LINEAR);
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    }
963    if (m_Fog) {
964        glFogf(GL_FOG_START, near_plane);
965        glFogf(GL_FOG_END, near_plane + m_VolumeDiameter);
966        glEnable(GL_FOG);
967    } else {
968        glDisable(GL_FOG);
969    }
970
971    glEnable(GL_BLEND);
972    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
973    if (m_AntiAlias) {
974        glEnable(GL_LINE_SMOOTH);
975    } else {
976        glDisable(GL_LINE_SMOOTH);
977    }
978}
979
980void GLACanvas::SetIndicatorTransform()
981{
982    list_flags |= NEVER_CACHE;
983
984    // Set the modelview transform and projection for drawing indicators.
985
986    glDisable(GL_DEPTH_TEST);
987    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_DEPTH_TEST");
988    glDisable(GL_FOG);
989    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_FOG");
990
991    // Just a simple 2D projection.
992    glMatrixMode(GL_PROJECTION);
993    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
994    glLoadIdentity();
995    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity (2)");
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    }
1001    CHECK_GL_ERROR("SetIndicatorTransform", "gluOrtho2D");
1002
1003    // No modelview transform.
1004    glMatrixMode(GL_MODELVIEW);
1005    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
1006    glLoadIdentity();
1007    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity");
1008
1009    glDisable(GL_TEXTURE_2D);
1010    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_TEXTURE_2D");
1011    glDisable(GL_BLEND);
1012    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_BLEND");
1013    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1014    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_S");
1015    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1016    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_T");
1017    glAlphaFunc(GL_GREATER, 0.5f);
1018    CHECK_GL_ERROR("SetIndicatorTransform", "glAlphaFunc");
1019    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1020    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MAG_FILTER");
1021    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1022    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MIN_FILTER");
1023    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
1024    CHECK_GL_ERROR("SetIndicatorTransform", "glHint");
1025}
1026
1027void GLACanvas::FinishDrawing()
1028{
1029    // Complete a redraw operation.
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    }
1038
1039    if (double_buffered) {
1040        SwapBuffers();
1041    } else {
1042        glFlush();
1043        CHECK_GL_ERROR("FinishDrawing", "glFlush");
1044    }
1045}
1046
1047void GLACanvas::DrawList(unsigned int l)
1048{
1049    // FIXME: uncomment to disable use of lists for debugging:
1050    // GenerateList(l); return;
1051    if (l >= drawing_lists.size()) drawing_lists.resize(l + 1);
1052
1053    // We generate the OpenGL lists lazily to minimise delays on startup.
1054    // So check if we need to generate the OpenGL list now.
1055    if (drawing_lists[l].need_to_generate()) {
1056        // Clear list_flags so that we can note what conditions to invalidate
1057        // the cached OpenGL list on.
1058        list_flags = 0;
1059
1060#ifdef GLA_DEBUG
1061        printf("generating list #%u... ", l);
1062        m_Vertices = 0;
1063#endif
1064        GenerateList(l);
1065#ifdef GLA_DEBUG
1066        printf("done (%d vertices)\n", m_Vertices);
1067#endif
1068        drawing_lists[l].finalise(list_flags);
1069    }
1070
1071    if (!drawing_lists[l].DrawList()) {
1072        // That list isn't cached (which means it probably can't usefully be
1073        // cached).
1074        GenerateList(l);
1075    }
1076}
1077
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
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
1109void GLACanvas::SetColour(const GLAPen& pen, double rgb_scale)
1110{
1111    // Set the colour for subsequent operations.
1112    glColor4f(pen.GetRed() * rgb_scale, pen.GetGreen() * rgb_scale,
1113              pen.GetBlue() * rgb_scale, alpha);
1114}
1115
1116void GLACanvas::SetColour(const GLAPen& pen)
1117{
1118    // Set the colour for subsequent operations.
1119    glColor4d(pen.components[0], pen.components[1], pen.components[2], alpha);
1120}
1121
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
1132void GLACanvas::SetColour(gla_colour colour)
1133{
1134    // Set the colour for subsequent operations.
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    }
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);
1149    CHECK_GL_ERROR("DrawText", "glRasterPos3d");
1150    m_Font.write_string(str.data(), str.size());
1151}
1152
1153void GLACanvas::DrawIndicatorText(int x, int y, const wxString& str)
1154{
1155    glRasterPos2d(x, y);
1156    CHECK_GL_ERROR("DrawIndicatorText", "glRasterPos2d");
1157    m_Font.write_string(str.data(), str.size());
1158}
1159
1160void GLACanvas::GetTextExtent(const wxString& str, int * x_ext, int * y_ext) const
1161{
1162    m_Font.get_text_extent(str.data(), str.size(), x_ext, y_ext);
1163}
1164
1165void GLACanvas::BeginQuadrilaterals()
1166{
1167    // Commence drawing of quadrilaterals.
1168
1169    glBegin(GL_QUADS);
1170}
1171
1172void GLACanvas::EndQuadrilaterals()
1173{
1174    // Finish drawing of quadrilaterals.
1175
1176    glEnd();
1177    CHECK_GL_ERROR("EndQuadrilaterals", "glEnd GL_QUADS");
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();
1192    CHECK_GL_ERROR("EndLines", "glEnd GL_LINES");
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();
1207    CHECK_GL_ERROR("EndTriangles", "glEnd GL_TRIANGLES");
1208}
1209
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();
1222    CHECK_GL_ERROR("EndTriangleStrip", "glEnd GL_TRIANGLE_STRIP");
1223}
1224
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.
1235
1236    glEnd();
1237    CHECK_GL_ERROR("EndPolyline", "glEnd GL_LINE_STRIP");
1238}
1239
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.
1250
1251    glEnd();
1252    CHECK_GL_ERROR("EndPolygon", "glEnd GL_POLYGON");
1253}
1254
1255void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z)
1256{
1257    // Place a vertex for the current object being drawn.
1258
1259#ifdef GLA_DEBUG
1260    m_Vertices++;
1261#endif
1262    glVertex3d(x, y, z);
1263}
1264
1265void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z,
1266                            glaTexCoord tex_x, glaTexCoord tex_y)
1267{
1268    // Place a vertex for the current object being drawn.
1269
1270#ifdef GLA_DEBUG
1271    m_Vertices++;
1272#endif
1273    glTexCoord2f(tex_x, tex_y);
1274    glVertex3d(x, y, z);
1275}
1276
1277void GLACanvas::PlaceIndicatorVertex(glaCoord x, glaCoord y)
1278{
1279    // Place a vertex for the current indicator object being drawn.
1280
1281    PlaceVertex(x, y, 0.0);
1282}
1283
1284void GLACanvas::BeginBlobs()
1285{
1286    // Commence drawing of a set of blobs.
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) {
1304        glPushAttrib(GL_ENABLE_BIT);
1305        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
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 {
1312        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1313        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1314        SetIndicatorTransform();
1315        glEnable(GL_DEPTH_TEST);
1316        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_DEPTH_TEST");
1317        glBegin(GL_LINES);
1318    }
1319}
1320
1321void GLACanvas::EndBlobs()
1322{
1323    // Finish drawing of a set of blobs.
1324    glEnd();
1325    if (blob_method != LINES) {
1326        CHECK_GL_ERROR("EndBlobs", "glEnd GL_POINTS");
1327    } else {
1328        CHECK_GL_ERROR("EndBlobs", "glEnd GL_LINES");
1329    }
1330    glPopAttrib();
1331    CHECK_GL_ERROR("EndBlobs", "glPopAttrib");
1332}
1333
1334void GLACanvas::DrawBlob(glaCoord x, glaCoord y, glaCoord z)
1335{
1336    if (blob_method != LINES) {
1337        // Draw a marker.
1338        PlaceVertex(x, y, z);
1339    } else {
1340        double X, Y, Z;
1341        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
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
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);
1362    }
1363#ifdef GLA_DEBUG
1364    m_Vertices++;
1365#endif
1366}
1367
1368void GLACanvas::DrawBlob(glaCoord x, glaCoord y)
1369{
1370    if (blob_method != LINES) {
1371        // Draw a marker.
1372        PlaceVertex(x, y, 0);
1373    } else {
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);
1387    }
1388#ifdef GLA_DEBUG
1389    m_Vertices++;
1390#endif
1391}
1392
1393void GLACanvas::BeginCrosses()
1394{
1395    // Plot crosses.
1396    if (cross_method == SPRITE) {
1397        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1398        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib");
1399        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
1400        CHECK_GL_ERROR("BeginCrosses", "glBindTexture");
1401        glEnable(GL_ALPHA_TEST);
1402        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_ALPHA_TEST");
1403        glPointSize(8);
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");
1407        glEnable(GL_TEXTURE_2D);
1408        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_TEXTURE_2D");
1409        glEnable(GL_POINT_SPRITE);
1410        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_POINT_SPRITE");
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).
1417        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1418        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib 2");
1419        SetIndicatorTransform();
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");
1424        glEnable(GL_DEPTH_TEST);
1425        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_DEPTH_TEST");
1426        glBegin(GL_LINES);
1427    }
1428}
1429
1430void GLACanvas::EndCrosses()
1431{
1432    glEnd();
1433    if (cross_method == SPRITE) {
1434        CHECK_GL_ERROR("EndCrosses", "glEnd GL_POINTS");
1435    } else {
1436        CHECK_GL_ERROR("EndCrosses", "glEnd GL_LINES");
1437    }
1438    glPopAttrib();
1439    CHECK_GL_ERROR("EndCrosses", "glPopAttrib");
1440}
1441
1442void GLACanvas::DrawCross(glaCoord x, glaCoord y, glaCoord z)
1443{
1444    if (cross_method == SPRITE) {
1445        // Draw a marker.
1446        PlaceVertex(x, y, z);
1447    } else {
1448        double X, Y, Z;
1449        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
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.
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);
1461        // Need to extend lines by an extra pixel (which shouldn't get drawn by
1462        // the diamond-exit rule).
1463        PlaceVertex(X - 3, Y - 3, Z);
1464        PlaceVertex(X + 4, Y + 4, Z);
1465        PlaceVertex(X - 3, Y + 3, Z);
1466        PlaceVertex(X + 4, Y - 4, Z);
1467    }
1468#ifdef GLA_DEBUG
1469    m_Vertices++;
1470#endif
1471}
1472
1473void GLACanvas::DrawRing(glaCoord x, glaCoord y)
1474{
1475    // Draw an unfilled circle
1476    const Double radius = 4;
1477    assert(m_Quadric);
1478    glMatrixMode(GL_MODELVIEW);
1479    CHECK_GL_ERROR("DrawRing", "glMatrixMode");
1480    glPushMatrix();
1481    CHECK_GL_ERROR("DrawRing", "glPushMatrix");
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");
1486    glPopMatrix();
1487    CHECK_GL_ERROR("DrawRing", "glPopMatrix");
1488}
1489
1490void GLACanvas::DrawRectangle(gla_colour fill, gla_colour edge,
1491                              glaCoord x0, glaCoord y0, glaCoord w, glaCoord h)
1492{
1493    // Draw a filled rectangle with an edge in the indicator plane.
1494    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1495    // size.
1496
1497    SetColour(fill);
1498    BeginQuadrilaterals();
1499    PlaceIndicatorVertex(x0, y0);
1500    PlaceIndicatorVertex(x0 + w, y0);
1501    PlaceIndicatorVertex(x0 + w, y0 + h);
1502    PlaceIndicatorVertex(x0, y0 + h);
1503    EndQuadrilaterals();
1504
1505    if (edge != fill) {
1506        SetColour(edge);
1507        BeginPolyline();
1508        PlaceIndicatorVertex(x0, y0);
1509        PlaceIndicatorVertex(x0 + w, y0);
1510        PlaceIndicatorVertex(x0 + w, y0 + h);
1511        PlaceIndicatorVertex(x0, y0 + h);
1512        PlaceIndicatorVertex(x0, y0);
1513        EndLines();
1514    }
1515}
1516
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
1526    glShadeModel(GL_SMOOTH);
1527    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_SMOOTH");
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();
1536    glShadeModel(GL_FLAT);
1537    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_FLAT");
1538}
1539
1540void GLACanvas::DrawCircle(gla_colour edge, gla_colour fill,
1541                           glaCoord cx, glaCoord cy, glaCoord radius)
1542{
1543    // Draw a filled circle with an edge.
1544    SetColour(fill);
1545    glMatrixMode(GL_MODELVIEW);
1546    CHECK_GL_ERROR("DrawCircle", "glMatrixMode");
1547    glPushMatrix();
1548    CHECK_GL_ERROR("DrawCircle", "glPushMatrix");
1549    glTranslated(cx, cy, 0.0);
1550    CHECK_GL_ERROR("DrawCircle", "glTranslated");
1551    assert(m_Quadric);
1552    gluDisk(m_Quadric, 0.0, radius, 36, 1);
1553    CHECK_GL_ERROR("DrawCircle", "gluDisk");
1554    SetColour(edge);
1555    gluDisk(m_Quadric, radius - 1.0, radius, 36, 1);
1556    CHECK_GL_ERROR("DrawCircle", "gluDisk (2)");
1557    glPopMatrix();
1558    CHECK_GL_ERROR("DrawCircle", "glPopMatrix");
1559}
1560
1561void GLACanvas::DrawSemicircle(gla_colour edge, gla_colour fill,
1562                               glaCoord cx, glaCoord cy,
1563                               glaCoord radius, glaCoord start)
1564{
1565    // Draw a filled semicircle with an edge.
1566    // The semicircle extends from "start" deg to "start"+180 deg (increasing
1567    // clockwise, 0 deg upwards).
1568    SetColour(fill);
1569    glMatrixMode(GL_MODELVIEW);
1570    CHECK_GL_ERROR("DrawSemicircle", "glMatrixMode");
1571    glPushMatrix();
1572    CHECK_GL_ERROR("DrawSemicircle", "glPushMatrix");
1573    glTranslated(cx, cy, 0.0);
1574    CHECK_GL_ERROR("DrawSemicircle", "glTranslated");
1575    assert(m_Quadric);
1576    gluPartialDisk(m_Quadric, 0.0, radius, 36, 1, start, 180.0);
1577    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk");
1578    SetColour(edge);
1579    gluPartialDisk(m_Quadric, radius - 1.0, radius, 36, 1, start, 180.0);
1580    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk (2)");
1581    glPopMatrix();
1582    CHECK_GL_ERROR("DrawSemicircle", "glPopMatrix");
1583}
1584
1585void
1586GLACanvas::DrawTriangle(gla_colour edge, gla_colour fill,
1587                        const Vector3 &p0, const Vector3 &p1, const Vector3 &p2)
1588{
1589    // Draw a filled triangle with an edge.
1590
1591    SetColour(fill);
1592    BeginTriangles();
1593    PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1594    PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1595    PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1596    EndTriangles();
1597
1598    SetColour(edge);
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();
1604    CHECK_GL_ERROR("DrawTriangle", "glEnd GL_LINE_STRIP");
1605}
1606
1607void GLACanvas::EnableDashedLines()
1608{
1609    // Enable dashed lines, and start drawing in them.
1610
1611    glLineStipple(1, 0x3333);
1612    CHECK_GL_ERROR("EnableDashedLines", "glLineStipple");
1613    glEnable(GL_LINE_STIPPLE);
1614    CHECK_GL_ERROR("EnableDashedLines", "glEnable GL_LINE_STIPPLE");
1615}
1616
1617void GLACanvas::DisableDashedLines()
1618{
1619    glDisable(GL_LINE_STIPPLE);
1620    CHECK_GL_ERROR("DisableDashedLines", "glDisable GL_LINE_STIPPLE");
1621}
1622
1623bool GLACanvas::Transform(const Vector3 & v,
1624                          double* x_out, double* y_out, double* z_out) const
1625{
1626    // Convert from data coordinates to screen coordinates.
1627
1628    // Perform the projection.
1629    return gluProject(v.GetX(), v.GetY(), v.GetZ(),
1630                      modelview_matrix, projection_matrix, viewport,
1631                      x_out, y_out, z_out);
1632}
1633
1634void GLACanvas::ReverseTransform(Double x, Double y,
1635                                 double* x_out, double* y_out, double* z_out) const
1636{
1637    // Convert from screen coordinates to data coordinates.
1638
1639    // Perform the projection.
1640    gluUnProject(x, y, 0.0, modelview_matrix, projection_matrix, viewport,
1641                 x_out, y_out, z_out);
1642    CHECK_GL_ERROR("ReverseTransform", "gluUnProject");
1643}
1644
1645Double GLACanvas::SurveyUnitsAcrossViewport() const
1646{
1647    // Measure the current viewport in survey units, taking into account the
1648    // current display scale.
1649
1650    assert(m_Scale != 0.0);
1651    list_flags |= INVALIDATE_ON_SCALE;
1652    Double result = m_VolumeDiameter / m_Scale;
1653    if (y_size < x_size) {
1654        result = result * x_size / y_size;
1655    }
1656    return result;
1657}
1658
1659void GLACanvas::ToggleSmoothShading()
1660{
1661    m_SmoothShading = !m_SmoothShading;
1662}
1663
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();
1675
1676        wxImage img;
1677        wxString texture(wmsg_cfgpth());
1678        texture += wxCONFIG_PATH_SEPARATOR;
1679        texture += wxT("images");
1680        texture += wxCONFIG_PATH_SEPARATOR;
1681        texture += wxT("texture.png");
1682        if (!img.LoadFile(texture, wxBITMAP_TYPE_PNG)) {
1683            // FIXME
1684            fprintf(stderr, "Couldn't load image.\n");
1685            exit(1);
1686        }
1687
1688        // Generate mipmaps.
1689        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, // was GL_LUMINANCE
1690                          img.GetWidth(), img.GetHeight(),
1691                          GL_RGB, GL_UNSIGNED_BYTE, img.GetData());
1692        CHECK_GL_ERROR("ToggleTextured", "gluBuild2DMipmaps");
1693
1694        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1695        CHECK_GL_ERROR("ToggleTextured", "glTexEnvi");
1696    }
1697}
1698
1699bool GLACanvas::SaveScreenshot(const wxString & fnm, wxBitmapType type) const
1700{
1701    const int width = x_size;
1702    const int height = y_size;
1703    unsigned char *pixels = (unsigned char *)malloc(3 * width * (height + 1));
1704    if (!pixels) return false;
1705    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1706    CHECK_GL_ERROR("SaveScreenshot", "glReadPixels");
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.
1719    wxImage grab(width, height, pixels);
1720    return grab.SaveFile(fnm, type);
1721}
1722
1723bool GLACanvas::CheckVisualFidelity(const unsigned char * target) const
1724{
1725    unsigned char pixels[3 * 8 * 8];
1726    if (double_buffered) {
1727        glReadBuffer(GL_BACK);
1728        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1729    }
1730    glReadPixels(x_size / 2 - 4, y_size / 2 - 5, 8, 8,
1731                 GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1732    CHECK_GL_ERROR("CheckVisualFidelity", "glReadPixels");
1733    if (double_buffered) {
1734        glReadBuffer(GL_FRONT);
1735        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1736    }
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
1752    return (memcmp(pixels, target, sizeof(pixels)) == 0);
1753}
1754
1755void GLACanvas::ReadPixels(int width, int height, unsigned char * buf) const
1756{
1757    CHECK_GL_ERROR("ReadPixels", "glReadPixels");
1758    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)buf);
1759}
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.