source: trunk/packages/vizservers/nanovis/VolumeRenderer.cpp @ 1429

Last change on this file since 1429 was 1429, checked in by gah, 15 years ago

Initial commit of new flow visualization command structure

File size: 31.5 KB
Line 
1/*
2 * ----------------------------------------------------------------------
3 * VolumeRenderer.cpp : VolumeRenderer class for volume visualization
4 *
5 * ======================================================================
6 *  AUTHOR:  Wei Qiao <qiaow@purdue.edu>
7 *           Purdue Rendering and Perceptualization Lab (PURPL)
8 *
9 *  Copyright (c) 2004-2006  Purdue Research Foundation
10 *
11 *  See the file "license.terms" for information on usage and
12 *  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 * ======================================================================
14 */
15
16#include <assert.h>
17#include <time.h>
18#include <sys/time.h>
19#include "nanovis.h"
20#include <R2/R2string.h>
21#include <R2/R2FilePath.h>
22#include "VolumeRenderer.h"
23#include "VolumeInterpolator.h"
24#include "NvStdVertexShader.h"
25#include "Trace.h"
26#include "Grid.h"
27
28#define NUMDIGITS       6
29
30VolumeRenderer::VolumeRenderer():
31  n_volumes(0),
32  slice_mode(false),
33  volume_mode(true)
34{
35    volume.clear();
36    tf.clear();
37
38    init_shaders();
39
40    const char *path = R2FilePath::getInstance()->getPath("Font.bmp");
41    if (path == NULL) {
42        fprintf(stderr, "can't find Font.bmp\n");
43        assert(path != NULL);
44    }
45    init_font(path);
46    delete [] path;
47    _volumeInterpolator = new VolumeInterpolator();
48}
49
50VolumeRenderer::~VolumeRenderer()
51{
52    delete _zincBlendeShader;
53    delete _regularVolumeShader;
54    delete _stdVertexShader;
55    delete _volumeInterpolator;
56}
57
58//initialize the volume shaders
59void VolumeRenderer::init_shaders(){
60 
61  //standard vertex program
62  _stdVertexShader = new NvStdVertexShader();
63
64  //volume rendering shader: one cubic volume
65  _regularVolumeShader = new NvRegularVolumeShader();
66
67  //volume rendering shader: one zincblende orbital volume.
68  //This shader renders one orbital of the simulation.
69  //A sim has S, P, D, SS orbitals. thus a full rendering requires 4 zincblende orbital volumes.
70  //A zincblende orbital volume is decomposed into 2 "interlocking" cubic 4-component volumes and passed to the shader.
71  //We render each orbital with a independent transfer functions then blend the result.
72  //
73  //The engine is already capable of rendering multiple volumes and combine them. Thus, we just invoke this shader on
74  //S, P, D and SS orbitals with different transfor functions. The result is a multi-orbital rendering.
75  _zincBlendeShader = new NvZincBlendeVolumeShader();
76}
77
78
79int VolumeRenderer::add_volume(Volume* _vol, TransferFunction* _tf){
80
81  int ret = n_volumes;
82
83  volume.push_back(_vol);
84  tf.push_back(_tf);
85
86  n_volumes++;
87
88  return ret;
89}
90
91/*
92 * FIXME:  This is a good example of the wrong data structures being used.
93 *         The volumes should be in a list not a vector.  Each list
94 *         element should contain pointers to both the volume and the
95 *         transfer function.  The shouldn't be parallel vectors. 
96 *
97 *         And there shouldn't be one vector for "all" volumes and another
98 *         for those being rendered, unless you work to keep them in sync. 
99 *         Use one master list instead.
100 */
101void
102VolumeRenderer::remove_volume(size_t volIndex)
103{
104    vector<Volume *>::iterator vIter;
105    vector<TransferFunction *>::iterator tfIter;
106
107    assert(volIndex < volume.size());
108    assert(volIndex < tf.size());
109
110    vIter = volume.begin();
111    tfIter = tf.begin();
112    size_t i;
113    for (i = 0; i < volIndex; i++) {
114        tfIter++;
115        vIter++;
116    }
117    volume.erase(vIter);
118    tf.erase(tfIter);
119    n_volumes--;
120}
121
122void
123VolumeRenderer::shade_volume(Volume* _vol, TransferFunction* _tf)
124{
125    for (unsigned int i=0; i < volume.size(); i++) {
126        if (volume[i] == _vol) {
127            tf[i] = _tf;
128        }
129    }
130}
131
132TransferFunction*
133VolumeRenderer::get_volume_shading(Volume* _vol)
134{
135    for (unsigned int i=0; i < volume.size(); i++) {
136        if (volume[i] == _vol) {
137            return tf[i];
138        }
139    }
140    return NULL;
141}
142
143struct SortElement {
144    float z;
145    int volume_id;
146    int slice_id;
147    SortElement(float _z, int _v, int _s):
148        z(_z), volume_id(_v), slice_id(_s){}
149};
150
151int slice_sort(const void* a, const void* b){
152  if((*((SortElement*)a)).z > (*((SortElement*)b)).z)
153      return 1;
154   else
155      return -1;
156}
157
158void VolumeRenderer::render_all_points()
159{
160#ifdef notdef
161    double x0 = 0;
162    double y0 = 0;
163    double z0 = 0;
164   
165    for(int i=0; i<n_volumes; i++){
166        int volume_index = i;
167        if(!volume[i]->is_enabled())
168            continue; //skip this volume
169       
170        Vector3* location = volume[volume_index]->get_location();
171        Vector4 shift_4d(location->x, location->y, location->z, 0);
172       
173        glPushMatrix();
174        glTranslatef(shift_4d.x, shift_4d.y, shift_4d.z);
175       
176        if (volume[volume_index]->outline_is_enabled()) {
177            float olcolor[3];
178            volume[volume_index]->get_outline_color(olcolor);
179            draw_bounding_box(x0, y0, z0, x0+1, y0+1, z0+1,
180                (double)olcolor[0], (double)olcolor[1], (double)olcolor[2], 1.5);
181        }
182       
183        glPopMatrix();
184    }
185#endif
186}
187
188void
189VolumeRenderer::render_all()
190{
191    Volume* cur_vol = 0;
192    Volume* ani_vol = 0;
193    TransferFunction* cur_tf = 0;
194    TransferFunction* ani_tf = 0;
195    int total_rendered_slices = 0;
196    int num_volumes = n_volumes;
197
198    if (_volumeInterpolator->is_started()) {
199        ++num_volumes;
200        ani_tf = tf[_volumeInterpolator->getReferenceVolumeID()];
201        ani_vol = _volumeInterpolator->getVolume();
202    }
203
204    //two dimension pointer array
205    ConvexPolygon*** polys = new ConvexPolygon**[num_volumes]; 
206    //number of actual slices for each volume
207    int* actual_slices = new int[num_volumes];
208
209    for(int vol_index = 0; vol_index< num_volumes; vol_index++) {
210        cur_vol = NULL;
211        cur_tf = NULL;
212#ifdef notdef
213        if (vol_index != n_volumes) {
214            cur_vol = volume[vol_index];
215            cur_tf = tf[vol_index];
216        } else {
217            cur_vol = ani_vol;
218            cur_tf = ani_tf;
219        }
220#else
221        cur_vol = volume[vol_index];
222        cur_tf = tf[vol_index];
223#endif
224
225        polys[vol_index] = NULL;
226        actual_slices[vol_index] = 0;
227
228        if(!cur_vol->is_enabled()) {
229            continue; //skip this volume
230        }
231
232        int n_slices = cur_vol->get_n_slice();
233        if (cur_vol->get_isosurface()) {
234            // double the number of slices
235            n_slices <<= 1;
236        }
237       
238        //volume start location
239        Vector3* location = cur_vol->get_location();
240        Vector4 shift_4d(location->x, location->y, location->z, 0);
241       
242        double x0 = 0;
243        double y0 = 0;
244        double z0 = 0;
245       
246        Mat4x4 model_view_no_trans, model_view_trans;
247        Mat4x4 model_view_no_trans_inverse, model_view_trans_inverse;
248       
249        double zNear, zFar;
250       
251        //initialize volume plane with world coordinates
252        Plane volume_planes[6];
253        volume_planes[0].set_coeffs( 1,  0,  0, -x0);
254        volume_planes[1].set_coeffs(-1,  0,  0,  x0+1);
255        volume_planes[2].set_coeffs( 0,  1,  0, -y0);
256        volume_planes[3].set_coeffs( 0, -1,  0,  y0+1);
257        volume_planes[4].set_coeffs( 0,  0,  1, -z0);
258        volume_planes[5].set_coeffs( 0,  0, -1,  z0+1);
259       
260        //get modelview matrix with no translation
261        glPushMatrix();
262        glScalef(cur_vol->aspect_ratio_width,
263                 cur_vol->aspect_ratio_height,
264                 cur_vol->aspect_ratio_depth);
265       
266        glEnable(GL_DEPTH_TEST);
267       
268        GLfloat mv_no_trans[16];
269        glGetFloatv(GL_MODELVIEW_MATRIX, mv_no_trans);
270       
271        model_view_no_trans = Mat4x4(mv_no_trans);
272        model_view_no_trans_inverse = model_view_no_trans.inverse();
273       
274        glPopMatrix();
275       
276        //get modelview matrix with translation
277        glPushMatrix();
278        glTranslatef(shift_4d.x, shift_4d.y, shift_4d.z);
279        glScalef(cur_vol->aspect_ratio_width,
280                 cur_vol->aspect_ratio_height,
281                 cur_vol->aspect_ratio_depth);
282        GLfloat mv_trans[16];
283        glGetFloatv(GL_MODELVIEW_MATRIX, mv_trans);
284       
285        model_view_trans = Mat4x4(mv_trans);
286        model_view_trans_inverse = model_view_trans.inverse();
287       
288        //draw volume bounding box with translation (the correct location in
289        //space)
290        if (cur_vol->outline_is_enabled()) {
291            float olcolor[3];
292            cur_vol->get_outline_color(olcolor);
293            draw_bounding_box(x0, y0, z0, x0+1, y0+1, z0+1,
294                (double)olcolor[0], (double)olcolor[1], (double)olcolor[2],
295                1.5);
296        }
297        glPopMatrix();
298       
299        //draw labels
300        glPushMatrix();
301        glTranslatef(shift_4d.x, shift_4d.y, shift_4d.z);
302        if(cur_vol->outline_is_enabled()) {
303            //draw_label(i);
304        }
305        glPopMatrix();
306       
307        //transform volume_planes to eye coordinates.
308        for(int i=0; i<6; i++)
309            volume_planes[i].transform(model_view_no_trans);
310       
311        get_near_far_z(mv_no_trans, zNear, zFar);
312       
313        //compute actual rendering slices
314        float z_step = fabs(zNear-zFar)/n_slices;               
315        int n_actual_slices;
316       
317        if (cur_vol->data_is_enabled()) {
318            n_actual_slices = (int)(fabs(zNear-zFar)/z_step + 1);
319            polys[vol_index] = new ConvexPolygon*[n_actual_slices];
320        } else {
321            n_actual_slices = 0;
322            polys[vol_index] = NULL;
323        }
324        actual_slices[vol_index] = n_actual_slices;
325       
326        Vector4 vert1 = (Vector4(-10, -10, -0.5, 1));
327        Vector4 vert2 = (Vector4(-10, +10, -0.5, 1));
328        Vector4 vert3 = (Vector4(+10, +10, -0.5, 1));
329        Vector4 vert4 = (Vector4(+10, -10, -0.5, 1));
330       
331       
332        // Render cutplanes first with depth test enabled.  They will mark the
333        // image with their depth values.  Then we render other volume slices.
334        // These volume slices will be occluded correctly by the cutplanes and
335        // vice versa.
336       
337        ConvexPolygon static_poly;
338        for(int i=0; i<cur_vol->get_cutplane_count(); i++) {
339            if(!cur_vol->cutplane_is_enabled(i))
340                continue;
341           
342            float offset = cur_vol->get_cutplane(i)->offset;
343            int axis = cur_vol->get_cutplane(i)->orient;
344           
345            if(axis==3){
346                vert1 = Vector4(-10, -10, offset, 1);
347                vert2 = Vector4(-10, +10, offset, 1);
348                vert3 = Vector4(+10, +10, offset, 1);
349                vert4 = Vector4(+10, -10, offset, 1);
350                //continue;
351            } else if(axis==1){
352                vert1 = Vector4(offset, -10, -10, 1);
353                vert2 = Vector4(offset, +10, -10, 1);
354                vert3 = Vector4(offset, +10, +10, 1);
355                vert4 = Vector4(offset, -10, +10, 1);
356                //continue;
357            } else if(axis==2){
358                vert1 = Vector4(-10, offset, -10, 1);
359                vert2 = Vector4(+10, offset, -10, 1);
360                vert3 = Vector4(+10, offset, +10, 1);
361                vert4 = Vector4(-10, offset, +10, 1);
362                //continue;
363            }
364           
365            vert1 = model_view_no_trans.transform(vert1);
366            vert2 = model_view_no_trans.transform(vert2);
367            vert3 = model_view_no_trans.transform(vert3);
368            vert4 = model_view_no_trans.transform(vert4);
369           
370            ConvexPolygon* p = &static_poly;
371            p->vertices.clear();
372           
373            p->append_vertex(vert1);
374            p->append_vertex(vert2);
375            p->append_vertex(vert3);
376            p->append_vertex(vert4);
377           
378            for(int k=0; k<6; k++){
379                p->clip(volume_planes[k], true);
380            }
381           
382            p->transform(model_view_no_trans_inverse);
383            p->transform(model_view_trans);
384           
385            glPushMatrix();
386            glScalef(cur_vol->aspect_ratio_width, cur_vol->aspect_ratio_height,
387                     cur_vol->aspect_ratio_depth);
388           
389            activate_volume_shader(cur_vol, cur_tf, true);
390            glPopMatrix();
391           
392            glEnable(GL_DEPTH_TEST);
393            glDisable(GL_BLEND);
394           
395            glBegin(GL_POLYGON);
396            p->Emit(true);
397            glEnd();
398            glDisable(GL_DEPTH_TEST);
399           
400            deactivate_volume_shader();
401        } //done cutplanes
402       
403       
404        //Now do volume rendering
405       
406        vert1 = (Vector4(-10, -10, -0.5, 1));
407        vert2 = (Vector4(-10, +10, -0.5, 1));
408        vert3 = (Vector4(+10, +10, -0.5, 1));
409        vert4 = (Vector4(+10, -10, -0.5, 1));
410       
411        int counter = 0;
412       
413        //transform slices and store them
414        float slice_z;
415        for (int i=0; i<n_actual_slices; i++) {
416            slice_z = zFar + i * z_step;        //back to front
417           
418            ConvexPolygon *poly = new ConvexPolygon();
419            polys[vol_index][counter] = poly;
420            counter++;
421           
422            poly->vertices.clear();
423            poly->set_id(vol_index);
424           
425            //Setting Z-coordinate
426            vert1.z = slice_z;
427            vert2.z = slice_z;
428            vert3.z = slice_z;
429            vert4.z = slice_z;
430           
431            poly->append_vertex(vert1);
432            poly->append_vertex(vert2);
433            poly->append_vertex(vert3);
434            poly->append_vertex(vert4);
435           
436            for(int k=0; k<6; k++) {
437                poly->clip(volume_planes[k], true);
438            }
439           
440            poly->transform(model_view_no_trans_inverse);
441            poly->transform(model_view_trans);
442           
443            if(poly->vertices.size()>=3)
444                total_rendered_slices++;
445        }
446       
447    } //iterate all volumes
448    //fprintf(stderr, "total slices: %d\n", total_rendered_slices);
449   
450    //We sort all the polygons according to their eye-space depth, from farthest to the closest.
451    //This step is critical for correct blending
452   
453    SortElement* slices = (SortElement*)malloc(sizeof(SortElement)*total_rendered_slices);
454   
455    int counter = 0;
456    for(int i=0; i<num_volumes; i++){
457        for(int j=0; j<actual_slices[i]; j++){
458            if(polys[i][j]->vertices.size() >= 3){
459                slices[counter] = SortElement(polys[i][j]->vertices[0].z, i, j);
460                counter++;
461            }
462        }
463    }
464   
465    //sort them
466    qsort(slices, total_rendered_slices, sizeof(SortElement), slice_sort);
467   
468    //Now we are ready to render all the slices from back to front
469    glEnable(GL_DEPTH_TEST);
470    glEnable(GL_BLEND);
471   
472    for(int i=0; i<total_rendered_slices; i++){
473        int volume_index = slices[i].volume_id;
474        int slice_index = slices[i].slice_id;
475        ConvexPolygon* cur = polys[volume_index][slice_index];
476       
477        if (volume_index == n_volumes) {
478            cur_vol = ani_vol;
479            cur_tf = ani_tf;
480        } else {
481            cur_vol = volume[volume_index];
482            cur_tf = tf[volume_index];
483        }
484       
485       
486        glPushMatrix();
487        glScalef(cur_vol->aspect_ratio_width, cur_vol->aspect_ratio_height, cur_vol->aspect_ratio_depth);
488       
489        activate_volume_shader(cur_vol, cur_tf, false);
490        glPopMatrix();
491       
492        glBegin(GL_POLYGON);
493        cur->Emit(true);
494        glEnd();
495
496        deactivate_volume_shader();
497    }
498   
499   
500    glDisable(GL_DEPTH_TEST);
501    glDisable(GL_BLEND);
502   
503    //Deallocate all the memory used
504    for(int i=0; i<num_volumes; i++){
505        for(int j=0; j<actual_slices[i]; j++){
506            delete polys[i][j];
507        }
508       
509        if (polys[i]) {
510            delete[] polys[i];
511        }
512    }
513   
514    delete[] polys;
515    delete[] actual_slices;
516    free(slices);
517}
518
519void VolumeRenderer::render(int volume_index)
520{
521  int n_slices = volume[volume_index]->get_n_slice();
522
523  //volume start location
524  Vector4 shift_4d(volume[volume_index]->location.x,
525                   volume[volume_index]->location.y,
526                   volume[volume_index]->location.z, 0);
527
528  double x0 = 0;
529  double y0 = 0;
530  double z0 = 0;
531
532  Mat4x4 model_view_no_trans, model_view_trans;
533  Mat4x4 model_view_no_trans_inverse, model_view_trans_inverse;
534
535  double zNear, zFar;
536
537  //initialize volume plane with world coordinates
538  Plane volume_planes[6];
539  volume_planes[0].set_coeffs(1, 0, 0, -x0);
540  volume_planes[1].set_coeffs(-1, 0, 0, x0+1);
541  volume_planes[2].set_coeffs(0, 1, 0, -y0);
542  volume_planes[3].set_coeffs(0, -1, 0, y0+1);
543  volume_planes[4].set_coeffs(0, 0, 1, -z0);
544  volume_planes[5].set_coeffs(0, 0, -1, z0+1);
545 
546  glPushMatrix();
547
548  glScalef(volume[volume_index]->aspect_ratio_width,
549          volume[volume_index]->aspect_ratio_height,
550          volume[volume_index]->aspect_ratio_depth);
551
552  glEnable(GL_DEPTH_TEST);
553
554  GLfloat mv_no_trans[16];
555  glGetFloatv(GL_MODELVIEW_MATRIX, mv_no_trans);
556
557  model_view_no_trans = Mat4x4(mv_no_trans);
558  model_view_no_trans_inverse = model_view_no_trans.inverse();
559
560  glPopMatrix();
561
562  //get modelview matrix with translation
563  glPushMatrix();
564  glTranslatef(shift_4d.x, shift_4d.y, shift_4d.z);
565  glScalef(volume[volume_index]->aspect_ratio_width,
566          volume[volume_index]->aspect_ratio_height,
567          volume[volume_index]->aspect_ratio_depth);
568  GLfloat mv_trans[16];
569  glGetFloatv(GL_MODELVIEW_MATRIX, mv_trans);
570
571  model_view_trans = Mat4x4(mv_trans);
572  model_view_trans_inverse = model_view_trans.inverse();
573
574  //draw volume bounding box
575  if (volume[volume_index]->outline_is_enabled()) {
576      draw_bounding_box(x0, y0, z0, x0+1, y0+1, z0+1, 0.8, 0.1, 0.1, 1.5);
577  }
578  glPopMatrix();
579
580  //transform volume_planes to eye coordinates.
581  for(int i=0; i<6; i++)
582    volume_planes[i].transform(model_view_no_trans);
583
584  get_near_far_z(mv_no_trans, zNear, zFar);
585  //fprintf(stderr, "zNear:%f, zFar:%f\n", zNear, zFar);
586  //fflush(stderr);
587
588  //compute actual rendering slices
589  float z_step = fabs(zNear-zFar)/n_slices;             
590  int n_actual_slices = (int)(fabs(zNear-zFar)/z_step + 1);
591  //fprintf(stderr, "slices: %d\n", n_actual_slices);
592  //fflush(stderr);
593
594  static ConvexPolygon staticPoly;     
595  float slice_z;
596
597  Vector4 vert1 = (Vector4(-10, -10, -0.5, 1));
598  Vector4 vert2 = (Vector4(-10, +10, -0.5, 1));
599  Vector4 vert3 = (Vector4(+10, +10, -0.5, 1));
600  Vector4 vert4 = (Vector4(+10, -10, -0.5, 1));
601
602  glEnable(GL_BLEND);
603
604  if(slice_mode){
605    glEnable(GL_DEPTH_TEST);
606
607  //render the cut planes
608  for(int i=0; i<volume[volume_index]->get_cutplane_count(); i++){
609    float offset = volume[volume_index]->get_cutplane(i)->offset;
610    int axis = volume[volume_index]->get_cutplane(i)->orient;
611
612    if (axis==1) {
613      vert1 = Vector4(-10, -10, offset, 1);
614      vert2 = Vector4(-10, +10, offset, 1);
615      vert3 = Vector4(+10, +10, offset, 1);
616      vert4 = Vector4(+10, -10, offset, 1);
617    } else if(axis==2){
618      vert1 = Vector4(offset, -10, -10, 1);
619      vert2 = Vector4(offset, +10, -10, 1);
620      vert3 = Vector4(offset, +10, +10, 1);
621      vert4 = Vector4(offset, -10, +10, 1);
622    } else if(axis==3) {
623      vert1 = Vector4(-10, offset, -10, 1);
624      vert2 = Vector4(+10, offset, -10, 1);
625      vert3 = Vector4(+10, offset, +10, 1);
626      vert4 = Vector4(-10, offset, +10, 1);
627    }
628
629    vert1 = model_view_no_trans.transform(vert1);
630    vert2 = model_view_no_trans.transform(vert2);
631    vert3 = model_view_no_trans.transform(vert3);
632    vert4 = model_view_no_trans.transform(vert4);
633
634    ConvexPolygon *poly;
635    poly = &staticPoly;
636    poly->vertices.clear();
637
638    poly->append_vertex(vert1);
639    poly->append_vertex(vert2);
640    poly->append_vertex(vert3);
641    poly->append_vertex(vert4);
642
643    for(int k=0; k<6; k++){
644      poly->clip(volume_planes[k], true);
645    }
646
647    //poly->transform(model_view_inverse);
648    //poly->translate(shift_4d);
649    //poly->transform(model_view);
650    poly->transform(model_view_no_trans_inverse);
651    poly->transform(model_view_trans);
652
653    glPushMatrix();
654    glScalef(volume[volume_index]->aspect_ratio_width, volume[volume_index]->aspect_ratio_height, volume[volume_index]->aspect_ratio_depth);
655
656    activate_volume_shader(volume[volume_index], tf[volume_index], true);
657    glPopMatrix();
658
659    glBegin(GL_POLYGON);
660      poly->Emit(true);
661    glEnd();
662
663    deactivate_volume_shader();
664  }
665  } //slice_mode
666
667
668  if(volume_mode){
669  glEnable(GL_DEPTH_TEST);
670
671  for (int i=0; i<n_actual_slices; i++){
672    slice_z = zFar + i * z_step;        //back to front
673       
674    ConvexPolygon *poly;
675    poly = &staticPoly;
676    poly->vertices.clear();
677
678    //Setting Z-coordinate
679    vert1.z = slice_z;
680    vert2.z = slice_z;
681    vert3.z = slice_z;
682    vert4.z = slice_z;
683               
684    poly->append_vertex(vert1);
685    poly->append_vertex(vert2);
686    poly->append_vertex(vert3);
687    poly->append_vertex(vert4);
688       
689    for(int k=0; k<6; k++){
690      poly->clip(volume_planes[k], true);
691    }
692
693    //move the volume to the proper location
694    //poly->transform(model_view_inverse);
695    //poly->translate(shift_4d);
696    //poly->transform(model_view);
697
698    poly->transform(model_view_no_trans_inverse);
699    poly->transform(model_view_trans);
700
701    glPushMatrix();
702    glScalef(volume[volume_index]->aspect_ratio_width, volume[volume_index]->aspect_ratio_height, volume[volume_index]->aspect_ratio_depth);
703   
704   /*
705    //draw slice lines only
706    glDisable(GL_BLEND);
707    glDisable(GL_TEXTURE_3D);
708    glDisable(GL_TEXTURE_2D);
709    glLineWidth(1.0);
710    glColor3f(1,1,1);
711    glBegin(GL_LINE_LOOP);
712      poly->Emit(false);
713    glEnd();
714    */
715   
716    activate_volume_shader(volume[volume_index], tf[volume_index], true);
717    glPopMatrix();
718
719    glBegin(GL_POLYGON);
720      poly->Emit(true);
721    glEnd();
722
723    deactivate_volume_shader();
724               
725  }
726  } //volume_mode
727
728  glDisable(GL_BLEND);
729  glDisable(GL_DEPTH_TEST);
730}
731
732void
733VolumeRenderer::draw_bounding_box(
734    float x0, float y0, float z0,
735    float x1, float y1, float z1,
736    float r, float g, float b,
737    float line_width)
738{
739    glPushMatrix();
740    glEnable(GL_DEPTH_TEST);
741    glDisable(GL_TEXTURE_2D);
742    glEnable(GL_BLEND);
743
744    glColor4d(r, g, b, 1.0);
745    glLineWidth(line_width);
746   
747    glBegin(GL_LINE_LOOP);
748    {
749        glVertex3d(x0, y0, z0);
750        glVertex3d(x1, y0, z0);
751        glVertex3d(x1, y1, z0);
752        glVertex3d(x0, y1, z0);
753    }
754    glEnd();
755   
756    glBegin(GL_LINE_LOOP);
757    {
758        glVertex3d(x0, y0, z1);
759        glVertex3d(x1, y0, z1);
760        glVertex3d(x1, y1, z1);
761        glVertex3d(x0, y1, z1);
762    }
763    glEnd();
764   
765   
766    glBegin(GL_LINE_LOOP);
767    {
768        glVertex3d(x0, y0, z0);
769        glVertex3d(x0, y0, z1);
770        glVertex3d(x0, y1, z1);
771        glVertex3d(x0, y1, z0);
772    }
773    glEnd();
774   
775    glBegin(GL_LINE_LOOP);
776    {
777        glVertex3d(x1, y0, z0);
778        glVertex3d(x1, y0, z1);
779        glVertex3d(x1, y1, z1);
780        glVertex3d(x1, y1, z0);
781    }
782    glEnd();
783
784#ifdef notdef
785    /* Rappture doesn't supply axis units yet. So turn labeling off until we
786     * can display the proper units with the distance of each bounding box
787     * dimension.
788     */
789    glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
790
791    if (NanoVis::fonts != NULL) {
792        double mv[16], prjm[16];
793        int viewport[4];
794        double wx, wy, wz;
795        double dx, dy, dz;
796
797        glGetDoublev(GL_MODELVIEW_MATRIX, mv);
798        glGetDoublev(GL_PROJECTION_MATRIX, prjm);
799        glGetIntegerv(GL_VIEWPORT, viewport);
800       
801        NanoVis::fonts->begin();
802        dx = x1 - x0;
803        dy = y1 - y0;
804        dz = z1 - z0;
805        if (gluProject((x0 + x1) * 0.5, y0, z0, mv, prjm, viewport,
806                       &wx, &wy, &wz)) {
807            char buff[20];
808            double min, max;
809
810            NanoVis::grid->xAxis.GetDataLimits(min, max);
811            glLoadIdentity();
812            glTranslatef((int)wx, viewport[3] - (int) wy, 0.0f);
813            const char *units;
814            units = NanoVis::grid->xAxis.GetUnits();
815            sprintf(buff, "%.*g %s", NUMDIGITS, max - min, units);
816            NanoVis::fonts->draw(buff);
817        }
818        if (gluProject(x0, (y0 + y1) * 0.5, z0, mv, prjm, viewport, &
819                       wx, &wy, &wz)) {
820            char buff[20];
821            double min, max;
822
823            NanoVis::grid->yAxis.GetDataLimits(min, max);
824            glLoadIdentity();
825            glTranslatef((int)wx, viewport[3] - (int) wy, 0.0f);
826            const char *units;
827            units = NanoVis::grid->yAxis.GetUnits();
828            sprintf(buff, "%.*g %s", NUMDIGITS, max - min, units);
829            NanoVis::fonts->draw(buff);
830        }
831        if (gluProject(x0, y0, (z0 + z1) * 0.5, mv, prjm, viewport,
832                       &wx, &wy, &wz)) {
833            glLoadIdentity();
834            glTranslatef((int)wx, viewport[3] - (int) wy, 0.0f);
835
836            double min, max;
837            NanoVis::grid->zAxis.GetDataLimits(min, max);
838            const char *units;
839            units = NanoVis::grid->zAxis.GetUnits();
840            char buff[20];
841            sprintf(buff, "%.*g %s", NUMDIGITS, max - min, units);
842            NanoVis::fonts->draw(buff);
843        }
844        NanoVis::fonts->end();
845    };
846#endif
847    glPopMatrix();
848    glDisable(GL_DEPTH_TEST);
849    glDisable(GL_BLEND);
850    glEnable(GL_TEXTURE_2D);
851}
852
853
854
855void VolumeRenderer::activate_volume_shader(Volume* vol, TransferFunction* tf, bool slice_mode)
856{
857  //vertex shader
858  _stdVertexShader->bind();
859
860  if (vol->volume_type == CUBIC)
861  {
862    //regular cubic volume
863    _regularVolumeShader->bind(tf->id, vol, slice_mode);
864  }
865  else if (vol->volume_type == ZINCBLENDE)
866  {
867    _zincBlendeShader->bind(tf->id, vol, slice_mode);
868  }
869}
870
871
872void VolumeRenderer::deactivate_volume_shader()
873{
874    _stdVertexShader->unbind();
875    _regularVolumeShader->unbind();
876    _zincBlendeShader->unbind();
877}
878
879
880void VolumeRenderer::get_near_far_z(Mat4x4 mv, double &zNear, double &zFar)
881{
882
883  double x0 = 0;
884  double y0 = 0;
885  double z0 = 0;
886  double x1 = 1;
887  double y1 = 1;
888  double z1 = 1;
889
890  double zMin, zMax;
891  zMin =  10000;
892  zMax = -10000;
893
894  double vertex[8][4];
895
896  vertex[0][0]=x0; vertex[0][1]=y0; vertex[0][2]=z0; vertex[0][3]=1.0;
897  vertex[1][0]=x1; vertex[1][1]=y0; vertex[1][2]=z0; vertex[1][3]=1.0;
898  vertex[2][0]=x0; vertex[2][1]=y1; vertex[2][2]=z0; vertex[2][3]=1.0;
899  vertex[3][0]=x0; vertex[3][1]=y0; vertex[3][2]=z1; vertex[3][3]=1.0;
900  vertex[4][0]=x1; vertex[4][1]=y1; vertex[4][2]=z0; vertex[4][3]=1.0;
901  vertex[5][0]=x1; vertex[5][1]=y0; vertex[5][2]=z1; vertex[5][3]=1.0;
902  vertex[6][0]=x0; vertex[6][1]=y1; vertex[6][2]=z1; vertex[6][3]=1.0;
903  vertex[7][0]=x1; vertex[7][1]=y1; vertex[7][2]=z1; vertex[7][3]=1.0;
904
905  for(int i=0;i<8;i++) {
906    Vector4 tmp = mv.transform(Vector4(vertex[i][0], vertex[i][1], vertex[i][2], vertex[i][3]));
907    tmp.perspective_devide();
908    vertex[i][2] = tmp.z;
909    if (vertex[i][2]<zMin) zMin = vertex[i][2];
910    if (vertex[i][2]>zMax) zMax = vertex[i][2];
911  }
912
913  zNear = zMax;
914  zFar = zMin;
915}
916
917void VolumeRenderer::set_slice_mode(bool val) { slice_mode = val; }
918void VolumeRenderer::set_volume_mode(bool val) { volume_mode = val; }
919void VolumeRenderer::switch_slice_mode() { slice_mode = (!slice_mode); }
920void VolumeRenderer::switch_volume_mode() { volume_mode = (!volume_mode); }
921
922void VolumeRenderer::enable_volume(int index){
923  volume[index]->enable();
924}
925
926void VolumeRenderer::disable_volume(int index){
927  volume[index]->disable();
928}
929
930
931bool
932VolumeRenderer::init_font(const char* filename)
933{
934    FILE *f;
935    unsigned short int bfType;
936    int bfOffBits;
937    short int biPlanes;
938    short int biBitCount;
939    int biSizeImage;
940    int width, height;
941    int i;
942    unsigned char temp;
943    unsigned char* data;
944    /* make sure the file is there and open it read-only (binary) */
945    f = fopen(filename, "rb");
946    if (f == NULL) {
947        fprintf(stderr, "can't open font file \"%s\"\n", filename);
948        return false;
949    }
950   
951    if (fread(&bfType, sizeof(short int), 1, f) != 1) {
952        fprintf(stderr, "can't read %d bytes from font file \"%s\"\n",
953                sizeof(short int), filename);
954        goto error;
955    }
956   
957    /* check if file is a bitmap */
958    if (bfType != 19778) {
959        fprintf(stderr, "not a bmp file.\n");
960        goto error;
961    }
962   
963    /* get the file size */
964    /* skip file size and reserved fields of bitmap file header */
965    fseek(f, 8, SEEK_CUR);
966   
967    /* get the position of the actual bitmap data */
968    if (fread(&bfOffBits, sizeof(int), 1, f) != 1) {
969        fprintf(stderr, "error reading file.\n");
970        goto error;
971    }
972    //printf("Data at Offset: %ld\n", bfOffBits);
973   
974    /* skip size of bitmap info header */
975    fseek(f, 4, SEEK_CUR);
976   
977    /* get the width of the bitmap */
978    if (fread(&width, sizeof(int), 1, f) != 1) {
979        fprintf(stderr, "error reading file.\n");
980        goto error;
981    }
982    //printf("Width of Bitmap: %d\n", texture->width);
983   
984    /* get the height of the bitmap */
985    if (fread(&height, sizeof(int), 1, f) != 1) {
986        fprintf(stderr, "error reading file.\n");
987        goto error;
988    }
989    //printf("Height of Bitmap: %d\n", texture->height);
990   
991    /* get the number of planes (must be set to 1) */
992    if (fread(&biPlanes, sizeof(short int), 1, f) != 1) {
993        fprintf(stderr, "error reading file.\n");
994        goto error;
995    }
996    if (biPlanes != 1) {
997        fprintf(stderr, "Error: number of Planes not 1!\n");
998        goto error;
999    }
1000   
1001    /* get the number of bits per pixel */
1002    if (fread(&biBitCount, sizeof(short int), 1, f) != 1) {
1003        fprintf(stderr, "error reading file.\n");
1004        goto error;
1005    }
1006   
1007    //printf("Bits per Pixel: %d\n", biBitCount);
1008    if (biBitCount != 24) {
1009        fprintf(stderr, "Bits per Pixel not 24\n");
1010        goto error;
1011    }
1012
1013
1014    /* calculate the size of the image in bytes */
1015    biSizeImage = width * height * 3 * sizeof(unsigned char);
1016    data = (unsigned char*) malloc(biSizeImage);
1017    if (data == NULL) {
1018        fprintf(stderr, "Can't allocate memory for image\n");
1019        goto error;
1020    }
1021
1022    /* seek to the actual data */
1023    fseek(f, bfOffBits, SEEK_SET);
1024    if (fread(data, biSizeImage, 1, f) != 1) {
1025        fprintf(stderr, "Error loading file!\n");
1026        goto error;
1027    }
1028    fclose(f);
1029
1030    /* swap red and blue (bgr -> rgb) */
1031    for (i = 0; i < biSizeImage; i += 3) {
1032       temp = data[i];
1033       data[i] = data[i + 2];
1034       data[i + 2] = temp;
1035    }
1036
1037    //insert alpha channel
1038    unsigned char* data_with_alpha;
1039    data_with_alpha = (unsigned char*)
1040        malloc(width*height*4*sizeof(unsigned char));
1041    for(int i=0; i<height; i++){
1042        for(int j=0; j<width; j++){
1043            unsigned char r, g, b, a;
1044            r = data[3*(i*width+j)];
1045            g = data[3*(i*width+j)+1];
1046            b = data[3*(i*width+j)+2];
1047           
1048            if(r==0 && g==0 && b==0)
1049                a = 0;
1050            else
1051                a = 255;
1052           
1053            data_with_alpha[4*(i*width+j)] = r;
1054            data_with_alpha[4*(i*width+j) + 1] = g;
1055            data_with_alpha[4*(i*width+j) + 2] = b;
1056            data_with_alpha[4*(i*width+j) + 3] = a;
1057           
1058        }
1059    }
1060    free(data);
1061   
1062    //create opengl texture
1063    glGenTextures(1, &font_texture);
1064    glBindTexture(GL_TEXTURE_2D, font_texture);
1065    //glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
1066    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data_with_alpha);
1067    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1068    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1069    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1070
1071    free(data_with_alpha);
1072
1073    build_font();
1074    return (glGetError()==0);
1075
1076 error:
1077    fclose(f);
1078    return false;
1079}
1080
1081
1082
1083void
1084VolumeRenderer::draw_label(Volume* vol)
1085{
1086
1087  //glEnable(GL_TEXTURE_2D);
1088  glDisable(GL_TEXTURE_2D);
1089  glEnable(GL_DEPTH_TEST);
1090
1091  //x
1092  glColor3f(0.5, 0.5, 0.5);
1093
1094  int length = vol->label[0].size();
1095  glPushMatrix();
1096 
1097    glTranslatef(.5*vol->aspect_ratio_width, vol->aspect_ratio_height, -0.1*vol->aspect_ratio_depth);
1098    glRotatef(180, 0, 0, 1);
1099    glRotatef(90, 1, 0, 0);
1100
1101    glScalef(0.0008, 0.0008, 0.0008);
1102    for(int i=0; i<length; i++){
1103      glutStrokeCharacter(GLUT_STROKE_ROMAN, vol->label[0].c_str()[i]);
1104      glTranslatef(0.04, 0., 0.);
1105    }
1106  glPopMatrix();
1107
1108  //y
1109  length = vol->label[1].size();
1110  glPushMatrix();
1111    glTranslatef(vol->aspect_ratio_width, 0.5*vol->aspect_ratio_height, -0.1*vol->aspect_ratio_depth);
1112    glRotatef(90, 0, 1, 0);
1113    glRotatef(90, 0, 0, 1);
1114
1115    glScalef(0.0008, 0.0008, 0.0008);
1116    for(int i=0; i<length; i++){
1117      glutStrokeCharacter(GLUT_STROKE_ROMAN, vol->label[1].c_str()[i]);
1118      glTranslatef(0.04, 0., 0.);
1119    }
1120  glPopMatrix();
1121
1122
1123  //z
1124  length = vol->label[2].size();
1125  glPushMatrix();
1126    glTranslatef(0., 1.*vol->aspect_ratio_height, 0.5*vol->aspect_ratio_depth);
1127    glRotatef(90, 0, 1, 0);
1128
1129    glScalef(0.0008, 0.0008, 0.0008);
1130    for(int i=0; i<length; i++){
1131      glutStrokeCharacter(GLUT_STROKE_ROMAN, vol->label[2].c_str()[i]);
1132      glTranslatef(0.04, 0., 0.);
1133    }
1134  glPopMatrix();
1135
1136  glDisable(GL_TEXTURE_2D);
1137}
1138
1139
1140
1141void VolumeRenderer::build_font() {
1142
1143    GLfloat cx, cy;         /* the character coordinates in our texture */
1144    font_base = glGenLists(256);
1145    glBindTexture(GL_TEXTURE_2D, font_texture);
1146    for (int loop = 0; loop < 256; loop++)
1147    {
1148        cx = (float) (loop % 16) / 16.0f;
1149        cy = (float) (loop / 16) / 16.0f;
1150        glNewList(font_base + loop, GL_COMPILE);
1151            glBegin(GL_QUADS);
1152                glTexCoord2f(cx, 1 - cy - 0.0625f);
1153                glVertex3f(0, 0, 0);
1154                glTexCoord2f(cx + 0.0625f, 1 - cy - 0.0625f);
1155                glVertex3f(0.04, 0, 0);
1156                glTexCoord2f(cx + 0.0625f, 1 - cy);
1157                glVertex3f(0.04, 0.04, 0);
1158                glTexCoord2f(cx, 1 - cy);
1159                glVertex3f(0, 0.04, 0);
1160            glEnd();
1161            glTranslated(0.04, 0, 0);
1162        glEndList();
1163    }
1164}
1165
1166
1167   
1168void VolumeRenderer::glPrint(char* string, int set){
1169
1170    if(set>1) set=1;
1171
1172    glBindTexture(GL_TEXTURE_2D, font_texture);
1173
1174    glListBase(font_base - 32 + (128 * set));
1175    glCallLists(strlen(string), GL_BYTE, string);
1176
1177}
1178
Note: See TracBrowser for help on using the repository browser.