Prev Up Next

Step two : invert an existing volume


invert-vol.cc

The goal is to make a simple program that inverts a volume : each transparent voxel in the original volume will be colored and each colored voxel will become transparent.
The program will be designed to be a filter (like grep), so it must read the source volume from standard input (stdin) and write the result to standard output (stdout). Of course, if the user supplies an argument, we will use this file instead of stdin. (And if he supplies a second argument, we will use it as the output file name).
We will have to load the file, check that this operation succeeded, invert the volume and write it.


#include <vol.h>
#include <stdio.h>

int main( int argc, char **argv ) {

    char *source_file = "";
    char *dest_file = "";
  • We use empty strings as default values for file names. Why ? because, for the vol library, empty string are understood as stdin and stdout when you want to read or write a vol file.

    if (argc > 1) {  
        source_file = argv[1];
        if (argc > 2)
            dest_file = argv[2];
    }

  • If argv[1] is present, take it as the filename of the source file. If argv[2] is present, take it as the filename of the destination file.

    Vol v( source_file );
  • This is how you can load a .vol file into a Vol object ! If source_file is an empty string (warning : an empty string is NOT a NULL pointer), then stdin will be used.

    if (!v.isOK()) {
        fprintf( stderr, "Couldn't load \"%s\" file !\n", source_file );
        return 1;
    }
  • The public member function isOK() returns a boolean that tells you if the global state of the object is good.
  • You have to check that isOK() is true after loading a .vol file, because this operation can fail for many reasons (the file doesn't exist, or it is not a .vol file).

   voxel alpha_color = v.alpha();
  • The public member function alpha() returns the voxel value used for transparent voxels in this Vol object.

    for (int i = v.minX(); i < v.maxX(); ++i) {        
        for (int j = v.minY(); j < v.maxY(); ++j) {
            for (int k = v.minZ(); k < v.maxZ(); ++k) {
        
                if (v(i, j, k) == alpha_color)
                    v(i, j, k) = 50;
                else    
                    v(i, j, k) = alpha_color;
        
            }       
        }       
    }
  • This loop inverts the volume.

    v.dumpVol( dest_file );

    return 0;
        
}
  • We dump the volume into the destination file.
  • You can notice that when you load a vol from a file, the modifications on the Vol object DO NOT affect the file. You can rewrite it if you want, or write the result in a new file as we did in this example.

Here is the result you should have :
Before
After
Original file Hey ! It worked !

Files

makefile
invert-vol.cc
example.vol

Valid HTML 4.0! Edited with vim