source: nanovis/branches/1.2/nanovis.cpp @ 5428

Last change on this file since 5428 was 5406, checked in by ldelgass, 9 years ago

backport from trunk: remove unused ctor params

  • Property svn:eol-style set to native
File size: 31.6 KB
Line 
1/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 * ----------------------------------------------------------------------
4 * Nanovis: Visualization of Nanoelectronics Data
5 *
6 * ======================================================================
7 *  AUTHOR:  Wei Qiao <qiaow@purdue.edu>
8 *           Michael McLennan <mmclennan@purdue.edu>
9 *           Purdue Rendering and Perceptualization Lab (PURPL)
10 *
11 *  Copyright (c) 2004-2013  HUBzero Foundation, LLC
12 *
13 *  See the file "license.terms" for information on usage and
14 *  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 * ======================================================================
16 */
17
18#include <sys/time.h>
19#include <cassert>
20#include <cstdio>
21#include <cmath> // for fmod()
22
23#include <GL/glew.h>
24#include <GL/glut.h>
25
26#include <graphics/RenderContext.h>
27#include <vrmath/BBox.h>
28#include <vrmath/Vector3f.h>
29
30#include <util/FilePath.h>
31#include <util/Fonts.h>
32
33#include <BMPImageLoaderImpl.h>
34#include <ImageLoaderFactory.h>
35
36#include "config.h"
37#include "nanovis.h"
38#include "nanovisServer.h"
39#include "define.h"
40
41#include "Flow.h"
42#include "Grid.h"
43#include "HeightMap.h"
44#include "Camera.h"
45#include "LIC.h"
46#include "Shader.h"
47#include "PlaneRenderer.h"
48#include "PPMWriter.h"
49#include "Texture2D.h"
50#include "Trace.h"
51#include "TransferFunction.h"
52#include "Unirect.h"
53#include "VelocityArrowsSlice.h"
54#include "Volume.h"
55#include "VolumeInterpolator.h"
56#include "VolumeRenderer.h"
57
58using namespace nv;
59using namespace nv::graphics;
60using namespace nv::util;
61using namespace vrmath;
62
63// STATIC MEMBER DATA
64
65Tcl_Interp *NanoVis::interp = NULL;
66
67bool NanoVis::redrawPending = false;
68bool NanoVis::debugFlag = false;
69bool NanoVis::axisOn = true;
70
71int NanoVis::winWidth = NPIX;
72int NanoVis::winHeight = NPIX;
73int NanoVis::renderWindow = 0;
74unsigned char *NanoVis::screenBuffer = NULL;
75Texture2D *NanoVis::legendTexture = NULL;
76Fonts *NanoVis::fonts;
77Camera *NanoVis::_camera = NULL;
78RenderContext *NanoVis::renderContext = NULL;
79
80NanoVis::TransferFunctionHashmap NanoVis::tfTable;
81NanoVis::VolumeHashmap NanoVis::volumeTable;
82NanoVis::FlowHashmap NanoVis::flowTable;
83NanoVis::HeightMapHashmap NanoVis::heightMapTable;
84
85double NanoVis::magMin = DBL_MAX;
86double NanoVis::magMax = -DBL_MAX;
87float NanoVis::xMin = FLT_MAX;
88float NanoVis::xMax = -FLT_MAX;
89float NanoVis::yMin = FLT_MAX;
90float NanoVis::yMax = -FLT_MAX;
91float NanoVis::zMin = FLT_MAX;
92float NanoVis::zMax = -FLT_MAX;
93BBox NanoVis::sceneBounds;
94
95VolumeRenderer *NanoVis::volRenderer = NULL;
96VelocityArrowsSlice *NanoVis::velocityArrowsSlice = NULL;
97LIC *NanoVis::licRenderer = NULL;
98PlaneRenderer *NanoVis::planeRenderer = NULL;
99Grid *NanoVis::grid = NULL;
100
101//frame buffer for final rendering
102GLuint NanoVis::_finalFbo = 0;
103GLuint NanoVis::_finalColorTex = 0;
104GLuint NanoVis::_finalDepthRb = 0;
105
106// Default camera location.
107Vector3f def_eye(0.0f, 0.0f, 2.5f);
108
109void
110NanoVis::removeAllData()
111{
112    TRACE("Enter");
113
114    if (grid != NULL) {
115        TRACE("Deleting grid");
116        delete grid;
117    }
118    if (_camera != NULL) {
119        TRACE("Deleting camera");
120        delete _camera;
121    }
122    if (volRenderer != NULL) {
123        TRACE("Deleting volRenderer");
124        delete volRenderer;
125    }
126    if (planeRenderer != NULL) {
127        TRACE("Deleting planeRenderer");
128        delete planeRenderer;
129    }
130    if (legendTexture != NULL) {
131        TRACE("Deleting legendTexture");
132        delete legendTexture;
133    }
134    TRACE("Deleting flows");
135    deleteFlows(interp);
136    if (licRenderer != NULL) {
137        TRACE("Deleting licRenderer");
138        delete licRenderer;
139    }
140    if (velocityArrowsSlice != NULL) {
141        TRACE("Deleting velocityArrowsSlice");
142        delete velocityArrowsSlice;
143    }
144    if (renderContext != NULL) {
145        TRACE("Deleting renderContext");
146        delete renderContext;
147    }
148    if (screenBuffer != NULL) {
149        TRACE("Deleting screenBuffer");
150        delete [] screenBuffer;
151        screenBuffer = NULL;
152    }
153    if (fonts != NULL) {
154        TRACE("Deleting fonts");
155        delete fonts;
156    }
157    TRACE("Leave");
158}
159
160void
161NanoVis::eventuallyRedraw()
162{
163    if (!redrawPending) {
164        glutPostRedisplay();
165        redrawPending = true;
166    }
167}
168
169void
170NanoVis::panCamera(float dx, float dy)
171{
172    /* Move the camera and its target by equal amounts along the x and y
173     * axes. */
174    TRACE("pan: x=%f, y=%f", dx, dy);
175
176    _camera->x(def_eye.x - dx);
177    _camera->y(def_eye.y + dy);
178    TRACE("set eye to %f %f", _camera->x(), _camera->y());
179}
180
181void
182NanoVis::zoomCamera(float z)
183{
184    /* Move the camera and its target by equal amounts along the x and y
185     * axes. */
186    TRACE("zoom: z=%f", z);
187
188    _camera->z(def_eye.z / z);
189    TRACE("set camera z to %f", _camera->z());
190
191    collectBounds();
192
193    _camera->resetClippingRange(sceneBounds.min, sceneBounds.max);
194}
195
196void
197NanoVis::rotateCamera(float phi, float theta, float psi)
198{
199    _camera->orient(phi, theta, psi);
200}
201
202void
203NanoVis::orientCamera(double *quat)
204{
205    _camera->orient(quat);
206}
207
208void
209NanoVis::setCameraPosition(Vector3f pos)
210{
211    _camera->setPosition(pos);
212}
213
214void
215NanoVis::setCameraUpdir(Camera::AxisDirection dir)
216{
217    _camera->setUpdir(dir);
218}
219
220void
221NanoVis::resetCamera(bool resetOrientation)
222{
223    TRACE("Resetting all=%d", resetOrientation ? 1 : 0);
224
225    collectBounds();
226    _camera->reset(sceneBounds.min, sceneBounds.max, resetOrientation);
227
228    def_eye = _camera->getPosition();
229}
230
231/** \brief Load a 3D volume
232 *
233 * \param name Volume ID
234 * \param width Number of samples in X direction
235 * \param height Number of samples in Y direction
236 * \param depth Number of samples in Z direction
237 * \param numComponents the number of scalars for each space point. All component
238 * scalars for a point are placed consequtively in data array
239 * width, height and depth: number of points in each dimension
240 * \param data Array of floats
241 * \param vmin Min value of field
242 * \param vmax Max value of field
243 * \param nonZeroMin Minimum non-zero value of field
244 * \param data pointer to an array of floats.
245 */
246Volume *
247NanoVis::loadVolume(const char *name, int width, int height, int depth,
248                    int numComponents, float *data, double vmin, double vmax,
249                    double nonZeroMin)
250{
251    VolumeHashmap::iterator itr = volumeTable.find(name);
252    if (itr != volumeTable.end()) {
253        WARN("volume \"%s\" already exists", name);
254        removeVolume(itr->second);
255    }
256
257    Volume *volume = new Volume(width, height, depth,
258                                numComponents,
259                                data, vmin, vmax, nonZeroMin);
260    Volume::updatePending = true;
261    volume->name(name);
262    volumeTable[name] = volume;
263
264    return volume;
265}
266
267// Gets a colormap 1D texture by name.
268TransferFunction *
269NanoVis::getTransferFunction(const TransferFunctionId& id)
270{
271    TransferFunctionHashmap::iterator itr = tfTable.find(id);
272    if (itr == tfTable.end()) {
273        TRACE("No transfer function named \"%s\" found", id.c_str());
274        return NULL;
275    } else {
276        return itr->second;
277    }
278}
279
280// Creates of updates a colormap 1D texture by name.
281TransferFunction *
282NanoVis::defineTransferFunction(const TransferFunctionId& id,
283                                size_t n, float *data)
284{
285    TransferFunction *tf = getTransferFunction(id);
286    if (tf == NULL) {
287        TRACE("Creating new transfer function \"%s\"", id.c_str());
288        tf = new TransferFunction(id.c_str(), n, data);
289        tfTable[id] = tf;
290    } else {
291        TRACE("Updating existing transfer function \"%s\"", id.c_str());
292        tf->update(n, data);
293    }
294    return tf;
295}
296
297int
298NanoVis::renderLegend(TransferFunction *tf, double min, double max,
299                      int width, int height, const char *volArg)
300{
301    TRACE("Enter");
302
303    int old_width = winWidth;
304    int old_height = winHeight;
305
306    planeRenderer->setScreenSize(width, height);
307    resizeOffscreenBuffer(width, height);
308
309    // generate data for the legend
310    float data[512];
311    for (int i=0; i < 256; i++) {
312        data[i] = data[i+256] = (float)(i/255.0);
313    }
314    legendTexture = new Texture2D(256, 2, GL_FLOAT, GL_LINEAR, 1, data);
315    int index = planeRenderer->addPlane(legendTexture, tf);
316    planeRenderer->setActivePlane(index);
317
318    bindOffscreenBuffer();
319    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear screen
320    planeRenderer->render();
321
322    glPixelStorei(GL_PACK_ALIGNMENT, 1);
323    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, screenBuffer);
324    {
325        char prefix[200];
326
327        TRACE("Sending ppm legend image %s min:%g max:%g", volArg, min, max);
328        sprintf(prefix, "nv>legend %s %g %g", volArg, min, max);
329#ifdef USE_THREADS
330        queuePPM(g_queue, prefix, screenBuffer, width, height);
331#else
332        writePPM(g_fdOut, prefix, screenBuffer, width, height);
333#endif
334    }
335    planeRenderer->removePlane(index);
336    resizeOffscreenBuffer(old_width, old_height);
337
338    delete legendTexture;
339    legendTexture = NULL;
340    TRACE("Leave");
341    return TCL_OK;
342}
343
344//initialize frame buffer objects for offscreen rendering
345bool
346NanoVis::initOffscreenBuffer()
347{
348    TRACE("Enter");
349    assert(_finalFbo == 0);
350    // Initialize a fbo for final display.
351    glGenFramebuffersEXT(1, &_finalFbo);
352
353    glGenTextures(1, &_finalColorTex);
354    glBindTexture(GL_TEXTURE_2D, _finalColorTex);
355    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
356    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
357#if defined(HAVE_FLOAT_TEXTURES) && defined(USE_HALF_FLOAT)
358    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, winWidth, winHeight, 0,
359                 GL_RGB, GL_INT, NULL);
360#elif defined(HAVE_FLOAT_TEXTURES)
361    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, winWidth, winHeight, 0,
362                 GL_RGB, GL_INT, NULL);
363#else
364    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0,
365                 GL_RGB, GL_INT, NULL);
366#endif
367
368    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _finalFbo);
369    glGenRenderbuffersEXT(1, &_finalDepthRb);
370    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
371    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
372                             winWidth, winHeight);
373    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
374                              GL_TEXTURE_2D, _finalColorTex, 0);
375    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
376                                 GL_RENDERBUFFER_EXT, _finalDepthRb);
377
378    GLenum status;
379    if (!CheckFBO(&status)) {
380        PrintFBOStatus(status, "finalFbo");
381        return false;
382    }
383
384    TRACE("Leave");
385    return true;
386}
387
388//resize the offscreen buffer
389bool
390NanoVis::resizeOffscreenBuffer(int w, int h)
391{
392    TRACE("Enter (%d, %d)", w, h);
393    if ((w == winWidth) && (h == winHeight)) {
394        return true;
395    }
396    winWidth = w;
397    winHeight = h;
398
399    if (fonts) {
400        fonts->resize(w, h);
401    }
402    TRACE("screenBuffer size: %d %d", w, h);
403
404    if (screenBuffer != NULL) {
405        delete [] screenBuffer;
406        screenBuffer = NULL;
407    }
408
409    screenBuffer = new unsigned char[3*winWidth*winHeight];
410    assert(screenBuffer != NULL);
411
412    //delete the current render buffer resources
413    glDeleteTextures(1, &_finalColorTex);
414    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
415    glDeleteRenderbuffersEXT(1, &_finalDepthRb);
416
417    TRACE("before deleteframebuffers");
418    glDeleteFramebuffersEXT(1, &_finalFbo);
419
420    TRACE("reinitialize FBO");
421    //Reinitialize final fbo for final display
422    glGenFramebuffersEXT(1, &_finalFbo);
423
424    glGenTextures(1, &_finalColorTex);
425    glBindTexture(GL_TEXTURE_2D, _finalColorTex);
426    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
427    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
428#if defined(HAVE_FLOAT_TEXTURES) && defined(USE_HALF_FLOAT)
429    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, winWidth, winHeight, 0,
430                 GL_RGB, GL_INT, NULL);
431#elif defined(HAVE_FLOAT_TEXTURES)
432    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, winWidth, winHeight, 0,
433                 GL_RGB, GL_INT, NULL);
434#else
435    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0,
436                 GL_RGB, GL_INT, NULL);
437#endif
438
439    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _finalFbo);
440    glGenRenderbuffersEXT(1, &_finalDepthRb);
441    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
442    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
443                             winWidth, winHeight);
444    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
445                              GL_TEXTURE_2D, _finalColorTex, 0);
446    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
447                                 GL_RENDERBUFFER_EXT, _finalDepthRb);
448
449    GLenum status;
450    if (!CheckFBO(&status)) {
451        PrintFBOStatus(status, "finalFbo");
452        return false;
453    }
454
455    TRACE("change camera");
456    //change the camera setting
457    _camera->setViewport(0, 0, winWidth, winHeight);
458    planeRenderer->setScreenSize(winWidth, winHeight);
459
460    TRACE("Leave (%d, %d)", w, h);
461    return true;
462}
463
464bool NanoVis::init(const char* path)
465{
466    // print OpenGL driver information
467    TRACE("-----------------------------------------------------------");
468    TRACE("OpenGL version: %s", glGetString(GL_VERSION));
469    TRACE("OpenGL vendor: %s", glGetString(GL_VENDOR));
470    TRACE("OpenGL renderer: %s", glGetString(GL_RENDERER));
471    TRACE("-----------------------------------------------------------");
472
473    if (path == NULL) {
474        ERROR("No path defined for shaders or resources");
475        return false;
476    }
477    GLenum err = glewInit();
478    if (GLEW_OK != err) {
479        ERROR("Can't init GLEW: %s", glewGetErrorString(err));
480        return false;
481    }
482    TRACE("Using GLEW %s", glewGetString(GLEW_VERSION));
483
484    // OpenGL 2.1 includes VBOs, PBOs, MRT, NPOT textures, point parameters, point sprites,
485    // GLSL 1.2, and occlusion queries.
486    if (!GLEW_VERSION_2_1) {
487        ERROR("OpenGL version 2.1 or greater is required");
488        return false;
489    }
490
491    // NVIDIA driver may report OpenGL 2.1, but not support PBOs in
492    // indirect GLX contexts
493    if (!GLEW_ARB_pixel_buffer_object) {
494        ERROR("Pixel buffer objects are not supported by driver, please check that the user running nanovis has permissions to create a direct rendering context (e.g. user has read/write access to /dev/nvidia* device nodes in Linux).");
495        return false;
496    }
497
498    // Additional extensions not in 2.1 core
499
500    // Framebuffer objects were promoted in 3.0
501    if (!GLEW_EXT_framebuffer_object) {
502        ERROR("EXT_framebuffer_oject extension is required");
503        return false;
504    }
505    // Rectangle textures were promoted in 3.1
506    // FIXME: can use NPOT in place of rectangle textures
507    if (!GLEW_ARB_texture_rectangle) {
508        ERROR("ARB_texture_rectangle extension is required");
509        return false;
510    }
511#ifdef HAVE_FLOAT_TEXTURES
512    // Float color buffers and textures were promoted in 3.0
513    if (!GLEW_ARB_texture_float ||
514        !GLEW_ARB_color_buffer_float) {
515        ERROR("ARB_texture_float and ARB_color_buffer_float extensions are required");
516        return false;
517    }
518#endif
519    // FIXME: should use GLSL for portability
520#ifdef USE_ARB_PROGRAMS
521    if (!GLEW_ARB_vertex_program ||
522        !GLEW_ARB_fragment_program) {
523        ERROR("ARB_vertex_program and ARB_fragment_program extensions are required");
524        return false;
525    }
526#else
527    if (!GLEW_NV_vertex_program3 ||
528        !GLEW_NV_fragment_program2) {
529        ERROR("NV_vertex_program3 and NV_fragment_program2 extensions are required");
530        return false;
531    }
532#endif
533
534    if (!FilePath::getInstance()->setPath(path)) {
535        ERROR("can't set file path to %s", path);
536        return false;
537    }
538
539    ImageLoaderFactory::getInstance()->addLoaderImpl("bmp", new BMPImageLoaderImpl());
540
541    return true;
542}
543
544bool
545NanoVis::initGL()
546{
547    TRACE("in initGL");
548    //buffer to store data read from the screen
549    if (screenBuffer) {
550        delete[] screenBuffer;
551        screenBuffer = NULL;
552    }
553    screenBuffer = new unsigned char[3*winWidth*winHeight];
554    assert(screenBuffer != NULL);
555
556    //create the camera with default setting
557    _camera = new Camera(0, 0, winWidth, winHeight);
558    _camera->setPosition(def_eye);
559
560    glEnable(GL_TEXTURE_2D);
561    glShadeModel(GL_FLAT);
562    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
563    glClearColor(0, 0, 0, 1);
564    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
565
566    //initialize lighting
567    GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0};
568    GLfloat mat_shininess[] = {30.0};
569    GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0};
570
571    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
572    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
573    glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);
574    glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);
575    glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light);
576    glLightfv(GL_LIGHT1, GL_SPECULAR, white_light);
577
578    //frame buffer object for offscreen rendering
579    if (!initOffscreenBuffer()) {
580        return false;
581    }
582
583    fonts = new Fonts();
584    fonts->addFont("verdana", "verdana.fnt");
585    fonts->setFont("verdana");
586
587    renderContext = new RenderContext();
588
589    volRenderer = new VolumeRenderer();
590
591    planeRenderer = new PlaneRenderer(winWidth, winHeight);
592
593    velocityArrowsSlice = new VelocityArrowsSlice();
594
595    licRenderer = new LIC();
596
597    grid = new Grid();
598    grid->setFont(fonts);
599
600    //assert(glGetError()==0);
601
602    TRACE("leaving initGL");
603
604    return true;
605}
606
607void
608NanoVis::draw3dAxis()
609{
610    if (!axisOn)
611        return;
612
613    glPushAttrib(GL_ENABLE_BIT);
614
615    glDisable(GL_TEXTURE_2D);
616    glEnable(GL_DEPTH_TEST);
617    glEnable(GL_COLOR_MATERIAL);
618    glDisable(GL_BLEND);
619
620    //draw axes
621    GLUquadric *obj;
622
623    obj = gluNewQuadric();
624
625    int segments = 50;
626
627    glColor3f(0.8, 0.8, 0.8);
628    glPushMatrix();
629    glTranslatef(0.4, 0., 0.);
630    glRotatef(90, 1, 0, 0);
631    glRotatef(180, 0, 1, 0);
632    glScalef(0.0005, 0.0005, 0.0005);
633    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'x');
634    glPopMatrix();
635
636    glPushMatrix();
637    glTranslatef(0., 0.4, 0.);
638    glRotatef(90, 1, 0, 0);
639    glRotatef(180, 0, 1, 0);
640    glScalef(0.0005, 0.0005, 0.0005);
641    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'y');
642    glPopMatrix();
643
644    glPushMatrix();
645    glTranslatef(0., 0., 0.4);
646    glRotatef(90, 1, 0, 0);
647    glRotatef(180, 0, 1, 0);
648    glScalef(0.0005, 0.0005, 0.0005);
649    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'z');
650    glPopMatrix();
651
652    glEnable(GL_LIGHTING);
653    glEnable(GL_LIGHT0);
654
655    //glColor3f(0.2, 0.2, 0.8);
656    glPushMatrix();
657    glutSolidSphere(0.02, segments, segments );
658    glPopMatrix();
659
660    glPushMatrix();
661    glRotatef(-90, 1, 0, 0);
662    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
663    glPopMatrix();
664
665    glPushMatrix();
666    glTranslatef(0., 0.3, 0.);
667    glRotatef(-90, 1, 0, 0);
668    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
669    glPopMatrix();
670
671    glPushMatrix();
672    glRotatef(90, 0, 1, 0);
673    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
674    glPopMatrix();
675
676    glPushMatrix();
677    glTranslatef(0.3, 0., 0.);
678    glRotatef(90, 0, 1, 0);
679    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
680    glPopMatrix();
681
682    glPushMatrix();
683    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
684    glPopMatrix();
685
686    glPushMatrix();
687    glTranslatef(0., 0., 0.3);
688    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
689    glPopMatrix();
690
691    gluDeleteQuadric(obj);
692
693    glPopAttrib();
694}
695
696void NanoVis::update()
697{
698    VolumeInterpolator *volInterp = volRenderer->getVolumeInterpolator();
699    if (volInterp->isStarted()) {
700        struct timeval clock;
701        gettimeofday(&clock, NULL);
702        double elapsed_time = clock.tv_sec + clock.tv_usec/1000000.0 -
703            volInterp->getStartTime();
704
705        TRACE("%g %g", elapsed_time,
706              volInterp->getInterval());
707        double fraction;
708        double f = fmod(elapsed_time, volInterp->getInterval());
709        if (f == 0.0) {
710            fraction = 0.0;
711        } else {
712            fraction = f / volInterp->getInterval();
713        }
714        TRACE("fraction : %g", fraction);
715        volInterp->update((float)fraction);
716    }
717}
718
719/**
720 * \brief Called when new volumes are added to update ranges
721 */
722void
723NanoVis::setVolumeRanges()
724{
725    TRACE("Enter");
726
727    double xMin, xMax, yMin, yMax, zMin, zMax;
728    xMin = yMin = zMin = DBL_MAX;
729    xMax = yMax = zMax = -DBL_MAX;
730    double valueMin = DBL_MAX, valueMax = -DBL_MAX;
731    VolumeHashmap::iterator itr;
732    for (itr = volumeTable.begin();
733         itr != volumeTable.end(); ++itr) {
734        Volume *volume = itr->second;
735        if (xMin > volume->xAxis.min()) {
736            xMin = volume->xAxis.min();
737        }
738        if (xMax < volume->xAxis.max()) {
739            xMax = volume->xAxis.max();
740        }
741        if (yMin > volume->yAxis.min()) {
742            yMin = volume->yAxis.min();
743        }
744        if (yMax < volume->yAxis.max()) {
745            yMax = volume->yAxis.max();
746        }
747        if (zMin > volume->zAxis.min()) {
748            zMin = volume->zAxis.min();
749        }
750        if (zMax < volume->zAxis.max()) {
751            zMax = volume->zAxis.max();
752        }
753        if (valueMin > volume->wAxis.min()) {
754            valueMin = volume->wAxis.min();
755        }
756        if (valueMax < volume->wAxis.max()) {
757            valueMax = volume->wAxis.max();
758        }
759    }
760    if ((xMin < DBL_MAX) && (xMax > -DBL_MAX)) {
761        grid->xAxis.setScale(xMin, xMax);
762    }
763    if ((yMin < DBL_MAX) && (yMax > -DBL_MAX)) {
764        grid->yAxis.setScale(yMin, yMax);
765    }
766    if ((zMin < DBL_MAX) && (zMax > -DBL_MAX)) {
767        grid->zAxis.setScale(zMin, zMax);
768    }
769    if ((valueMin < DBL_MAX) && (valueMax > -DBL_MAX)) {
770        Volume::valueMin = valueMin;
771        Volume::valueMax = valueMax;
772    }
773    Volume::updatePending = false;
774    TRACE("Leave");
775}
776
777/**
778 * \brief Called when new heightmaps are added to update ranges
779 */
780void
781NanoVis::setHeightmapRanges()
782{
783    TRACE("Enter");
784
785    double xMin, xMax, yMin, yMax, zMin, zMax;
786    xMin = yMin = zMin = DBL_MAX;
787    xMax = yMax = zMax = -DBL_MAX;
788    double valueMin = DBL_MAX, valueMax = -DBL_MAX;
789    HeightMapHashmap::iterator itr;
790    for (itr = heightMapTable.begin();
791         itr != heightMapTable.end(); ++itr) {
792        HeightMap *heightMap = itr->second;
793        if (xMin > heightMap->xAxis.min()) {
794            xMin = heightMap->xAxis.min();
795        }
796        if (xMax < heightMap->xAxis.max()) {
797            xMax = heightMap->xAxis.max();
798        }
799        if (yMin > heightMap->yAxis.min()) {
800            yMin = heightMap->yAxis.min();
801        }
802        if (yMax < heightMap->yAxis.max()) {
803            yMax = heightMap->yAxis.max();
804        }
805        if (zMin > heightMap->zAxis.min()) {
806            zMin = heightMap->zAxis.min();
807        }
808        if (zMax < heightMap->zAxis.max()) {
809            zMax = heightMap->zAxis.max();
810        }
811        if (valueMin > heightMap->wAxis.min()) {
812            valueMin = heightMap->wAxis.min();
813        }
814        if (valueMax < heightMap->wAxis.max()) {
815            valueMax = heightMap->wAxis.max();
816        }
817    }
818    if ((xMin < DBL_MAX) && (xMax > -DBL_MAX)) {
819        grid->xAxis.setScale(xMin, xMax);
820    }
821    if ((yMin < DBL_MAX) && (yMax > -DBL_MAX)) {
822        grid->yAxis.setScale(yMin, yMax);
823    }
824    if ((zMin < DBL_MAX) && (zMax > -DBL_MAX)) {
825        grid->zAxis.setScale(zMin, zMax);
826    }
827    if ((valueMin < DBL_MAX) && (valueMax > -DBL_MAX)) {
828        HeightMap::valueMin = valueMin;
829        HeightMap::valueMax = valueMax;
830    }
831    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
832         itr != heightMapTable.end(); ++itr) {
833        itr->second->mapToGrid(grid);
834    }
835    HeightMap::updatePending = false;
836    TRACE("Leave");
837}
838
839void
840NanoVis::collectBounds(bool onlyVisible)
841{
842    if (Flow::updatePending) {
843        setFlowRanges();
844        grid->xAxis.setScale(xMin, xMax);
845        grid->yAxis.setScale(yMin, yMax);
846        grid->zAxis.setScale(zMin, zMax);
847    }
848
849    sceneBounds.makeEmpty();
850
851    for (VolumeHashmap::iterator itr = volumeTable.begin();
852         itr != volumeTable.end(); ++itr) {
853        Volume *volume = itr->second;
854
855        if (onlyVisible && !volume->visible())
856            continue;
857
858        BBox bbox;
859        volume->getWorldSpaceBounds(bbox.min, bbox.max);
860        sceneBounds.extend(bbox);
861    }
862
863    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
864         itr != heightMapTable.end(); ++itr) {
865        HeightMap *heightMap = itr->second;
866
867        if (onlyVisible && !heightMap->isVisible())
868            continue;
869
870        BBox bbox;
871        heightMap->getWorldSpaceBounds(bbox.min, bbox.max);
872        sceneBounds.extend(bbox);
873    }
874
875    BBox bbox;
876    getFlowBounds(bbox.min, bbox.max, onlyVisible);
877    sceneBounds.extend(bbox);
878
879#if 0
880    if (!onlyVisible || grid->isVisible()) {
881        BBox bbox;
882        grid->getBounds(bbox.min, bbox.max);
883        sceneBounds.extend(bbox);
884    }
885#endif
886
887    if (sceneBounds.isEmpty()) {
888        sceneBounds.min.set(-0.5, -0.5, -0.5);
889        sceneBounds.max.set( 0.5,  0.5,  0.5);
890    }
891
892    TRACE("Scene bounds: (%g,%g,%g) - (%g,%g,%g)",
893          sceneBounds.min.x, sceneBounds.min.y, sceneBounds.min.z,
894          sceneBounds.max.x, sceneBounds.max.y, sceneBounds.max.z);
895}
896
897void
898NanoVis::setBgColor(float color[3])
899{
900    TRACE("Setting bgcolor to %g %g %g", color[0], color[1], color[2]);
901    glClearColor(color[0], color[1], color[2], 1);
902}
903
904void
905NanoVis::removeVolume(Volume *volume)
906{
907    VolumeHashmap::iterator itr = volumeTable.find(volume->name());
908    if (itr != volumeTable.end()) {
909        volumeTable.erase(itr);
910    }
911    delete volume;
912}
913
914Flow *
915NanoVis::getFlow(const char *name)
916{
917    FlowHashmap::iterator itr = flowTable.find(name);
918    if (itr == flowTable.end()) {
919        TRACE("Can't find flow '%s'", name);
920        return NULL;
921    }
922    return itr->second;
923}
924
925Flow *
926NanoVis::createFlow(Tcl_Interp *interp, const char *name)
927{
928    FlowHashmap::iterator itr = flowTable.find(name);
929    if (itr != flowTable.end()) {
930        ERROR("Flow '%s' already exists", name);
931        return NULL;
932    }
933    Flow *flow = new Flow(interp, name);
934    flowTable[name] = flow;
935    return flow;
936}
937
938/**
939 * \brief Delete flow object and hash table entry
940 *
941 * This is called by the flow command instance delete callback
942 */
943void
944NanoVis::deleteFlow(const char *name)
945{
946    FlowHashmap::iterator itr = flowTable.find(name);
947    if (itr != flowTable.end()) {
948        delete itr->second;
949        flowTable.erase(itr);
950    }
951}
952
953/**
954 * \brief Delete all flow object commands
955 *
956 * This will also delete the flow objects and hash table entries
957 */
958void
959NanoVis::deleteFlows(Tcl_Interp *interp)
960{
961    FlowHashmap::iterator itr;
962    for (itr = flowTable.begin();
963         itr != flowTable.end(); ++itr) {
964        Tcl_DeleteCommandFromToken(interp, itr->second->getCommandToken());
965    }
966    flowTable.clear();
967}
968
969/**
970 * \brief Called when new flows are added to update ranges
971 */
972bool
973NanoVis::setFlowRanges()
974{
975    TRACE("Enter");
976
977    /*
978     * Step 1. Get the overall min and max magnitudes of all the
979     *         flow vectors.
980     */
981    magMin = DBL_MAX;
982    magMax = -DBL_MAX;
983
984    for (FlowHashmap::iterator itr = flowTable.begin();
985         itr != flowTable.end(); ++itr) {
986        Flow *flow = itr->second;
987        if (!flow->isDataLoaded()) {
988            continue;
989        }
990        Unirect3d *data = flow->data();
991        double range[2];
992        range[0] = data->magMin();
993        range[1] = data->magMax();
994        if (range[0] < magMin) {
995            magMin = range[0];
996        }
997        if (range[1] > magMax) {
998            magMax = range[1];
999        }
1000        if (data->xMin() < xMin) {
1001            xMin = data->xMin();
1002        }
1003        if (data->yMin() < yMin) {
1004            yMin = data->yMin();
1005        }
1006        if (data->zMin() < zMin) {
1007            zMin = data->zMin();
1008        }
1009        if (data->xMax() > xMax) {
1010            xMax = data->xMax();
1011        }
1012        if (data->yMax() > yMax) {
1013            yMax = data->yMax();
1014        }
1015        if (data->zMax() > zMax) {
1016            zMax = data->zMax();
1017        }
1018    }
1019
1020    TRACE("magMin=%g magMax=%g", NanoVis::magMin, NanoVis::magMax);
1021
1022    /*
1023     * Step 2. Generate the vector field from each data set.
1024     */
1025    for (FlowHashmap::iterator itr = flowTable.begin();
1026         itr != flowTable.end(); ++itr) {
1027        Flow *flow = itr->second;
1028        if (!flow->isDataLoaded()) {
1029            continue; // Flow exists, but no data has been loaded yet.
1030        }
1031        if (flow->visible()) {
1032            flow->initializeParticles();
1033        }
1034        if (!flow->scaleVectorField()) {
1035            return false;
1036        }
1037        // FIXME: This doesn't work when there is more than one flow.
1038        licRenderer->setSlicePosition(flow->getRelativePosition());
1039        velocityArrowsSlice->setSlicePosition(flow->getRelativePosition());
1040    }
1041    advectFlows();
1042
1043    Flow::updatePending = false;
1044    return true;
1045}
1046
1047void
1048NanoVis::getFlowBounds(Vector3f& min,
1049                       Vector3f& max,
1050                       bool onlyVisible)
1051{
1052    TRACE("Enter");
1053
1054    min.set(FLT_MAX, FLT_MAX, FLT_MAX);
1055    max.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
1056
1057    for (FlowHashmap::iterator itr = flowTable.begin();
1058         itr != flowTable.end(); ++itr) {
1059        itr->second->getBounds(min, max, onlyVisible);
1060    }
1061}
1062
1063void
1064NanoVis::renderFlows()
1065{
1066    for (FlowHashmap::iterator itr = flowTable.begin();
1067         itr != flowTable.end(); ++itr) {
1068        Flow *flow = itr->second;
1069        if (flow->isDataLoaded() && flow->visible()) {
1070            flow->render();
1071        }
1072    }
1073}
1074
1075void
1076NanoVis::resetFlows()
1077{
1078    NanoVis::licRenderer->reset();
1079    for (FlowHashmap::iterator itr = flowTable.begin();
1080         itr != flowTable.end(); ++itr) {
1081        Flow *flow = itr->second;
1082        if (flow->isDataLoaded()) {
1083            flow->resetParticles();
1084        }
1085    }
1086}   
1087
1088void
1089NanoVis::advectFlows()
1090{
1091    TRACE("Enter");
1092    for (FlowHashmap::iterator itr = flowTable.begin();
1093         itr != flowTable.end(); ++itr) {
1094        Flow *flow = itr->second;
1095        if (flow->isDataLoaded()) {
1096            flow->advect();
1097        }
1098    }
1099}
1100
1101void
1102NanoVis::render()
1103{
1104    TRACE("Enter");
1105
1106    if (Flow::updatePending) {
1107        setFlowRanges();
1108        grid->xAxis.setScale(xMin, xMax);
1109        grid->yAxis.setScale(yMin, yMax);
1110        grid->zAxis.setScale(zMin, zMax);
1111    }
1112    if (HeightMap::updatePending) {
1113        setHeightmapRanges();
1114    }
1115    if (Volume::updatePending) {
1116        setVolumeRanges();
1117    }
1118
1119    // Start final rendering
1120
1121    // Need to reset fbo since it may have been changed to default (0)
1122    bindOffscreenBuffer();
1123
1124    // Clear screen
1125    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1126
1127    glEnable(GL_DEPTH_TEST);
1128    glEnable(GL_COLOR_MATERIAL);
1129
1130    // Emit modelview and projection matrices
1131    _camera->initialize();
1132
1133    // Rotate for updir if required
1134    glPushMatrix();
1135
1136    switch (_camera->getUpdir()) {
1137    case Camera::X_POS:
1138        glRotatef(90, 0, 0, 1);
1139        glRotatef(90, 1, 0, 0);
1140        break;
1141    case Camera::Y_POS:
1142        // this is the default
1143        break;
1144    case Camera::Z_POS:
1145        glRotatef(-90, 1, 0, 0);
1146        glRotatef(-90, 0, 0, 1);
1147        break;
1148    case Camera::X_NEG:
1149        glRotatef(-90, 0, 0, 1);
1150        break;
1151    case Camera::Y_NEG:
1152        glRotatef(180, 0, 0, 1);
1153        glRotatef(-90, 0, 1, 0);
1154        break;
1155    case Camera::Z_NEG:
1156        glRotatef(90, 1, 0, 0);
1157        break;
1158    }
1159
1160    // Now render things in the scene
1161
1162    draw3dAxis();
1163
1164    grid->render();
1165
1166    licRenderer->render();
1167
1168    velocityArrowsSlice->render();
1169
1170    renderFlows();
1171
1172    volRenderer->renderAll();
1173
1174    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
1175         itr != heightMapTable.end(); ++itr) {
1176        itr->second->render(renderContext);
1177    }
1178    glPopMatrix();
1179
1180    CHECK_FRAMEBUFFER_STATUS();
1181    TRACE("Leave");
1182    redrawPending = false;
1183}
Note: See TracBrowser for help on using the repository browser.