Example #1
0
int main(int argc, const char **argv)
{
	util_logging_init(argv[0]);
	path_init();

	/* device types */
	string devicelist = "";
	string devicename = "cpu";
	bool list = false, debug = false;
	int threads = 0, verbosity = 1;

	vector<DeviceType>& types = Device::available_types();

	foreach(DeviceType type, types) {
		if(devicelist != "")
			devicelist += ", ";

		devicelist += Device::string_from_type(type);
	}

	/* parse options */
	ArgParse ap;

	ap.options ("Usage: cycles_server [options]",
		"--device %s", &devicename, ("Devices to use: " + devicelist).c_str(),
		"--list-devices", &list, "List information about all available devices",
		"--threads %d", &threads, "Number of threads to use for CPU device",
#ifdef WITH_CYCLES_LOGGING
		"--debug", &debug, "Enable debug logging",
		"--verbose %d", &verbosity, "Set verbosity of the logger",
#endif
		NULL);

	if(ap.parse(argc, argv) < 0) {
		fprintf(stderr, "%s\n", ap.geterror().c_str());
		ap.usage();
		exit(EXIT_FAILURE);
	}

	if(debug) {
		util_logging_start();
		util_logging_verbosity_set(verbosity);
	}

	if(list) {
		vector<DeviceInfo>& devices = Device::available_devices();

		printf("Devices:\n");

		foreach(DeviceInfo& info, devices) {
			printf("    %s%s\n",
				info.description.c_str(),
				(info.display_device)? " (display)": "");
		}

		exit(EXIT_SUCCESS);
	}
Example #2
0
static void
getargs (int argc, const char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("Usage:  testtex [options] inputfile",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-o %s", &output_filename, "Output test image",
                  "-d %s", &dataformatname, "Set the output data format to one of:"
                        "uint8, sint8, uint10, uint12, uint16, sint16, half, float, double",
                  "-res %d %d", &output_xres, &output_yres,
                      "Resolution of output test image",
                  "-iters %d", &iters,
                      "Iterations for time trials",
                  "--blur %f", &blur, "Add blur to texture lookup",
                  "--width %f", &width, "Multiply filter width of texture lookup",
                  "--fill %f", &fill, "Set fill value for missing channels",
                  "--wrap %s", &wrapmodes, "Set wrap mode (default, black, clamp, periodic, mirror, overscan)",
                  "--missing %f %f %f", &missing[0], &missing[1], &missing[2],
                        "Specify missing texture color",
                  "--autotile %d", &autotile, "Set auto-tile size for the image cache",
                  "--automip", &automip, "Set auto-MIPmap for the image cache",
                  "--blocksize %d", &blocksize, "Set blocksize (n x n) for batches",
                  "--handle", &use_handle, "Use texture handle rather than name lookup",
                  "--searchpath %s", &searchpath, "Search path for files",
                  "--nowarp", &nowarp, "Do not warp the image->texture mapping",
                  "--tube", &tube, "Make a tube projection",
                  "--cachesize %f", &cachesize, "Set cache size, in MB",
                  "--scale %f", &scalefactor, "Scale intensities",
                  "--maxfiles %d", &maxfiles, "Set maximum open files",
                  "--nountiled", &nountiled, "Reject untiled images",
                  "--nounmipped", &nounmipped, "Reject unmipped images",
                  "--ctr", &test_construction, "Test TextureOpt construction time",
                  "--gettexels", &test_gettexels, "Test TextureSystem::get_texels",
                  "--getimagespec", &test_getimagespec, "Test TextureSystem::get_imagespec",
                  "--offset %f %f %f", &offset[0], &offset[1], &offset[2], "Offset texture coordinates",
                  "--scalest %f %f", &sscale, &tscale, "Scale texture lookups (s, t)",
                  "--graytorgb", &gray_to_rgb, "Convert gratscale textures to RGB",
                  "--resetstats", &resetstats, "Print and reset statistics on each iteration",
                  NULL);
    if (ap.parse (argc, argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (filenames.size() < 1) {
        std::cerr << "testtex: Must have at least one input file\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
}
Example #3
0
static void
getargs(int argc, char* argv[])
{
    bool help = false;
    ArgParse ap;
    // clang-format off
    ap.options(
        "fmath_test\n" OIIO_INTRO_STRING "\n"
        "Usage:  fmath_test [options]",
        // "%*", parse_files, "",
        "--help", &help, "Print help message",
        "-v", &verbose, "Verbose mode",
        // "--threads %d", &numthreads,
        //     ustring::sprintf("Number of threads (default: %d)", numthreads).c_str(),
        "--iterations %d", &iterations,
            ustring::sprintf("Number of values to convert for benchmarks (default: %d)", iterations).c_str(),
        "--trials %d", &ntrials, "Number of trials",
        nullptr);
    // clang-format on
    if (ap.parse(argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage();
        exit(EXIT_FAILURE);
    }
    if (help) {
        ap.usage();
        exit(EXIT_FAILURE);
    }
}
Example #4
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("hash_test\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  hash_test [options]",
                // "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose mode",
                "--iters %d", &iterations,
                    Strutil::format("Number of iterations (default: %d)", iterations).c_str(),
                "--trials %d", &ntrials, "Number of trials",
                NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}
Example #5
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("compute_test\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  compute_test [options]",
                // "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose mode",
                "--threads %d", &numthreads,
                    ustring::format("Number of threads (default: %d)", numthreads).c_str(),
                "--iterations %d", &iterations,
                    ustring::format("Number of iterations (default: %d)", iterations).c_str(),
                "--trials %d", &ntrials, "Number of trials",
                "--allgpus", &allgpus, "Run OpenCL tests on all devices, not just default",
                "--wedge", &wedge, "Do a wedge test",
                NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}
Example #6
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("spin_rw_test\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  spin_rw_test [options]",
                // "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose mode",
                "--threads %d", &numthreads, 
                    ustring::format("Number of threads (default: %d)", numthreads).c_str(),
                "--iters %d", &iterations,
                    ustring::format("Number of iterations (default: %d)", iterations).c_str(),
                "--trials %d", &ntrials, "Number of trials",
                "--rwratio %d", &read_write_ratio, 
                    ustring::format("Reader::writer ratio (default: %d)", read_write_ratio).c_str(),
                "--wedge", &wedge, "Do a wedge test",
                NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}
Example #7
0
static void
getargs (int argc, const char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("Usage:  testtex [options] inputfile",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-o %s", &output_filename, "Output test image",
                  "-res %d %d", &output_xres, &output_yres,
                      "Resolution of output test image",
                  "-iters %d", &iters,
                      "Iterations for time trials",
                  "--blur %f", &blur, "Add blur to texture lookup",
                  "--width %f", &width, "Multiply filter width of texture lookup",
                  "--missing %f %f %f", &missing[0], &missing[1], &missing[2],
                        "Specify missing texture color",
                  "--autotile %d", &autotile, "Set auto-tile size for the image cache",
                  "--automip", &automip, "Set auto-MIPmap for the image cache",
                  "--blocksize %d", &blocksize, "Set blocksize (n x n) for batches",
                  "--handle", &use_handle, "Use texture handle rather than name lookup",
                  "--searchpath %s", &searchpath, "Search path for files",
                  "--nowarp", &nowarp, "Do not warp the image->texture mapping",
                  "--cachesize %f", &cachesize, "Set cache size, in MB",
                  "--scale %f", &scalefactor, "Scale intensities",
                  "--maxfiles %d", &maxfiles, "Set maximum open files",
                  "--nountiled", &nountiled, "Reject untiled images",
                  "--nounmipped", &nounmipped, "Reject unmipped images",
                  "--ctr", &test_construction, "Test TextureOpt construction time",
                  "--offset %f %f %f", &offset[0], &offset[1], &offset[2], "Offset texture coordinates",
                  "--scalest %f", &scalest, "Scale st coordinates",
                  NULL);
    if (ap.parse (argc, argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (filenames.size() < 1) {
        std::cerr << "testtex: Must have at least one input file\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
}
static void
getargs (int argc, const char *argv[])
{
    static bool help = false;
    ArgParse ap;
    ap.options ("Usage:  testshade [options] shader...",
                "%*", add_shader, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose messages",
                "--debug", &debug, "Lots of debugging info",
                "--stats", &stats, "Print run statistics",
                "-g %d %d", &xres, &yres, "Make an X x Y grid of shading points",
                "-o %L %L", &outputvars, &outputfiles,
                        "Output (variable, filename)",
                "-od %s", &dataformatname, "Set the output data format to one of:\n"
                        "\t\t\t\tuint8, half, float",
                "--layer %s", &layername, "Set next layer name",
                "--fparam %L %L",
                        &fparams, &fparams,
                        "Add a float param (args: name value)",
                "--iparam %L %L",
                        &iparams, &iparams,
                        "Add an integer param (args: name value)",
                "--vparam %L %L %L %L",
                        &vparams, &vparams, &vparams, &vparams,
                        "Add a vector or color param (args: name x y z)",
                "--sparam %L %L",
                        &sparams, &sparams,
                        "Add a string param (args: name value)",
                "--connect %L %L %L %L",
                    &connections, &connections, &connections, &connections,
                    "Connect fromlayer fromoutput tolayer toinput",
                "--raytype %s", &raytype, "Set the raytype",
                "--iters %d", &iters, "Number of iterations",
                "-O0", &O0, "Do no runtime shader optimization",
                "-O1", &O1, "Do a little runtime shader optimization",
                "-O2", &O2, "Do lots of runtime shader optimization",
//                "-v", &verbose, "Verbose output",
                NULL);
    if (ap.parse(argc, argv) < 0 || shadernames.empty()) {
        std::cerr << ap.error_message() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        std::cout <<
            "testshade -- Test Open Shading Language\n"
            "(c) Copyright 2009-2010 Sony Pictures Imageworks Inc. All Rights Reserved.\n";
        ap.usage ();
        exit (EXIT_SUCCESS);
    }
}
Example #9
0
static void
getargs(int argc, char* argv[])
{
    // clang-format off
    bool help = false;
    ArgParse ap;
    ap.options ("idiff -- compare two images\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  idiff [options] image1 image2",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-q", &quiet, "Quiet (minimal messages)",
                  "-a", &compareall, "Compare all subimages/miplevels",
                  "<SEPARATOR>", "Thresholding and comparison options",
                  "-fail %g", &failthresh, "Failure threshold difference (0.000001)",
                  "-failpercent %g", &failpercent, "Allow this percentage of failures (0)",
                  "-hardfail %g", &hardfail, "Fail if any one pixel exceeds this error (infinity)",
                  "-warn %g", &warnthresh, "Warning threshold difference (0.00001)",
                  "-warnpercent %g", &warnpercent, "Allow this percentage of warnings (0)",
                  "-hardwarn %g", &hardwarn, "Warn if any one pixel exceeds this error (infinity)",
                  "-p", &perceptual, "Perform perceptual (rather than numeric) comparison",
                  "<SEPARATOR>", "Difference image options",
                  "-o %s", &diffimage, "Output difference image",
                  "-od", &outdiffonly, "Output image only if nonzero difference",
                  "-abs", &diffabs, "Output image of absolute value, not signed difference",
                  "-scale %g", &diffscale, "Scale the output image by this factor",
//                  "-meta", &comparemeta, "Compare metadata",
                  NULL);
    if (ap.parse(argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (filenames.size() != 2) {
        std::cerr << "idiff: Must have two input filenames.\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
    // clang-format on
}
Example #10
0
int
main(int argc, const char* argv[])
{
    Filesystem::convert_native_arguments(argc, argv);
    ArgParse ap;
    // clang-format off
    ap.options ("igrep -- search images for matching metadata\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  igrep [options] pattern filename...",
                "%*", parse_files, "",
                "-i", &ignore_case, "Ignore upper/lower case distinctions",
                "-v", &invert_match, "Invert match (select non-matching files)",
                "-E", &extended_regex, "Pattern is an extended regular expression",
                "-f", &file_match, "Match against file name as well as metadata",
                "-l", &list_files, "List the matching files (no detail)",
                "-r", &recursive, "Recurse into directories",
                "-d", &print_dirs, "Print directories (when recursive)",
                "-a", &all_subimages, "Search all subimages of each file",
                "--help", &help, "Print help message",
                NULL);
    // clang-format off
    if (ap.parse(argc, argv) < 0 || pattern.empty() || filenames.empty()) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        return EXIT_FAILURE;
    }
    if (help) {
        ap.usage();
        exit(EXIT_FAILURE);
    }

#if USE_BOOST_REGEX
    boost::regex_constants::syntax_option_type flag
        = boost::regex_constants::grep;
    if (extended_regex)
        flag = boost::regex::extended;
    if (ignore_case)
        flag |= boost::regex_constants::icase;
#else
    auto flag = std::regex_constants::grep;
    if (extended_regex)
        flag = std::regex_constants::extended;
    if (ignore_case)
        flag |= std::regex_constants::icase;
#endif
    regex re(pattern, flag);
    for (auto&& s : filenames)
        grep_file(s, re);

    return 0;
}
Example #11
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("timer_test\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  timer_test [options]",
                "%*", parse_files, "",
                "--help", &help, "Print help message",
                NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}
Example #12
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("iv -- image viewer\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  iv [options] [filename...]",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-F", &foreground_mode, "Foreground mode",
                  NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}
Example #13
0
int main( int argc, const char** argv )
{

#ifdef	AQSIS_SYSTEM_WIN32
	char acPath[256];
	char rootPath[256];
	if( GetModuleFileName( NULL, acPath, 256 ) != 0)
	{
		// guaranteed file name of at least one character after path
		*( strrchr( acPath, '\\' ) + 1 ) = '\0';
		std::string	 stracPath(acPath);
		stracPath.append("..\\");
		_fullpath(rootPath,&stracPath[0],256);
	}
	g_shader_path = rootPath;
	g_shader_path.append( "shaders" );
#elif defined(AQSIS_SYSTEM_MACOSX)
#else

	g_shader_path = AQSIS_XSTR(DEFAULT_SHADER_PATH);
#endif

	/*Aqsis::QGetRenderContextI();*/
	ArgParse ap;
	ap.usageHeader( ArgParse::apstring( "Usage: " ) + argv[ 0 ] + " <shadername>" );
	ap.argFlag( "help", "\aPrint this help and exit", &g_cl_help );
	ap.alias( "help" , "h" );
	ap.argFlag( "version", "\aPrint version information and exit", &g_cl_version );
	ap.argString( "shaders", "=string\aOverride the default shader searchpath(s) [" + g_shader_path + "]", &g_cl_shader_path );

	if ( argc > 1 && !ap.parse( argc - 1, argv + 1 ) )
	{
		Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
		exit( 1 );
	}

	if ( g_cl_help )
	{
		std::cout << ap.usagemsg();
		exit( 0 );
	}

	if ( g_cl_version )
	{
		std::cout << "aqsltell version " << AQSIS_VERSION_STR_FULL << std::endl << "compiled " << __DATE__ << " " << __TIME__ << std::endl;
		exit( 0 );
	}

	// Apply environment-variable overrides to default paths ...
	if(getenv("AQSIS_SHADER_PATH"))
		g_shader_path = getenv("AQSIS_SHADER_PATH");

	// Apply command-line overrides to default paths ...
	if(!g_cl_shader_path.empty())
		g_shader_path = g_cl_shader_path;

	// Any leftovers are presumed to be shader names.
	if ( ap.leftovers().size() == 0 )     // If no files specified, take input from stdin.
	{
		Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
		exit( 1 );
	}
	else
	{
		for ( ArgParse::apstringvec::const_iterator e = ap.leftovers().begin(); e != ap.leftovers().end(); e++ )
		{
			SLX_SetPath( const_cast<char*>( g_shader_path.c_str() ) );
			SLX_SetDSOPath( const_cast<char*>( g_shader_path.c_str() ) );
			Slo_SetShader( ( char* ) e->c_str() );

			if ( SLX_SetShader( ( char* ) e->c_str() ) == 0 )
			{
				// SLX_SetShader successful
				int	nArgs;
				int i;
				SLX_VISSYMDEF * symPtr;

				std::cout << SLX_TypetoStr( SLX_GetType() ) << " \"" << Slo_GetName() << "\"" << std::endl;
				nArgs = SLX_GetNArgs();

				for ( i = 0; i < nArgs; i++ )
				{
					symPtr = SLX_GetArgById( i );
					if ( symPtr != NULL )
					{
						TqInt arrayLen = 1;
						if ( symPtr->svd_arraylen != 0 )
							arrayLen = symPtr->svd_arraylen;

						std::cout << "    \"" << symPtr->svd_name << "\" \"parameter " <<
						SLX_DetailtoStr( symPtr->svd_detail ) << " " <<
						SLX_TypetoStr( symPtr->svd_type );

						if ( symPtr->svd_arraylen != 0 )
							std::cout << "[" << arrayLen << "]";

						std::cout << "\"" << std::endl;

						TqInt arrayIndex;
						for ( arrayIndex = 0; arrayIndex < arrayLen; arrayIndex++ )
						{
							std::cout << "\t\tDefault value: ";

							if ( symPtr->svd_spacename != NULL )
							{
								if ( ( symPtr->svd_type == SLX_TYPE_POINT ) ||
								        ( symPtr->svd_type == SLX_TYPE_NORMAL ) ||
								        ( symPtr->svd_type == SLX_TYPE_VECTOR ) ||
								        ( symPtr->svd_type == SLX_TYPE_MATRIX ) ||
								        ( symPtr->svd_type == SLX_TYPE_COLOR ) )
									std::cout << "\"" << symPtr->svd_spacename << "\" ";
							}

							if ( symPtr->svd_default.stringval != NULL )
							{
								switch ( symPtr->svd_type )
								{
										case SLX_TYPE_UNKNOWN:
										std::cout << "unknown" << std::endl;
										break;
										case SLX_TYPE_POINT:
										case SLX_TYPE_NORMAL:
										case SLX_TYPE_VECTOR:
										std::cout << "[" << symPtr->svd_default.pointval[ arrayIndex ].xval << " " <<
										symPtr->svd_default.pointval[ arrayIndex ].yval << " " <<
										symPtr->svd_default.pointval[ arrayIndex ].zval <<
										"]" << std::endl;
										break;
										case SLX_TYPE_COLOR:
										std::cout << "[" << symPtr->svd_default.pointval[ arrayIndex ].xval << " " <<
										symPtr->svd_default.pointval[ arrayIndex ].yval << " " <<
										symPtr->svd_default.pointval[ arrayIndex ].zval <<
										"]" << std::endl;
										break;
										case SLX_TYPE_SCALAR:
										std::cout << symPtr->svd_default.scalarval[ arrayIndex ] << std::endl;
										break;
										case SLX_TYPE_STRING:
										std::cout << "\"" << symPtr->svd_default.stringval[ arrayIndex ] << "\"" << std::endl;
										break;
										case SLX_TYPE_MATRIX:
										std::cout << "[" <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[0][0] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[0][1] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[0][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[0][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[1][0] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[1][1] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[1][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[1][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[2][0] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[2][1] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[2][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[2][3] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[3][0] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[3][1] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[3][2] << " " <<
										symPtr->svd_default.matrixval[ arrayIndex ].val[3][3] <<
										"]" << std::endl;
										break;
										default:
										std::cout << "unknown" << std::endl;
										break;
								}
							}
						}
					}
					else
					{
						printf( "ERROR - null pointer to value\n" );
					}
					//std::cout << std::endl;
				}

				SLX_EndShader();
			}
			else
			{
				printf("ERROR - could not read shader file\n");
			}
		}
	}

	return ( 0 );
}
Example #14
0
int main (int argc, const char* argv[])
{
    bool generate = false;
    bool extract = false;
    int cubesize = 32;
    int maxwidth = 2048;
    std::string inputfile;
    std::string outputfile;
    std::string config;
    std::string incolorspace;
    std::string outcolorspace;
    
    // TODO: Add optional allocation transform instead of colorconvert
    ArgParse ap;
    ap.options("ociolutimage -- Convert a 3dlut to or from an image\n\n"
               "usage:  ociolutimage [options] <OUTPUTFILE.LUT>\n\n"
               "example:  ociolutimage --generate --output lut.exr\n"
               "example:  ociolutimage --extract --input lut.exr --output output.spi3d\n",
               "<SEPARATOR>", "",
               "--generate", &generate, "Generate a lattice image",
               "--extract", &extract, "Extract a 3dlut from an input image",
               "<SEPARATOR>", "",
               "--cubesize %d", &cubesize, "Size of the cube (default: 32)",
               "--maxwidth %d", &maxwidth, "Specify maximum width of the image (default: 2048)",
               "--input %s", &inputfile, "Specify the input filename",
               "--output %s", &outputfile, "Specify the output filename",
               "<SEPARATOR>", "",
               "--config %s", &config, ".ocio configuration file (default: $OCIO)",
               "--colorconvert %s %s", &incolorspace, &outcolorspace, "Apply a color space conversion to the image.",
               NULL);
    
    if (ap.parse(argc, argv) < 0)
    {
        std::cout << ap.geterror() << std::endl;
        ap.usage();
        std::cout << "\n";
        return 1;
    }
    
    if (argc == 1 )
    {
        ap.usage();
        std::cout << "\n";
        return 1;
    }
    
    if(generate)
    {
        try
        {
            Generate(cubesize, maxwidth,
                     outputfile,
                     config, incolorspace, outcolorspace);
        }
        catch(std::exception & e)
        {
            std::cerr << "Error generating image: " << e.what() << std::endl;
            exit(1);
        }
        catch(...)
        {
            std::cerr << "Error generating image. An unknown error occurred.\n";
            exit(1);
        }
    }
    else if(extract)
    {
        try
        {
            Extract(cubesize, maxwidth,
                    inputfile, outputfile);
        }
        catch(std::exception & e)
        {
            std::cerr << "Error extracting lut: " << e.what() << std::endl;
            exit(1);
        }
        catch(...)
        {
            std::cerr << "Error extracting lut. An unknown error occurred.\n";
            exit(1);
        }
    }
    else
    {
        std::cerr << "Must specify either --generate or --extract.\n";
        exit(1);
    }
    
    return 0;
}
Example #15
0
int main( int argc, const char** argv )
{
	ArgParse ap;
	RtFilterFunc filterfunc;
	float bake;

	ap.usageHeader( ArgParse::apstring( "Usage: " ) + argv[ 0 ] + " [options] infile outfile" );
	ap.argFlag( "help", "\aPrint this help and exit", &g_help );
	ap.alias( "help" , "h" );
	ap.argFlag( "version", "\aPrint version information and exit", &g_version );
	ap.argInt( "verbose", "=integer\aSet log output level\n"
		"\a0 = errors\n"
		"\a1 = warnings (default)\n"
		"\a2 = information\n"
		"\a3 = debug", &g_cl_verbose );
	ap.alias( "verbose" , "v" );
	ap.argString( "compression", "=string\a[none|lzw|packbits|deflate] (default: %default)", &g_compress );
	ap.argFlag( "envcube", " px nx py ny pz nz\aproduce a cubeface environment map from 6 images.", &g_envcube );
	ap.argFlag( "envlatl", "\aproduce a latlong environment map from an image file.", &g_envlatl );
	ap.argFlag( "shadow", "\aproduce a shadow map from a z file.", &g_shadow );
	ap.argString( "swrap", "=string\as wrap [black|periodic|clamp] (default: %default)", &g_swrap );
	ap.argString( "smode", "=string\a(equivalent to swrap for BMRT compatibility)", &g_swrap );
	ap.argString( "twrap", "=string\at wrap [black|periodic|clamp] (default: %default)", &g_twrap );
	ap.argString( "tmode", "=string\a(equivalent to twrap for BMRT compatibility)", &g_swrap );
	ap.argString( "wrap", "=string\awrap s&t [black|periodic|clamp]", &g_wrap );
	ap.argString( "mode", "=string\as (equivalent to wrap for BMRT compatibility)", &g_wrap );
	ap.argString( "filter", "=string\a[box|bessel|catmull-rom|disk|gaussian|sinc|triangle|mitchell] (default: %default)", &g_filter );
	ap.argFloat( "fov(envcube)", "=float\a[>=0.0f] (default: %default)", &g_fov );
	ap.argFloat( "swidth", "=float\as width [>0.0f] (default: %default)", &g_swidth );
	ap.alias( "swidth", "sfilterwidth" );
	ap.argFloat( "twidth", "=float\at width [>0.0f] (default: %default)", &g_twidth );
	ap.alias( "twidth", "tfilterwidth" );
	ap.argFloat( "width", "=float\awidth [>0.0f] set both swidth and twidth (default: %default)", &g_width );
	ap.alias( "width", "filterwidth" );
	ap.argFloat( "quality", "=float\a[>=1.0f && <= 100.0f] (default: %default)", &g_quality );
	ap.argFloat( "bake", "=float\a[>=2.0f && <= 2048.0f] (default: %default)", &g_bake );
	ap.argString( "resize", "=string\a[up|down|round|up-|down-|round-] (default: %default)\n\aNot used, for BMRT compatibility only!", &g_resize );


	if ( argc > 1 && !ap.parse( argc - 1, argv + 1 ) )
	{
		Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
		exit( 1 );
	}

	if ( g_version )
	{
		version( std::cout );
		exit( 0 );
	}

	if ( g_help || ap.leftovers().size() <= 1 )
	{
		std::cout << ap.usagemsg();
		exit( 0 );
	}

	if ( g_envcube && g_shadow )
	{
		std::cout << "Specify only one of envcube or shadow" << std::endl;
		exit( 1 );
	}


	/* find the pixel's filter function */
	filterfunc = RiBoxFilter;
	if ( g_filter == "box" )
		filterfunc = RiBoxFilter;
	else if ( g_filter == "mitchell" )
		filterfunc = RiMitchellFilter;
	else if ( g_filter == "sinc" )
		filterfunc = RiSincFilter;
	else if ( g_filter == "catmull-rom" )
		filterfunc = RiCatmullRomFilter;
	else if ( g_filter == "disk" )
		filterfunc = RiDiskFilter;
	else if ( g_filter == "bessel" )
		filterfunc = RiBesselFilter;
	else if ( g_filter == "triangle" )
		filterfunc = RiTriangleFilter;
	else if ( g_filter == "gaussian" )
		filterfunc = RiGaussianFilter;



	/* protect the s,t width */
	if ( g_swidth < 1.0 )
	{
		Aqsis::log() << "g_swidth is smaller than 1.0." << " 1.0 will be used instead." << std::endl;
		g_swidth = 1.0;
	}
	if ( g_twidth < 1.0 )
	{
		Aqsis::log() << "g_twidth is smaller than 1.0." << " 1.0 will be used instead." << std::endl;
		g_twidth = 1.0;
	}

	/* protect the s,t wrap mode */
	if ( !( ( g_swrap == "black" ) || ( g_swrap == "periodic" ) || ( g_swrap == "clamp" ) ) )
	{
		Aqsis::log() << "Unknown s wrap mode: " << g_swrap << ". black will be used instead." << std::endl;
		g_swrap = "black";
	}
	if ( !( ( g_twrap == "black" ) || ( g_twrap == "periodic" ) || ( g_twrap == "clamp" ) ) )
	{
		Aqsis::log() << "Unknown t wrap mode: " << g_twrap << ". black will be used instead." << std::endl;
		g_twrap = "black";
	}
	if ( !( ( g_wrap == "" ) || ( g_wrap == "black" ) || ( g_wrap == "periodic" ) || ( g_wrap == "clamp" ) ) )
	{
		Aqsis::log() << "Unknown wrap mode: " << g_wrap << ". black will be used instead." << std::endl;
		g_wrap = "black";
	}

	/* If wrap is specified, it overrides both s and t */
	if( g_wrap != "" )
	{
		g_twrap = g_wrap;
		g_swrap = g_wrap;
	}

	/* Need to set both st width ? */
	if ( g_width > 0.0 )
	{
		g_twidth = g_swidth = g_width;
	}

	/* protect the compression mode */
	if ( !( ( g_compress == "deflate" ) ||
	        ( g_compress == "lzw" ) ||
	        ( g_compress == "none" ) ||
	        ( g_compress == "packbits" )
	      )
	   )
	{
		Aqsis::log() << "Unknown compression mode: " << g_compress << ". none." << std::endl;
		g_compress = "none";
	}

	/* protect the quality mode */
	if ( g_quality < 1.0f )
		g_quality = 1.0;
	if ( g_quality > 100.0f )
		g_quality = 100.0;

	/* protect the bake mode */
	if ( g_bake < 2.0f )
		g_bake = 2.0;
	if ( g_bake > 2048.0f )
		g_bake = 2048.0;

	char *compression = ( char * ) g_compress.c_str();
	float quality = ( float ) g_quality;


	std::auto_ptr<std::streambuf> show_level( new Aqsis::show_level_buf(Aqsis::log()) );
	Aqsis::log_level_t level = Aqsis::ERROR;
	if( g_cl_verbose > 0 )
		level = Aqsis::WARNING;
	if( g_cl_verbose > 1 )
		level = Aqsis::INFO;
	if( g_cl_verbose > 2 )
		level = Aqsis::DEBUG;
	std::auto_ptr<std::streambuf> filter_level( new Aqsis::filter_by_level_buf(level, Aqsis::log()) );

	RiBegin(RI_NULL);

	if ( g_envcube )
	{
		if ( ap.leftovers().size() != 7 )
		{
			Aqsis::log() << "Need 6 images for cubic environment map" << std::endl;
			return ( -1 );
		}

		printf( "CubeFace Environment %s %s %s %s %s %s ----> %s \n\t\"fov\"= %4.1f\n\t\"filter\"= %s \n\t\"swidth\"= %4.1f\n\t\"twidth\"= %4.1f\n\t\"compression\" = %s\n",
		        const_cast<char*>(ap.leftovers() [ 0 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 1 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 2 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 3 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 4 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 5 ].c_str()),
		        const_cast<char*>(ap.leftovers() [ 6 ].c_str()),
		        g_fov,
		        g_filter.c_str(),
		        g_swidth,
		        g_twidth,
		        ( char* ) g_compress.c_str()
		      );

		RiMakeCubeFaceEnvironment(
		    const_cast<char*>(ap.leftovers() [ 0 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 1 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 2 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 3 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 4 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 5 ].c_str()),
		    const_cast<char*>(ap.leftovers() [ 6 ].c_str()),
		    g_fov,
		    filterfunc,
		    ( float ) g_swidth,
		    ( float ) g_twidth,
		    "compression",
		    &compression,
		    "quality",
		    &quality,
		    RI_NULL );
	}
	else if ( g_shadow )
	{
		printf( "Shadow %s ----> %s \n\t\"compression\" = %s\n",
		        ( char* ) ap.leftovers() [ 0 ].c_str(),
		        ( char* ) ap.leftovers() [ 1 ].c_str(),
		        ( char* ) g_compress.c_str() );



		RiMakeShadow( ( char* ) ap.leftovers() [ 0 ].c_str(), ( char* ) ap.leftovers() [ 1 ].c_str(), ( float ) g_twidth, "compression", &compression, "quality", &quality, RI_NULL );
	}
	else if ( g_envlatl )
	{
		printf( "LatLong Environment %s ----> %s \n\t\"compression\" = %s \n",
		        ( char* ) ap.leftovers() [ 0 ].c_str(),
		        ( char* ) ap.leftovers() [ 1 ].c_str(),
		        ( char* ) g_compress.c_str() );

		RiMakeLatLongEnvironment( ( char* ) ap.leftovers() [ 0 ].c_str(), ( char* ) ap.leftovers() [ 1 ].c_str(), filterfunc,
		                          ( float ) g_swidth, ( float ) g_twidth, "compression", &compression, "quality", &quality, RI_NULL );
	}
	else
	{
		printf( "Texture %s ----> %s \n\t\"swrap\"= %s \n\t\"twrap\"= %s \n\t\"filter\"= %s \n\t\"swidth\"= %4.1f\n\t\"twidth\"= %4.1f\n\t\"compression\" = %s\n",
		        ( char* ) ap.leftovers() [ 0 ].c_str(),
		        ( char* ) ap.leftovers() [ 1 ].c_str(),
		        ( char* ) g_swrap.c_str(),
		        ( char* ) g_twrap.c_str(),
		        ( char* ) g_filter.c_str(),
		        g_swidth,
		        g_twidth,
		        compression
		      );

 		bake = g_bake;

		RiMakeTexture( ( char* ) ap.leftovers() [ 0 ].c_str(), ( char* ) ap.leftovers() [ 1 ].c_str(),
		               ( char* ) g_swrap.c_str(), ( char* ) g_twrap.c_str(), filterfunc,
		               ( float ) g_swidth, ( float ) g_twidth, "compression", &compression, "quality", &quality, "float bake", &bake, RI_NULL );
	}

	RiEnd();

	return ( 0 );
}
Example #16
0
int main(int argc, const char **argv)
{
    bool help = false;
    int errorcount = 0;
    std::string inputconfig;
    std::string outputconfig;
    
    ArgParse ap;
    ap.options("ociocheck -- validate an OpenColorIO configuration\n\n"
               "usage:  ociocheck [options]\n",
               "--help", &help, "Print help message",
               "--iconfig %s", &inputconfig, "Input .ocio configuration file (default: $OCIO)",
               "--oconfig %s", &outputconfig, "Output .ocio file",
               NULL);
    
    if (ap.parse(argc, argv) < 0)
    {
        std::cout << ap.geterror() << std::endl;
        ap.usage();
        std::cout << DESC_STRING;
        return 1;
    }
    
    if (help)
    {
        ap.usage();
        std::cout << DESC_STRING;
        return 1;
    }
    
    try
    {
        OCIO::ConstConfigRcPtr config;
        
        std::cout << std::endl;
        std::cout << "OpenColorIO Library Version: " << OCIO::GetVersion() << std::endl;
        std::cout << "OpenColorIO Library VersionHex: " << OCIO::GetVersionHex() << std::endl;
        
        if(!inputconfig.empty())
        {
            std::cout << "Loading " << inputconfig << std::endl;
            config = OCIO::Config::CreateFromFile(inputconfig.c_str());
        }
        else if(getenv("OCIO"))
        {
            std::cout << "Loading $OCIO " << getenv("OCIO") << std::endl;
            config = OCIO::Config::CreateFromEnv();
        }
        else
        {
            std::cout << "ERROR: You must specify an input OCIO configuration ";
            std::cout << "(either with --iconfig or $OCIO).\n";
            ap.usage ();
            std::cout << DESC_STRING;
            return 1;
        }
        
        std::cout << std::endl;
        std::cout << "** General **" << std::endl;
        std::cout << "Search Path: " << config->getSearchPath() << std::endl;
        std::cout << "Working Dir: " << config->getWorkingDir() << std::endl;
        
        std::cout << std::endl;
        std::cout << "Default Display: " << config->getDefaultDisplay() << std::endl;
        std::cout << "Default View: " << config->getDefaultView(config->getDefaultDisplay()) << std::endl;
        
        {
            std::cout << std::endl;
            std::cout << "** Roles **" << std::endl;
            
            std::set<std::string> usedroles;
            const char * allroles[] = { OCIO::ROLE_DEFAULT, OCIO::ROLE_SCENE_LINEAR,
                                        OCIO::ROLE_DATA, OCIO::ROLE_REFERENCE,
                                        OCIO::ROLE_COMPOSITING_LOG, OCIO::ROLE_COLOR_TIMING,
                                        OCIO::ROLE_COLOR_PICKING,
                                        OCIO::ROLE_TEXTURE_PAINT, OCIO::ROLE_MATTE_PAINT,
                                        NULL };
            int MAXROLES=256;
            for(int i=0;i<MAXROLES; ++i)
            {
                const char * role = allroles[i];
                if(!role) break;
                usedroles.insert(role);
                
                OCIO::ConstColorSpaceRcPtr cs = config->getColorSpace(role);
                if(cs)
                {
                    std::cout << cs->getName() << " (" << role << ")" << std::endl;
                }
                else
                {
                    std::cout << "ERROR: NOT DEFINED" << " (" << role << ")" << std::endl;
                    errorcount += 1;
                }
            }
            
            for(int i=0; i<config->getNumRoles(); ++i)
            {
                const char * role = config->getRoleName(i);
                if(usedroles.find(role) != usedroles.end()) continue;
                
                OCIO::ConstColorSpaceRcPtr cs = config->getColorSpace(role);
                if(cs)
                {
                    std::cout << cs->getName() << " (" << role << ": user)" << std::endl;
                }
                else
                {
                    std::cout << "ERROR: NOT DEFINED" << " (" << role << ")" << std::endl;
                    errorcount += 1;
                }
                
            }
        }
        
        std::cout << std::endl;
        std::cout << "** ColorSpaces **" << std::endl;
        OCIO::ConstColorSpaceRcPtr lin = config->getColorSpace(OCIO::ROLE_SCENE_LINEAR);
        if(!lin)
        {
            std::cout << "Error: scene_linear role must be defined." << std::endl;
            errorcount += 1;
        }
        else
        {
            for(int i=0; i<config->getNumColorSpaces(); ++i)
            {
                OCIO::ConstColorSpaceRcPtr cs = config->getColorSpace(config->getColorSpaceNameByIndex(i));
                
                bool convertsToLinear = true;
                std::string convertsToLinearErrorText;
                
                bool convertsFromLinear = true;
                std::string convertsFromLinearErrorText;
                
                try
                {
                    OCIO::ConstProcessorRcPtr p = config->getProcessor(cs, lin);
                }
                catch(OCIO::Exception & exception)
                {
                    convertsToLinear = false;
                    convertsToLinearErrorText = exception.what();
                }
                
                try
                {
                    OCIO::ConstProcessorRcPtr p = config->getProcessor(lin, cs);
                }
                catch(OCIO::Exception & exception)
                {
                    convertsFromLinear = false;
                    convertsFromLinearErrorText = exception.what();
                }
                
                if(convertsToLinear && convertsFromLinear)
                {
                    std::cout << cs->getName() << std::endl;
                }
                else if(!convertsToLinear && !convertsFromLinear)
                {
                    std::cout << cs->getName();
                    std::cout << " -- error" << std::endl;
                    std::cout << "\t" << convertsToLinearErrorText << std::endl;
                    std::cout << "\t" << convertsFromLinearErrorText << std::endl;
                    
                    errorcount += 1;
                }
                else if(convertsToLinear)
                {
                    std::cout << cs->getName();
                    std::cout << " -- input only" << std::endl;
                }
                else if(convertsFromLinear)
                {
                    std::cout << cs->getName();
                    std::cout << " -- output only" << std::endl;
                }
            }
        }
        
        std::cout << std::endl;
        std::cout << "** Looks **" << std::endl;
        if(config->getNumLooks()>0)
        {
            for(int i=0; i<config->getNumLooks(); ++i)
            {
                std::cout << config->getLookNameByIndex(i) << std::endl;
            }
        }
        else
        {
            std::cout << "no looks defined" << std::endl;
        }
        std::cout << std::endl;
        std::cout << "** Sanity Check **" << std::endl;
        
        try
        {
            config->sanityCheck();
            std::cout << "passed" << std::endl;
        }
        catch(OCIO::Exception & exception)
        {
            std::cout << "ERROR" << std::endl;
            errorcount += 1;
            std::cout << exception.what() << std::endl;
        }
        
        if(!outputconfig.empty())
        {
            std::ofstream output;
            output.open(outputconfig.c_str());
            
            if(!output.is_open())
            {
                std::cout << "Error opening " << outputconfig << " for writing." << std::endl;
            }
            else
            {
                config->serialize(output);
                output.close();
                std::cout << "Wrote " << outputconfig << std::endl;
            }
        }
    }
    catch(OCIO::Exception & exception)
    {
        std::cout << "ERROR: " << exception.what() << std::endl;
        return 1;
    } catch (std::exception& exception) {
        std::cout << "ERROR: " << exception.what() << "\n";
        return 1;
    }
    catch(...)
    {
        std::cout << "Unknown error encountered." << std::endl;
        return 1;
    }
    
        
    std::cout << std::endl;
    if(errorcount == 0)
    {
        std::cout << "Tests complete." << std::endl << std::endl;
        return 0;
    }
    else
    {
        std::cout << errorcount << " tests failed." << std::endl << std::endl;
        return 1;
    }
}
Example #17
0
int main (int argc, const char* argv[])
{
    
    bool help = false;
    int cubesize = -1;
    int shapersize = -1; // cubsize^2
    std::string format;
    std::string inputconfig;
    std::string inputspace;
    std::string shaperspace;
    std::string looks;
    std::string outputspace;
    bool usestdout = false;
    bool verbose = false;
    
    int whitepointtemp = 6505;
    std::string displayicc;
    std::string description;
    std::string copyright = "No copyright. Use freely.";
    
    // What are the allowed baker output formats?
    std::ostringstream formats;
    formats << "the LUT format to bake: ";
    for(int i=0; i<OCIO::Baker::getNumFormats(); ++i)
    {
        if(i!=0) formats << ", ";
        formats << OCIO::Baker::getFormatNameByIndex(i);
        formats << " (." << OCIO::Baker::getFormatExtensionByIndex(i) << ")";
    }
    formats << ", icc (.icc)";
    
    std::string formatstr = formats.str();
    
    std::string dummystr;
    float dummyf1, dummyf2, dummyf3;
    
    ArgParse ap;
    ap.options("ociobakelut -- create a new LUT or ICC profile from an OCIO config or LUT file(s)\n\n"
               "usage:  ociobakelut [options] <OUTPUTFILE.LUT>\n\n"
               "example:  ociobakelut --inputspace lg10 --outputspace srgb8 --format flame lg_to_srgb.3dl\n"
               "example:  ociobakelut --lut filmlut.3dl --lut calibration.3dl --format flame display.3dl\n"
               "example:  ociobakelut --cccid 0 --lut cdlgrade.ccc --lut calibration.3dl --format flame graded_display.3dl\n"
               "example:  ociobakelut --lut look.3dl --offset 0.01 -0.02 0.03 --lut display.3dl --format flame display_with_look.3dl\n"
               "example:  ociobakelut --inputspace lg10 --outputspace srgb8 --format icc ~/Library/ColorSync/Profiles/test.icc\n"
               "example:  ociobakelut --lut filmlut.3dl --lut calibration.3dl --format icc ~/Library/ColorSync/Profiles/test.icc\n\n",
               "%*", parse_end_args, "",
               "<SEPARATOR>", "Using Existing OCIO Configurations",
               "--inputspace %s", &inputspace, "Input OCIO ColorSpace (or Role)",
               "--outputspace %s", &outputspace, "Output OCIO ColorSpace (or Role)",
               "--shaperspace %s", &shaperspace, "the OCIO ColorSpace or Role, for the shaper",
               "--looks %s", &looks, "the OCIO looks to apply",
               "--iconfig %s", &inputconfig, "Input .ocio configuration file (default: $OCIO)\n",
               "<SEPARATOR>", "Config-Free LUT Baking",
               "<SEPARATOR>", "    (all options can be specified multiple times, each is applied in order)",
               "--cccid %s", &dummystr, "Specify a CCCId for any following LUTs",
               "--lut %s", &dummystr, "Specify a LUT (forward direction)",
               "--invlut %s", &dummystr, "Specify a LUT (inverse direction)",
               "--slope %f %f %f", &dummyf1, &dummyf2, &dummyf3, "slope",
               "--offset %f %f %f", &dummyf1, &dummyf2, &dummyf3, "offset (float)",
               "--offset10 %f %f %f", &dummyf1, &dummyf2, &dummyf3, "offset (10-bit)",
               "--power %f %f %f", &dummyf1, &dummyf2, &dummyf3, "power",
               "--sat %f", &dummyf1, "saturation (ASC-CDL luma coefficients)\n",
               "<SEPARATOR>", "Baking Options",
               "--format %s", &format, formatstr.c_str(),
               "--shapersize %d", &shapersize, "size of the shaper (default: format specific)",
               "--cubesize %d", &cubesize, "size of the cube (default: format specific)",
               "--stdout", &usestdout, "Write to stdout (rather than file)",
               "--v", &verbose, "Verbose",
               "--help", &help, "Print help message\n",
               "<SEPARATOR>", "ICC Options",
               //"--cubesize %d", &cubesize, "size of the ICC CLUT cube (default: 32)",
               "--whitepoint %d", &whitepointtemp, "whitepoint for the profile (default: 6505)",
               "--displayicc %s", &displayicc , "an ICC profile which matches the OCIO profiles target display",
               "--description %s", &description , "a meaningful description, this will show up in UI like photoshop (defaults to \"filename.icc\")",
               "--copyright %s", &copyright , "a copyright field (default: \"No copyright. Use freely.\"\n",
               // TODO: add --metadata option
               NULL);
    
    if (ap.parse(argc, argv) < 0)
    {
        std::cout << ap.geterror() << std::endl;
        ap.usage();
        std::cout << "\n";
        return 1;
    }
    
    if (help || (argc == 1 ))
    {
        ap.usage();
        std::cout << "\n";
        return 1;
    }
    
    // If we're printing to stdout, disable verbose printouts
    if(usestdout)
    {
        verbose = false;
    }
    
    // Create the OCIO processor for the specified transform.
    OCIO::ConstConfigRcPtr config;
    
    
    OCIO::GroupTransformRcPtr groupTransform;
    
    try
    {
        groupTransform = parse_luts(argc, argv);
    }
    catch(const OCIO::Exception & e)
    {
        std::cerr << "\nERROR: " << e.what() << std::endl;
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "\nERROR: An unknown error occurred in parse_luts" << std::endl;
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    
    if(!groupTransform)
    {
        std::cerr << "\nERROR: parse_luts returned null transform" << std::endl;
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    
    // If --luts have been specified, synthesize a new (temporary) configuration
    // with the transformation embedded in a colorspace.
    if(!groupTransform->empty())
    {
        if(!inputspace.empty())
        {
            std::cerr << "\nERROR: --inputspace is not allowed when using --lut\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        if(!outputspace.empty())
        {
            std::cerr << "\nERROR: --outputspace is not allowed when using --lut\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        if(!looks.empty())
        {
            std::cerr << "\nERROR: --looks is not allowed when using --lut\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        if(!shaperspace.empty())
        {
            std::cerr << "\nERROR: --shaperspace is not allowed when using --lut\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        
        OCIO::ConfigRcPtr editableConfig = OCIO::Config::Create();
        
        OCIO::ColorSpaceRcPtr inputColorSpace = OCIO::ColorSpace::Create();
        inputspace = "RawInput";
        inputColorSpace->setName(inputspace.c_str());
        editableConfig->addColorSpace(inputColorSpace);
        
        OCIO::ColorSpaceRcPtr outputColorSpace = OCIO::ColorSpace::Create();
        outputspace = "ProcessedOutput";
        outputColorSpace->setName(outputspace.c_str());
        
        outputColorSpace->setTransform(groupTransform,
            OCIO::COLORSPACE_DIR_FROM_REFERENCE);
        
        if(verbose)
        {
            std::cout << "[OpenColorIO DEBUG]: Specified Transform:";
            std::cout << *groupTransform;
            std::cout << "\n";
        }
        
        editableConfig->addColorSpace(outputColorSpace);
        config = editableConfig;
    }
    else
    {
    
        if(inputspace.empty())
        {
            std::cerr << "\nERROR: You must specify the --inputspace.\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        
        if(outputspace.empty())
        {
            std::cerr << "\nERROR: You must specify the --outputspace.\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        
        if(format.empty())
        {
            std::cerr << "\nERROR: You must specify the LUT format using --format.\n\n";
            std::cerr << "See --help for more info." << std::endl;
            return 1;
        }
        
        if(!inputconfig.empty())
        {
            if(!usestdout && verbose)
                std::cout << "[OpenColorIO INFO]: Loading " << inputconfig << std::endl;
            config = OCIO::Config::CreateFromFile(inputconfig.c_str());
        }
        else if(getenv("OCIO"))
        {
            if(!usestdout && verbose)
                std::cout << "[OpenColorIO INFO]: Loading $OCIO " << getenv("OCIO") << std::endl;
            config = OCIO::Config::CreateFromEnv();
        }
        else
        {
            std::cerr << "ERROR: You must specify an input OCIO configuration ";
            std::cerr << "(either with --iconfig or $OCIO).\n\n";
            ap.usage ();
            return 1;
        }
    }
    
    if(outputfile.empty() && !usestdout)
    {
        std::cerr << "\nERROR: You must specify the outputfile or --stdout.\n\n";
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    
    try
    {
        if(format == "icc")
        {
            if(description.empty())
            {
                description = outputfile;
                if(verbose)
                    std::cout << "[OpenColorIO INFO]: \"--description\" set to default value of filename.icc: " << outputfile << "" << std::endl;
            }
            
            if(usestdout)
            {
                std::cerr << "\nERROR: --stdout not supported when writing ICC profiles.\n\n";
                std::cerr << "See --help for more info." << std::endl;
                return 1;
            }
            
            if(outputfile.empty())
            {
                std::cerr << "ERROR: you need to specify a output ICC path\n";
                std::cerr << "See --help for more info." << std::endl;
                return 1;
            }
            
            if(cubesize<2) cubesize = 32; // default

            OCIO::ConstProcessorRcPtr processor;
            if (!looks.empty())
            {
                OCIO::LookTransformRcPtr transform =
                    OCIO::LookTransform::Create();
                transform->setLooks(looks.c_str());
                transform->setSrc(inputspace.c_str());
                transform->setDst(outputspace.c_str());
                processor = config->getProcessor(transform,
                    OCIO::TRANSFORM_DIR_FORWARD);
            }
            else
            {
                processor = config->getProcessor(inputspace.c_str(),
                    outputspace.c_str());
            }
            
            SaveICCProfileToFile(outputfile,
                                 processor,
                                 cubesize,
                                 whitepointtemp,
                                 displayicc,
                                 description,
                                 copyright,
                                 verbose);
        }
        else
        {
        
            OCIO::BakerRcPtr baker = OCIO::Baker::Create();
            
            // setup the baker for our LUT type
            baker->setConfig(config);
            baker->setFormat(format.c_str());
            baker->setInputSpace(inputspace.c_str());
            baker->setShaperSpace(shaperspace.c_str());
            baker->setLooks(looks.c_str());
            baker->setTargetSpace(outputspace.c_str());
            if(shapersize!=-1) baker->setShaperSize(shapersize);
            if(cubesize!=-1) baker->setCubeSize(cubesize);
            
            // output LUT
            std::ostringstream output;
            
            if(!usestdout && verbose)
                std::cout << "[OpenColorIO INFO]: Baking '" << format << "' LUT" << std::endl;
            
            if(usestdout)
            {
                baker->bake(std::cout);
            }
            else
            {
                std::ofstream f(outputfile.c_str());
                baker->bake(f);
                if(verbose)
                    std::cout << "[OpenColorIO INFO]: Wrote '" << outputfile << "'" << std::endl;
            }
        }
    }
    catch(OCIO::Exception & exception)
    {
        std::cerr << "OCIO Error: " << exception.what() << std::endl;
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    catch (std::exception& exception)
    {
        std::cerr << "Error: " << exception.what() << "\n";
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "Unknown OCIO error encountered." << std::endl;
        std::cerr << "See --help for more info." << std::endl;
        return 1;
    }
    
    return 0;
}
Example #18
0
int main( int argc, const char** argv )
{
	std::signal(SIGINT, aqsisSignalHandler);
	std::signal(SIGABRT, aqsisSignalHandler);
	RtInt returnCode = 0;

	StartMemoryDebugging();
	{
		ArgParse ap;
		ap.usageHeader( ArgParse::apstring( "Aqsis command line renderer\nUsage: " ) + argv[ 0 ] + " [options] [RIB file...]" );
		ap.argFlag( "help", "\aPrint this help and exit", &g_cl_help );
		ap.alias( "help" , "h" );
		ap.argFlag( "version", "\aPrint version information and exit", &g_cl_version );
		ap.argFlag( "pause", "\aWait for a keypress on completion", &g_cl_pause );
		ap.argFlag( "progress", "\aPrint progress information", &g_cl_progress );
		ap.argFlag( "Progress", "\aPrint PRMan-compatible progress information (ignores -progressformat)", &g_cl_Progress );
		ap.argString( "progressformat", "=string\aprintf-style format string for -progress", &g_cl_strprogress );
		ap.argInt( "endofframe", "=integer\aEquivalent to \"endofframe\" RIB option", &g_cl_endofframe );
		ap.argInt( "verbose", "=integer\aSet log output level\n"
		           "\a0 = errors\n"
		           "\a1 = warnings (default)\n"
		           "\a2 = information\n"
		           "\a3 = debug", &g_cl_verbose );
		ap.alias( "verbose", "v" );
		ap.argFlag( "echoapi", "\aEcho all RI API calls to the log output (experimental)", &g_cl_echoapi);

		ap.argInt( "priority", "=integer\aControl the priority class of aqsis.\n"
			"\a0 = idle\n"
			"\a1 = normal\n"
			"\a2 = high\n"
			"\a3 = RT", &g_cl_priority);
		ap.alias( "priority", "z");
		
		ap.argString( "type", "=string\aSpecify a display device type to use", &g_cl_type );
		ap.argString( "addtype", "=string\aSpecify a display device type to add", &g_cl_addtype );
		ap.argString( "mode", "=string\aSpecify a display device mode to use", &g_cl_mode );
		ap.argFlag( "fb", "\aSame as --type=\"framebuffer\" --mode=\"rgb\"", &g_cl_fb );
		ap.alias( "fb", "d" );
		ap.argFloats( "crop", " x1 x2 y1 y2\aSpecify a crop window, values are in screen space.", &g_cl_cropWindow, ArgParse::SEP_ARGV, 4);
		ap.argFlag( "nocolor", "\aDisable colored output", &g_cl_no_color );
		ap.argFlag( "beep", "\aBeep on completion of all ribs", &g_cl_beep );
		ap.alias( "nocolor", "nc" );
		ap.argInts( "res", " x y\aSpecify the resolution of the render.", &g_cl_res, ArgParse::SEP_ARGV, 2);
		ap.argStrings( "option", "=string\aA valid RIB Option string, can be specified multiple times.", &g_cl_options);
#		ifdef AQSIS_SYSTEM_POSIX
		ap.argFlag( "syslog", "\aLog messages to syslog", &g_cl_syslog );
#		endif // AQSIS_SYSTEM_POSIX
#		if ENABLE_MPDUMP
		ap.argFlag( "mpdump", "\aOutput MP list to a custom 'dump' file", &g_cl_mpdump );
#		endif // ENABLE_MPDUMP

		ap.argString( "shaders", "=string\aOverride the default shader searchpath(s)", &g_cl_shader_path );
		ap.argString( "archives", "=string\aOverride the default archive searchpath(s)", &g_cl_archive_path );
		ap.argString( "textures", "=string\aOverride the default texture searchpath(s)", &g_cl_texture_path );
		ap.argString( "displays", "=string\aOverride the default display searchpath(s)", &g_cl_display_path );
		ap.argString( "procedurals", "=string\aOverride the default procedural searchpath(s)", &g_cl_procedural_path );
		ap.allowUnrecognizedOptions();

		if ( argc > 1 && !ap.parse( argc - 1, argv + 1 ) )
		{
			Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
			return( 1 );
		}

		// Check that the number of arguments to crop are valid if specified.
		if ( g_cl_cropWindow.size() > 0 && g_cl_cropWindow.size() != 4 )
		{
			Aqsis::log() << Aqsis::error << "Invalid number of arguments to -crop, expected 4, got " << g_cl_cropWindow.size() << std::endl;
			g_cl_help = true;
		}

		if ( g_cl_help )
		{
			std::cout << ap.usagemsg();
			return( 0 );
		}

		if ( g_cl_version )
		{
			std::cout << "aqsis version " << AQSIS_VERSION_STR_FULL
#			ifdef _DEBUG
			<< " (debug build)"
#			endif
			<< "\n"
			<< "compiled " << __DATE__ << " " << __TIME__ << "\n";
			return( 0 );
		}

#		ifdef	AQSIS_SYSTEM_WIN32
		std::auto_ptr<std::streambuf> ansi( new Aqsis::ansi_buf(Aqsis::log()) );
#		endif

		std::auto_ptr<std::streambuf> reset_level( new Aqsis::reset_level_buf(Aqsis::log()) );
		std::auto_ptr<std::streambuf> show_timestamps( new Aqsis::timestamp_buf(Aqsis::log()) );
		std::auto_ptr<std::streambuf> fold_duplicates( new Aqsis::fold_duplicates_buf(Aqsis::log()) );
		std::auto_ptr<std::streambuf> color_level;
		if(!g_cl_no_color)
		{
			std::auto_ptr<std::streambuf> temp_color_level( new Aqsis::color_level_buf(Aqsis::log()) );
			color_level = temp_color_level;
		}
		std::auto_ptr<std::streambuf> show_level( new Aqsis::show_level_buf(Aqsis::log()) );
		Aqsis::log_level_t level = Aqsis::ERROR;
		if( g_cl_verbose > 0 )
			level = Aqsis::WARNING;
		if( g_cl_verbose > 1 )
			level = Aqsis::INFO;
		if( g_cl_verbose > 2 )
			level = Aqsis::DEBUG;
		std::auto_ptr<std::streambuf> filter_level( new Aqsis::filter_by_level_buf(level, Aqsis::log()) );
#		ifdef AQSIS_SYSTEM_POSIX
		if( g_cl_syslog )
			std::auto_ptr<std::streambuf> use_syslog( new Aqsis::syslog_buf(Aqsis::log()) );
#		endif // AQSIS_SYSTEM_POSIX

		if (g_cl_priority != 1)
		{
			// Set the priority on the main thread
			setPriority(g_cl_priority);
		}

		RiBegin(RI_NULL);
		setupOptions();
		try
		{
			if ( ap.leftovers().size() == 0 )
			{
				// If no files specified, take input from stdin.
				//
				// TODO: We'd like to turn off stdio synchronisation to allow fast
				// buffering... unfortunately this causes very odd problems with
				// the aqsis logging facility as of svn r2804
				//
				//std::ios_base::sync_with_stdio(false);
				Aqsis::QGetRenderContextI()->parseRibStream(std::cin, "stdin");
			}
			else
			{
				for(ArgParse::apstringvec::const_iterator fileName = ap.leftovers().begin();
						fileName != ap.leftovers().end(); fileName++)
				{
					std::ifstream inFile(fileName->c_str());
					if(inFile)
					{
						Aqsis::QGetRenderContextI()->parseRibStream(inFile, *fileName);
						returnCode = RiLastError;
					}
					else
					{
						Aqsis::log() << Aqsis::error
							<< "Cannot open file \"" << *fileName << "\"\n";
						returnCode = RIE_NOFILE;
					}
				}
			}
		}
		catch(const std::exception& e)
		{
			Aqsis::log() << Aqsis::error << e.what() << std::endl;
			returnCode = RIE_BUG;
		}
		catch(...)
		{
			Aqsis::log() << Aqsis::error
				<< "unknown exception has been encountered\n";
			returnCode = RIE_BUG;
		}
		RiEnd();
	}

	StopMemoryDebugging();

	if(g_cl_beep)
		std::cout << "\a" << std::ends;

	if(g_cl_pause)
	{
		std::cout << "Press any key..." << std::ends;
		std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
	}

	return returnCode;
}
static void options_parse(int argc, const char **argv)
{
	options.width = 0;
	options.height = 0;
	options.filepath = "";
	options.session = NULL;
	options.quiet = false;

	/* device names */
	string device_names = "";
	string devicename = "cpu";
	bool list = false;

	vector<DeviceType>& types = Device::available_types();

	foreach(DeviceType type, types) {
		if(device_names != "")
			device_names += ", ";

		device_names += Device::string_from_type(type);
	}

	/* shading system */
	string ssname = "svm";

	/* parse options */
	ArgParse ap;
	bool help = false;

	ap.options ("Usage: cycles [options] file.xml",
		"%*", files_parse, "",
		"--device %s", &devicename, ("Devices to use: " + device_names).c_str(),
#ifdef WITH_OSL
		"--shadingsys %s", &ssname, "Shading system to use: svm, osl",
#endif
		"--background", &options.session_params.background, "Render in background, without user interface",
		"--quiet", &options.quiet, "In background mode, don't print progress messages",
		"--samples %d", &options.session_params.samples, "Number of samples to render",
		"--output %s", &options.session_params.output_path, "File path to write output image",
		"--threads %d", &options.session_params.threads, "CPU Rendering Threads",
		"--width  %d", &options.width, "Window width in pixel",
		"--height %d", &options.height, "Window height in pixel",
		"--list-devices", &list, "List information about all available devices",
		"--help", &help, "Print help message",
		NULL);

	if(ap.parse(argc, argv) < 0) {
		fprintf(stderr, "%s\n", ap.geterror().c_str());
		ap.usage();
		exit(EXIT_FAILURE);
	}
	else if(list) {
		vector<DeviceInfo>& devices = Device::available_devices();
		printf("Devices:\n");

		foreach(DeviceInfo& info, devices) {
			printf("    %s%s\n",
				info.description.c_str(),
				(info.display_device)? " (display)": "");
		}

		exit(EXIT_SUCCESS);
	}
static void options_parse(int argc, const char **argv)
{
	options.width = 0;
	options.height = 0;
	options.filepath = "";
	options.session = NULL;
	options.quiet = false;

	/* device names */
	string device_names = "";
	string devicename = "cpu";
	bool list = false;

	vector<DeviceType>& types = Device::available_types();

	/* TODO(sergey): Here's a feedback loop happens: on the one hand we want
	 * the device list to be printed in help message, on the other hand logging
	 * is not initialized yet so we wouldn't have debug log happening in the
	 * device initialization.
	 */
	foreach(DeviceType type, types) {
		if(device_names != "")
			device_names += ", ";

		device_names += Device::string_from_type(type);
	}

	/* shading system */
	string ssname = "svm";

	/* parse options */
	ArgParse ap;
	bool help = false, debug = false, version = false;
	int verbosity = 1;

	ap.options ("Usage: cycles [options] file.xml",
		"%*", files_parse, "",
		"--device %s", &devicename, ("Devices to use: " + device_names).c_str(),
#ifdef WITH_OSL
		"--shadingsys %s", &ssname, "Shading system to use: svm, osl",
#endif
		"--background", &options.session_params.background, "Render in background, without user interface",
		"--quiet", &options.quiet, "In background mode, don't print progress messages",
		"--samples %d", &options.session_params.samples, "Number of samples to render",
		"--output %s", &options.session_params.output_path, "File path to write output image",
		"--threads %d", &options.session_params.threads, "CPU Rendering Threads",
		"--width  %d", &options.width, "Window width in pixel",
		"--height %d", &options.height, "Window height in pixel",
		"--list-devices", &list, "List information about all available devices",
#ifdef WITH_CYCLES_LOGGING
		"--debug", &debug, "Enable debug logging",
		"--verbose %d", &verbosity, "Set verbosity of the logger",
#endif
		"--help", &help, "Print help message",
		"--version", &version, "Print version number",
		NULL);

	if(ap.parse(argc, argv) < 0) {
		fprintf(stderr, "%s\n", ap.geterror().c_str());
		ap.usage();
		exit(EXIT_FAILURE);
	}

	if(debug) {
		util_logging_start();
		util_logging_verbosity_set(verbosity);
	}

	if(list) {
		vector<DeviceInfo>& devices = Device::available_devices();
		printf("Devices:\n");

		foreach(DeviceInfo& info, devices) {
			printf("    %-10s%s%s\n",
				Device::string_from_type(info.type).c_str(),
				info.description.c_str(),
				(info.display_device)? " (display)": "");
		}

		exit(EXIT_SUCCESS);
	}
Example #21
0
static void
getargs (int argc, char *argv[], ImageSpec &configspec)
{
    bool help = false;
    // Basic runtime options
    std::string dataformatname = "";
    std::string fileformatname = "";
    std::vector<std::string> mipimages;
    int tile[3] = { 64, 64, 1 };  // FIXME if we ever support volume MIPmaps
    std::string compression = "zip";
    bool updatemode = false;
    bool checknan = false;
    std::string fixnan; // none, black, box3
    bool set_full_to_pixels = false;
    bool do_highlight_compensation = false;
    std::string filtername;
    // Options controlling file metadata or mipmap creation
    float fovcot = 0.0f;
    std::string wrap = "black";
    std::string swrap;
    std::string twrap;
    bool doresize = false;
    Imath::M44f Mcam(0.0f), Mscr(0.0f);  // Initialize to 0
    bool separate = false;
    bool nomipmap = false;
    bool prman_metadata = false;
    bool constant_color_detect = false;
    bool monochrome_detect = false;
    bool opaque_detect = false;
    bool compute_average = true;
    int nchannels = -1;
    bool prman = false;
    bool oiio = false;
    bool ignore_unassoc = false;  // ignore unassociated alpha tags
    bool unpremult = false;
    bool sansattrib = false;
    float sharpen = 0.0f;
    std::string incolorspace;
    std::string outcolorspace;
    std::string colorconfigname;
    std::string channelnames;
    std::vector<std::string> string_attrib_names, string_attrib_values;
    std::vector<std::string> any_attrib_names, any_attrib_values;
    filenames.clear();

    ArgParse ap;
    ap.options ("maketx -- convert images to tiled, MIP-mapped textures\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  maketx [options] file...",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-o %s", &outputfilename, "Output filename",
                  "--threads %d", &nthreads, "Number of threads (default: #cores)",
                  "-u", &updatemode, "Update mode",
                  "--format %s", &fileformatname, "Specify output file format (default: guess from extension)",
                  "--nchannels %d", &nchannels, "Specify the number of output image channels.",
                  "--chnames %s", &channelnames, "Rename channels (comma-separated)",
                  "-d %s", &dataformatname, "Set the output data format to one of: "
                          "uint8, sint8, uint16, sint16, half, float",
                  "--tile %d %d", &tile[0], &tile[1], "Specify tile size",
                  "--separate", &separate, "Use planarconfig separate (default: contiguous)",
                  "--compression %s", &compression, "Set the compression method (default = zip, if possible)",
                  "--fovcot %f", &fovcot, "Override the frame aspect ratio. Default is width/height.",
                  "--wrap %s", &wrap, "Specify wrap mode (black, clamp, periodic, mirror)",
                  "--swrap %s", &swrap, "Specific s wrap mode separately",
                  "--twrap %s", &twrap, "Specific t wrap mode separately",
                  "--resize", &doresize, "Resize textures to power of 2 (default: no)",
                  "--noresize %!", &doresize, "Do not resize textures to power of 2 (deprecated)",
                  "--filter %s", &filtername, filter_help_string().c_str(),
                  "--hicomp", &do_highlight_compensation,
                          "Compress HDR range before resize, expand after.",
                  "--sharpen %f", &sharpen, "Sharpen MIP levels (default = 0.0 = no)",
                  "--nomipmap", &nomipmap, "Do not make multiple MIP-map levels",
                  "--checknan", &checknan, "Check for NaN/Inf values (abort if found)",
                  "--fixnan %s", &fixnan, "Attempt to fix NaN/Inf values in the image (options: none, black, box3)",
                  "--fullpixels", &set_full_to_pixels, "Set the 'full' image range to be the pixel data window",
                  "--Mcamera %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
                          &Mcam[0][0], &Mcam[0][1], &Mcam[0][2], &Mcam[0][3], 
                          &Mcam[1][0], &Mcam[1][1], &Mcam[1][2], &Mcam[1][3], 
                          &Mcam[2][0], &Mcam[2][1], &Mcam[2][2], &Mcam[2][3], 
                          &Mcam[3][0], &Mcam[3][1], &Mcam[3][2], &Mcam[3][3], 
                          "Set the camera matrix",
                  "--Mscreen %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
                          &Mscr[0][0], &Mscr[0][1], &Mscr[0][2], &Mscr[0][3], 
                          &Mscr[1][0], &Mscr[1][1], &Mscr[1][2], &Mscr[1][3], 
                          &Mscr[2][0], &Mscr[2][1], &Mscr[2][2], &Mscr[2][3], 
                          &Mscr[3][0], &Mscr[3][1], &Mscr[3][2], &Mscr[3][3], 
                          "Set the screen matrix",
                  "--prman-metadata", &prman_metadata, "Add prman specific metadata",
                  "--attrib %L %L", &any_attrib_names, &any_attrib_values, "Sets metadata attribute (name, value)",
                  "--sattrib %L %L", &string_attrib_names, &string_attrib_values, "Sets string metadata attribute (name, value)",
                  "--sansattrib", &sansattrib, "Write command line into Software & ImageHistory but remove --sattrib and --attrib options",
                  "--constant-color-detect", &constant_color_detect, "Create 1-tile textures from constant color inputs",
                  "--monochrome-detect", &monochrome_detect, "Create 1-channel textures from monochrome inputs",
                  "--opaque-detect", &opaque_detect, "Drop alpha channel that is always 1.0",
                  "--no-compute-average %!", &compute_average, "Don't compute and store average color",
                  "--ignore-unassoc", &ignore_unassoc, "Ignore unassociated alpha tags in input (don't autoconvert)",
                  "--runstats", &runstats, "Print runtime statistics",
                  "--stats", &runstats, "", // DEPRECATED 1.6
                  "--mipimage %L", &mipimages, "Specify an individual MIP level",
                  "<SEPARATOR>", "Basic modes (default is plain texture):",
                  "--shadow", &shadowmode, "Create shadow map",
                  "--envlatl", &envlatlmode, "Create lat/long environment map",
                  "--lightprobe", &lightprobemode, "Create lat/long environment map from a light probe",
                  "--bumpslopes", &bumpslopesmode, "Create a 6 channels bump-map with height, derivatives and square derivatives from an height or a normal map",
            
//                  "--envcube", &envcubemode, "Create cubic env map (file order: px, nx, py, ny, pz, nz) (UNIMP)",
                  "<SEPARATOR>", colortitle_help_string().c_str(),
                  "--colorconfig %s", &colorconfigname, "Explicitly specify an OCIO configuration file",
                  "--colorconvert %s %s", &incolorspace, &outcolorspace,
                          colorconvert_help_string().c_str(),
                  "--unpremult", &unpremult, "Unpremultiply before color conversion, then premultiply "
                          "after the color conversion.  You'll probably want to use this flag "
                          "if your image contains an alpha channel.",
                  "<SEPARATOR>", "Configuration Presets",
                  "--prman", &prman, "Use PRMan-safe settings for tile size, planarconfig, and metadata.",
                  "--oiio", &oiio, "Use OIIO-optimized settings for tile size, planarconfig, metadata.",
                  NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (filenames.empty()) {
        ap.briefusage ();
        std::cout << "\nFor detailed help: maketx --help\n";
        exit (EXIT_SUCCESS);
    }

    int optionsum = ((int)shadowmode + (int)envlatlmode + (int)envcubemode +
                     (int)lightprobemode) + (int)bumpslopesmode;
    if (optionsum > 1) {
        std::cerr << "maketx ERROR: At most one of the following options may be set:\n"
                  << "\t--shadow --envlatl --envcube --lightprobe\n";
        exit (EXIT_FAILURE);
    }
    if (optionsum == 0)
        mipmapmode = true;
    
    if (prman && oiio) {
        std::cerr << "maketx ERROR: '--prman' compatibility, and '--oiio' optimizations are mutually exclusive.\n";
        std::cerr << "\tIf you'd like both prman and oiio compatibility, you should choose --prman\n";
        std::cerr << "\t(at the expense of oiio-specific optimizations)\n";
        exit (EXIT_FAILURE);
    }

    if (filenames.size() != 1) {
        std::cerr << "maketx ERROR: requires exactly one input filename\n";
        exit (EXIT_FAILURE);
    }


//    std::cout << "Converting " << filenames[0] << " to " << outputfilename << "\n";

    // Figure out which data format we want for output
    if (! dataformatname.empty()) {
        if (dataformatname == "uint8")
            configspec.format = TypeDesc::UINT8;
        else if (dataformatname == "int8" || dataformatname == "sint8")
            configspec.format = TypeDesc::INT8;
        else if (dataformatname == "uint16")
            configspec.format = TypeDesc::UINT16;
        else if (dataformatname == "int16" || dataformatname == "sint16")
            configspec.format = TypeDesc::INT16;
        else if (dataformatname == "half")
            configspec.format = TypeDesc::HALF;
        else if (dataformatname == "float")
            configspec.format = TypeDesc::FLOAT;
        else if (dataformatname == "double")
            configspec.format = TypeDesc::DOUBLE;
        else {
            std::cerr << "maketx ERROR: unknown data format \"" << dataformatname << "\"\n";
            exit (EXIT_FAILURE);
        }
    }

    configspec.tile_width  = tile[0];
    configspec.tile_height = tile[1];
    configspec.tile_depth  = tile[2];
    configspec.attribute ("compression", compression);
    if (fovcot != 0.0f)
        configspec.attribute ("fovcot", fovcot);
    configspec.attribute ("planarconfig", separate ? "separate" : "contig");
    if (Mcam != Imath::M44f(0.0f))
        configspec.attribute ("worldtocamera", TypeMatrix, &Mcam);
    if (Mscr != Imath::M44f(0.0f))
        configspec.attribute ("worldtoscreen", TypeMatrix, &Mscr);
    std::string wrapmodes = (swrap.size() ? swrap : wrap) + ',' + 
                            (twrap.size() ? twrap : wrap);
    configspec.attribute ("wrapmodes", wrapmodes);

    configspec.attribute ("maketx:verbose", verbose);
    configspec.attribute ("maketx:runstats", runstats);
    configspec.attribute ("maketx:resize", doresize);
    configspec.attribute ("maketx:nomipmap", nomipmap);
    configspec.attribute ("maketx:updatemode", updatemode);
    configspec.attribute ("maketx:constant_color_detect", constant_color_detect);
    configspec.attribute ("maketx:monochrome_detect", monochrome_detect);
    configspec.attribute ("maketx:opaque_detect", opaque_detect);
    configspec.attribute ("maketx:compute_average", compute_average);
    configspec.attribute ("maketx:unpremult", unpremult);
    configspec.attribute ("maketx:incolorspace", incolorspace);
    configspec.attribute ("maketx:outcolorspace", outcolorspace);
    configspec.attribute ("maketx:colorconfig", colorconfigname);
    configspec.attribute ("maketx:checknan", checknan);
    configspec.attribute ("maketx:fixnan", fixnan);
    configspec.attribute ("maketx:set_full_to_pixels", set_full_to_pixels);
    configspec.attribute ("maketx:highlightcomp", (int)do_highlight_compensation);
    configspec.attribute ("maketx:sharpen", sharpen);
    if (filtername.size())
        configspec.attribute ("maketx:filtername", filtername);
    configspec.attribute ("maketx:nchannels", nchannels);
    configspec.attribute ("maketx:channelnames", channelnames);
    if (fileformatname.size())
        configspec.attribute ("maketx:fileformatname", fileformatname);
    configspec.attribute ("maketx:prman_metadata", prman_metadata);
    configspec.attribute ("maketx:oiio_options", oiio);
    configspec.attribute ("maketx:prman_options", prman);
    if (mipimages.size())
        configspec.attribute ("maketx:mipimages", Strutil::join(mipimages,";"));

    std::string cmdline = Strutil::format ("OpenImageIO %s : %s",
                                     OIIO_VERSION_STRING,
                                     command_line_string (argc, argv, sansattrib));
    configspec.attribute ("Software", cmdline);
    configspec.attribute ("maketx:full_command_line", cmdline);

    // Add user-specified string attributes
    for (size_t i = 0; i < string_attrib_names.size(); ++i) {
        configspec.attribute (string_attrib_names[i], string_attrib_values[i]);
    }

    // Add user-specified "any" attributes -- try to deduce the type
    for (size_t i = 0; i < any_attrib_names.size(); ++i) {
        string_view s = any_attrib_values[i];
        // Does it parse as an int (and nothing more?)
        int ival;
        if (Strutil::parse_int(s,ival)) {
            Strutil::skip_whitespace(s);
            if (! s.size()) {
                configspec.attribute (any_attrib_names[i], ival);
                continue;
            }
        }
        s = any_attrib_values[i];
        // Does it parse as a float (and nothing more?)
        float fval;
        if (Strutil::parse_float(s,fval)) {
            Strutil::skip_whitespace(s);
            if (! s.size()) {
                configspec.attribute (any_attrib_names[i], fval);
                continue;
            }
        }
        // OK, treat it like a string
        configspec.attribute (any_attrib_names[i], any_attrib_values[i]);
    }

    if (ignore_unassoc) {
        configspec.attribute ("maketx:ignore_unassoc", (int)ignore_unassoc);
        ImageCache *ic = ImageCache::create ();  // get the shared one
        ic->attribute ("unassociatedalpha", (int)ignore_unassoc);
    }
}
Example #22
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    
    ArgParse ap;
    ap.options ("maketx -- convert images to tiled, MIP-mapped textures\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  maketx [options] file...",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-o %s", &outputfilename, "Output filename",
                  "-t %d", &nthreads, "Number of threads (default: #cores)",
                  "-u", &updatemode, "Update mode",
                  "--format %s", &fileformatname, "Specify output file format (default: guess from extension)",
                  "--nchannels %d", &nchannels, "Specify the number of output image channels.",
                  "-d %s", &dataformatname, "Set the output data format to one of: "
                          "uint8, sint8, uint16, sint16, half, float",
                  "--tile %d %d", &tile[0], &tile[1], "Specify tile size",
                  "--separate", &separate, "Use planarconfig separate (default: contiguous)",
//                  "--ingamma %f", &ingamma, "Specify gamma of input files (default: 1)",
//                  "--outgamma %f", &outgamma, "Specify gamma of output files (default: 1)",
//                  "--opaquewidth %f", &opaquewidth, "Set z fudge factor for volume shadows",
                  "--fov %f", &fov, "Field of view for envcube/shadcube/twofish",
                  "--fovcot %f", &fovcot, "Override the frame aspect ratio. Default is width/height.",
                  "--wrap %s", &wrap, "Specify wrap mode (black, clamp, periodic, mirror)",
                  "--swrap %s", &swrap, "Specific s wrap mode separately",
                  "--twrap %s", &twrap, "Specific t wrap mode separately",
                  "--resize", &doresize, "Resize textures to power of 2 (default: no)",
                  "--noresize", &noresize, "Do not resize textures to power of 2 (deprecated)",
                  "--filter %s", &filtername, filter_help_string().c_str(),
                  "--nomipmap", &nomipmap, "Do not make multiple MIP-map levels",
                  "--checknan", &checknan, "Check for NaN and Inf values (abort if found)",
                  "--Mcamera %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
                          &Mcam[0][0], &Mcam[0][1], &Mcam[0][2], &Mcam[0][3], 
                          &Mcam[1][0], &Mcam[1][1], &Mcam[1][2], &Mcam[1][3], 
                          &Mcam[2][0], &Mcam[2][1], &Mcam[2][2], &Mcam[2][3], 
                          &Mcam[3][0], &Mcam[3][1], &Mcam[3][2], &Mcam[3][3], 
                          "Set the camera matrix",
                  "--Mscreen %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
                          &Mscr[0][0], &Mscr[0][1], &Mscr[0][2], &Mscr[0][3], 
                          &Mscr[1][0], &Mscr[1][1], &Mscr[1][2], &Mscr[1][3], 
                          &Mscr[2][0], &Mscr[2][1], &Mscr[2][2], &Mscr[2][3], 
                          &Mscr[3][0], &Mscr[3][1], &Mscr[3][2], &Mscr[3][3], 
                          "Set the camera matrix",
                  "--hash", &embed_hash, "Embed SHA-1 hash of pixels in the header",
                  "--prman-metadata", &prman_metadata, "Add prman specific metadata",
                  "--constant-color-detect", &constant_color_detect, "Create 1-tile textures from constant color inputs",
                  "--monochrome-detect", &monochrome_detect, "Create 1-channel textures from monochrome inputs",
                  "--stats", &stats, "Print runtime statistics",
//FIXME           "-c %s", &channellist, "Restrict/shuffle channels",
//FIXME           "-debugdso"
//FIXME           "-note %s", &note, "Append a note to the image comments",
                  "<SEPARATOR>", "Basic modes (default is plain texture):",
                  "--shadow", &shadowmode, "Create shadow map",
//                  "--shadcube", &shadowcubemode, "Create shadow cube (file order: px,nx,py,ny,pz,nz) (UNIMPLEMENTED)",
//                  "--volshad", &volshadowmode, "Create volume shadow map (UNIMP)",
                  "--envlatl", &envlatlmode, "Create lat/long environment map",
                  "--envcube", &envcubemode, "Create cubic env map (file order: px, nx, py, ny, pz, nz) (UNIMP)",
//                  "--lightprobe", &lightprobemode, "Convert a lightprobe to cubic env map (UNIMP)",
//                  "--latl2envcube", &latl2envcubemode, "Convert a lat-long env map to a cubic env map (UNIMP)",
//                  "--vertcross", &vertcrossmode, "Convert a vertical cross layout to a cubic env map (UNIMP)",
                  "<SEPARATOR>", "Configuration Presets",
                  "--prman", &prman, "Use PRMan-safe settings for tile size, planarconfig, and metadata.",
                  "--oiio", &oiio, "Use OIIO-optimized settings for tile size, planarconfig, metadata, and constant-color optimizations.",
                  NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    full_command_line = ap.command_line ();

    int optionsum = ((int)shadowmode + (int)shadowcubemode + (int)volshadowmode +
                     (int)envlatlmode + (int)envcubemode +
                     (int)lightprobemode + (int)vertcrossmode +
                     (int)latl2envcubemode);
    if (optionsum > 1) {
        std::cerr << "maketx ERROR: At most one of the following options may be set:\n"
                  << "\t--shadow --shadcube --volshad --envlatl --envcube\n"
                  << "\t--lightprobe --vertcross --latl2envcube\n";
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (optionsum == 0)
        mipmapmode = true;
    if (doresize)
        noresize = false;
    
    if (prman && oiio) {
        std::cerr << "maketx ERROR: '--prman' compatibility, and '--oiio' optimizations are mutually exclusive.\n";
        std::cerr << "\tIf you'd like both prman and oiio compatibility, you should choose --prman\n";
        std::cerr << "\t(at the expense of oiio-specific optimizations)\n";
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (filenames.size() < 1) {
        std::cerr << "maketx ERROR: Must have at least one input filename specified.\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }

    filter = setup_filter (filtername);
    if (! filter) {
        std::cerr << "maketx ERROR: could not make filter '" << filtername << "\n";
        exit (EXIT_FAILURE);
    }

    if (embed_hash && verbose) {
        std::cerr << "maketx WARNING: The --embed_hash option is deprecated, and no longer necessary.\n";
        std::cerr << "                 (Hashes are always computed.)\n";
    }
    
//    std::cout << "Converting " << filenames[0] << " to " << outputfilename << "\n";
}
Example #23
0
/** Process the sl file from stdin and produce an slx bytestream.
 */
int main( int argc, const char** argv )
{
	ArgParse ap;
	boost::scoped_ptr<IqCodeGen> codeGenerator;
	bool error = false; ///! Couldn't compile shader

	ap.usageHeader( ArgParse::apstring( "Usage: " ) + argv[ 0 ] + " [options] <filename>" );
	ap.argString( "o", " %s \aspecify output filename", &g_stroutname );
	ap.argStrings( "i", "%s \aSet path for #include files.", &g_includes );
	ap.argStrings( "I", "%s \aSet path for #include files.", &g_includes );
	ap.argStrings( "D", "Sym[=value] \adefine symbol <string> to have value <value> (default: 1).", &g_defines );
	ap.argStrings( "U", "Sym \aUndefine an initial symbol.", &g_undefines );
	ap.argString( "backend", " %s \aCompiler backend (default %default).  Possibilities include \"slx\" or \"dot\":\a"
			      "slx - produce a compiled shader (in the aqsis shader VM stack language)\a"
				  "dot - make a graphviz visualization of the parse tree (useful for debugging only).", &g_backendName );
	ap.argFlag( "help", "\aPrint this help and exit", &g_help );
	ap.alias("help", "h");
	ap.argFlag( "version", "\aPrint version information and exit", &g_version );
	ap.argFlag( "nocolor", "\aDisable colored output", &g_cl_no_color );
	ap.alias( "nocolor" , "nc" );
	ap.argFlag( "d", "\adump sl data", &g_dumpsl );
	ap.argInt( "verbose", "=integer\aSet log output level\n"
			   "\a0 = errors\n"
			   "\a1 = warnings (default)\n"
			   "\a2 = information\n"
			   "\a3 = debug", &g_cl_verbose );
	ap.alias( "verbose", "v" );

	if ( argc > 1 && !ap.parse( argc - 1, argv + 1 ) )
	{
		Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
		exit( 1 );
	}

	if ( g_version )
	{
		version( std::cout );
		exit( 0 );
	}

	if ( g_help )
	{
		std::cout << ap.usagemsg();
		exit( 0 );
	}

#ifdef	AQSIS_SYSTEM_WIN32
	std::auto_ptr<std::streambuf> ansi( new Aqsis::ansi_buf(Aqsis::log()) );
#endif

	std::auto_ptr<std::streambuf> reset_level( new Aqsis::reset_level_buf(Aqsis::log()) );
	std::auto_ptr<std::streambuf> show_timestamps( new Aqsis::timestamp_buf(Aqsis::log()) );
	std::auto_ptr<std::streambuf> fold_duplicates( new Aqsis::fold_duplicates_buf(Aqsis::log()) );
	std::auto_ptr<std::streambuf> color_level;
	if(!g_cl_no_color)
	{
		std::auto_ptr<std::streambuf> temp_color_level( new Aqsis::color_level_buf(Aqsis::log()) );
		color_level = temp_color_level;
	}
	std::auto_ptr<std::streambuf> show_level( new Aqsis::show_level_buf(Aqsis::log()) );
	Aqsis::log_level_t level = Aqsis::ERROR;
	if( g_cl_verbose > 0 )
		level = Aqsis::WARNING;
	if( g_cl_verbose > 1 )
		level = Aqsis::INFO;
	if( g_cl_verbose > 2 )
		level = Aqsis::DEBUG;
	std::auto_ptr<std::streambuf> filter_level( new Aqsis::filter_by_level_buf(level, Aqsis::log()) );
#ifdef	AQSIS_SYSTEM_POSIX

	if( g_cl_syslog )
		std::auto_ptr<std::streambuf> use_syslog( new Aqsis::syslog_buf(Aqsis::log()) );
#endif	// AQSIS_SYSTEM_POSIX

	if ( ap.leftovers().size() == 0 )
	{
		std::cout << ap.usagemsg();
		exit( 0 );
	}
	else
	{
		for ( ArgParse::apstringvec::const_iterator e = ap.leftovers().begin(); e != ap.leftovers().end(); e++ )
		{
			//Expand filenames
			std::vector<std::string> files = Aqsis::cliGlob(*e);
			std::vector<std::string>::iterator it;
			for(it = files.begin(); it != files.end(); ++it){ 
				ResetParser();
				// Create a code generator for the requested backend.
				if(g_backendName == "slx")
					codeGenerator.reset(new CqCodeGenVM());
				else if(g_backendName == "dot")
					codeGenerator.reset(new CqCodeGenGraphviz());
				else
				{
					std::cout << "Unknown backend type: \"" << g_backendName << "\", assuming slx.";
					codeGenerator.reset(new CqCodeGenVM());
				}
				// current file position is saved for exception handling
				boost::wave::util::file_position_type current_position;

				try
				{
					//  Open and read in the specified input file.
					std::ifstream instream(it->c_str());
					std::string instring;
	
					if (!instream.is_open()) 
					{
						std::cerr << "Could not open input file: " << *it << std::endl;
						continue;
					}
					instream.unsetf(std::ios::skipws);
					instring = std::string(std::istreambuf_iterator<char>(instream.rdbuf()),
					    std::istreambuf_iterator<char>());
	
					typedef boost::wave::cpplexer::lex_token<> token_type;
					typedef boost::wave::cpplexer::lex_iterator<token_type> lex_iterator_type;
					typedef boost::wave::context<std::string::iterator, lex_iterator_type>
					    context_type;
					context_type ctx (instring.begin(), instring.end(), it->c_str());

					// Append the -i arguments passed in to forward them to the preprocessor.
					for ( ArgParse::apstringvec::const_iterator include = g_includes.begin(); include != g_includes.end(); include++ )
					{
						ctx.add_sysinclude_path( include->c_str() );
						ctx.add_include_path( include->c_str() );
					}
  
					// Setup the default defines.
					ctx.add_macro_definition( "AQSIS" );
					ctx.add_macro_definition( "PI=3.141592654" );
  
					// Append the -d arguments passed in to forward them to the preprocessor.
					for ( ArgParse::apstringvec::const_iterator define = g_defines.begin(); define != g_defines.end(); define++ )
					{
						ctx.add_macro_definition( define->c_str() );
					}
  
					// Append the -u arguments passed in to forward them to the preprocessor.
					for ( ArgParse::apstringvec::const_iterator undefine = g_undefines.begin(); undefine != g_undefines.end(); undefine++ )
					{
						ctx.remove_macro_definition( undefine->c_str() );
					}
  
					// analyze the input file
					context_type::iterator_type first = ctx.begin();
					context_type::iterator_type last = ctx.end();

					std::stringstream preprocessed(std::stringstream::in | std::stringstream::out);
					std::ofstream dumpfile;
					if( g_dumpsl )
					{
						std::string dumpfname(*it);
						dumpfname.append(".pp");
						dumpfile.open(dumpfname.c_str());
					};

					while (first != last) 
					{
						current_position = (*first).get_position();
						preprocessed << (*first).get_value();
						dumpfile << (*first).get_value();

						try
						{
							++first	;
						}
						catch (boost::wave::preprocess_exception &e) 
  						{
							Aqsis::log() 
							<< e.file_name() << "(" << e.line_no() << "): "
							<< e.description() << std::endl;
							if (e.get_errorcode() == ::boost::wave::preprocess_exception::last_line_not_terminated )
							{
								preprocessed << std::endl;
								dumpfile << std::endl;
								break;
							};
  						}
						catch (...) 
						{
							throw &e;
						}

					};
  
					if( dumpfile.is_open() )
						dumpfile.close();
  
					if ( Parse( preprocessed, e->c_str(), Aqsis::log() ) )
						codeGenerator->OutputTree( GetParseTree(), g_stroutname );
					else
						error = true;
				}
				catch (boost::wave::cpp_exception &e) 
				{
					// some preprocessing error
					Aqsis::log() 
					<< e.file_name() << "(" << e.line_no() << "): "
					<< e.description() << std::endl;
					continue;
				}
				catch (std::exception &e)
				{
					// use last recognized token to retrieve the error position
					Aqsis::log() << current_position.get_file()
				        << "(" << current_position.get_line() << "): "
				        << "exception caught: " << e.what()
				        << std::endl;
					continue;
				}
				catch (...) {
					// use last recognized token to retrieve the error position
					Aqsis::log() << current_position.get_file()
					<< "(" << current_position.get_line() << "): "
					<< "unexpected exception caught." << std::endl;
					continue;
				}
			}
		};
	}

	return error;
}
Example #24
0
static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("iconvert -- copy images with format conversions and other alterations\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  iconvert [options] inputfile outputfile\n"
                "   or:  iconvert --inplace [options] file...\n",
                "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose status messages",
                "--threads %d", &nthreads, "Number of threads (default 0 = #cores)",
                "-d %s", &dataformatname, "Set the output data format to one of:"
                        "uint8, sint8, uint10, uint12, uint16, sint16, half, float, double",
                "-g %f", &gammaval, "Set gamma correction (default = 1)",
                "--tile %d %d", &tile[0], &tile[1], "Output as a tiled image",
                "--scanline", &scanline, "Output as a scanline image",
                "--compression %s", &compression, "Set the compression method (default = same as input)",
                "--quality %d", &quality, "Set the compression quality, 1-100",
                "--no-copy-image", &no_copy_image, "Do not use ImageOutput copy_image functionality (dbg)",
                "--adjust-time", &adjust_time, "Adjust file times to match DateTime metadata",
                "--caption %s", &caption, "Set caption (ImageDescription)",
                "--keyword %L", &keywords, "Add a keyword",
                "--clear-keywords", &clear_keywords, "Clear keywords",
                "--attrib %L %L", &attribnames, &attribvals, "Set a string attribute (name, value)",
                "--orientation %d", &orientation, "Set the orientation",
                "--rotcw", &rotcw, "Rotate 90 deg clockwise",
                "--rotccw", &rotccw, "Rotate 90 deg counter-clockwise",
                "--rot180", &rot180, "Rotate 180 deg",
                "--inplace", &inplace, "Do operations in place on images",
                "--sRGB", &sRGB, "This file is in sRGB color space",
                "--separate", &separate, "Force planarconfig separate",
                "--contig", &contig, "Force planarconfig contig",
                "--no-clobber", &noclobber, "Do no overwrite existing files",
//FIXME         "-z", &zfile, "Treat input as a depth file",
//FIXME         "-c %s", &channellist, "Restrict/shuffle channels",
                NULL);
    if (ap.parse(argc, (const char**)argv) < 0) {
	std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (filenames.size() != 2 && ! inplace) {
        std::cerr << "iconvert: Must have both an input and output filename specified.\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
    if (filenames.size() == 0 && inplace) {
        std::cerr << "iconvert: Must have at least one filename\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
    if (((int)rotcw + (int)rotccw + (int)rot180 + (orientation>0)) > 1) {
        std::cerr << "iconvert: more than one of --rotcw, --rotccw, --rot180, --orientation\n";
        ap.usage();
        exit (EXIT_FAILURE);
    }
}
int main(int argc, const char** argv)
{
	ArgParse::apflag showhelp = false;
	ArgParse::apint myint = 0;

	ArgParse ap;
	ap.allowOneCharOptionsToBeCombined();
	ap.usageHeader(ArgParse::apstring("Usage: ") + argv[0] + " [options]");
	ap.argFlag("help", "\aprint this help, then exit", &showhelp);
	ap.argInt("integer", "=value\aa random integer you can give for no reason",
	          &myint);
	ap.alias("help", "h");
	ap.alias("integer", "i");
	if (!ap.parse(argc-1, argv+1))
	{
		Aqsis::log() << ap.errmsg() << std::endl << ap.usagemsg();
		return 1;
	}

	if (ap.leftovers().size() > 0)
	{
		Aqsis::log() << "Extra crud \"" << ap.leftovers()[0] << "\" on command line";
		Aqsis::log() << std::endl << ap.usagemsg();
		return 1;
	}

	if (myint != 0)
	{
		cout << "Your favorite integer is " << myint << endl;
	}

	if (showhelp)
	{
		cout << ap.usagemsg();
		return 0;
	}

	int bad = 0;

	cout << "Testing flags and integers... ";
	myint = 3;
	showhelp = false;
	int ok = 0;
	const char* av[100];

	if (ap.parse(0, av) && !showhelp && myint == 3 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-h";
	if (ap.parse(1, av) && showhelp && myint == 3 && ap.leftovers().size() == 0)
		ok++;

	showhelp = false;
	av[0] = "--help";
	if (ap.parse(1, av) && showhelp && myint == 3 && ap.leftovers().size() == 0)
		ok++;

	showhelp = false;
	av[0] = "--integer";
	av[1] = "5";
	if (ap.parse(2, av) && !showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	myint = 3;
	av[0] = "-i";
	if (ap.parse(2, av) && !showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	myint = 3;
	av[2] = "--help";
	if (ap.parse(3, av) && showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-h";
	av[1] = "-i";
	av[2] = "5";
	myint = 3;
	showhelp = false;
	if (ap.parse(3, av) && showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-hi";
	av[1] = "5";
	myint = 3;
	showhelp = false;
	if (ap.parse(2, av) && showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-hi=5";
	myint = 3;
	showhelp = false;
	if (ap.parse(1, av) && showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-help";
	if (!ap.parse(1, av) &&
	        ap.errmsg() == "-help: 'e' is an unrecognized option")
		ok++;

	av[0] = "--integer=5";
	myint = 3;
	showhelp = false;
	if (ap.parse(1, av) && !showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "--integer:5";
	myint = 3;
	if (ap.parse(1, av) && !showhelp && myint == 5 && ap.leftovers().size() == 0)
		ok++;

	av[0] = "-ih";
	av[1] = "5";
	if (!ap.parse(2, av) &&
	        ap.errmsg() == "-ih: 'i' requires an argument")
		ok++;

	av[0] = "--help=5";
	if (!ap.parse(1, av) &&
	        ap.errmsg() == "--help=5: doesn't take an argument")
		ok++;

	av[0] = "--nohelp";
	showhelp = true;
	myint = 3;
	if (ap.parse(1, av) && !showhelp && myint == 3 && ap.leftovers().size() == 0)
		ok++;

	av[1] = "--help";
	if (!ap.parse(2, av) &&
	        ap.errmsg() == "--help: negated flag used with non-negated flag")
		ok++;

	if (ok == 16)
	{
		cout << "PASS" << endl;
	}
	else
	{
		cout << "FAIL" << endl;
		bad++;
	}

	ok = 0;
	cout << "Testing strings and floats... ";

	ArgParse::apfloat tex;
	ArgParse::apfloat metafont;
	ArgParse::apstring kpathsea;
	ArgParse t1;
	t1.argFloat("tex", "\aversion of TeX", &tex);
	t1.argFloat("metafont", "\aversion of Metafont", &metafont);
	t1.argString("kpathsea", "\aversion of Kpathsea", &kpathsea);

	av[0] = "-tex";
	av[1] = "3.14159";
	av[2] = "--metafont=2.7182";
	av[3] = "--kpathsea";
	av[4] = "3.3.1";
	if (t1.parse(5, av) && t1.leftovers().size() == 0 &&
	        tex == 3.14159 && metafont == 2.7182 && kpathsea == "3.3.1")
		ok++;

	av[1] = "blech";
	if (!t1.parse(5, av) &&
	        t1.errmsg() ==  "-tex: \"blech\" is not a valid floating-point number")
		ok++;

	if (ok == 2)
	{
		cout << "PASS" << endl;
	}
	else
	{
		cout << "FAIL" << endl;
		bad++;
	}

	ok = 0;
	cout << "Testing usage message... ";

	ArgParse::apflag junkf;
	ArgParse t2;
	t2.usageHeader("GNU `tar' saves blah, blah, blah\n\n"
	               "Main operation mode:", 26);
	t2.argFlag("t", "\alist the contents of an archive", &junkf);
	t2.argFlag("x", "\aextract files from an archive", &junkf);
	t2.argFlag("delete",
	           "\adelete from the archive (not on mag tapes!)", &junkf);
	t2.alias("t", "list");
	t2.alias("x", "extract");
	t2.alias("x", "get");
	t2.usageHeader("\nOperation modifiers:", 29);
	t2.argFlag("G", "\ahandle old GNU-format incremental backup", &junkf);
	t2.argFlag("g", "=FILE\ahandle new GNU-format incremental backup", &junkf);
	t2.alias("G", "incremental");
	t2.alias("g", "listed-incremental");
	t2.usageHeader("\nArchive format selection:", 37);
	t2.argFlag("V", "=NAME\acreate archive with volume name NAME\n      "
	           "        PATTERN\aat list/extract time, a globbing PATTERN",
	           &junkf);
	t2.alias("V", "label");
	t2.allowOneCharOptionsToBeCombined();
	if (t2.usagemsg() ==
	        "GNU `tar' saves blah, blah, blah\n"
	        "\n"
	        "Main operation mode:\n"
	        "  -t, --list              list the contents of an archive\n"
	        "  -x, --get, --extract    extract files from an archive\n"
	        "      --delete            delete from the archive (not on mag tapes!)\n"
	        "\n"
	        "Operation modifiers:\n"
	        "  -G, --incremental          handle old GNU-format incremental backup\n"
	        "  -g, --listed-incremental=FILE\n"
	        "                             handle new GNU-format incremental backup\n"
	        "\n"
	        "Archive format selection:\n"
	        "  -V, --label=NAME                   create archive with volume name NAME\n"
	        "              PATTERN                at list/extract time, a globbing PATTERN\n")
		ok++;

	if (ok == 1)
	{
		cout << "PASS" << endl;
	}
	else
	{
		cout << "FAIL" << endl;
		bad++;
	}

	ok = 0;
	cout << "Testing arrays... ";
	ArgParse::apintvec foo;
	ArgParse::apfloatvec bar;
	ArgParse::apstringvec baz;
	ArgParse t3;
	t3.argInts("foo", "", &foo);
	t3.argFloats("bar", "", &bar);
	t3.argStrings("baz", "", &baz);

	av[0] = "eins";
	av[1] = "-baz=one";
	av[2] = "-foo=1";
	av[3] = "zwei";
	av[4] = "drei";
	av[5] = "-baz";
	av[6] = "two";
	av[7] = "vier";
	av[8] = "-foo=2";
	av[9] = "-bar=1";
	av[10] = "-bar=2";
	av[11] = "-bar";
	av[12] = "3";
	av[13] = "-bar:4";
	av[14] = "-foo=3";
	av[15] = "--baz=three";
	av[16] = "-baz:four";
	av[17] = "-foo=4";
	if (t3.parse(18, av) && checkArrays(foo, bar, baz, t3.leftovers()))
		ok++;

	foo.clear();
	bar.clear();
	baz.clear();
	ArgParse t4;
	t4.argInts("foo", "", &foo, ArgParse::SEP_ARGV);
	t4.argFloats("bar", "", &bar, ArgParse::SEP_ARGV);
	t4.argStrings("baz", "", &baz, ArgParse::SEP_ARGV);
	av[0] = "eins";
	av[1] = "zwei";
	av[2] = "-baz=one";
	av[3] = "two";
	av[4] = "-foo";
	av[5] = "1";
	av[6] = "2";
	av[7] = "3";
	av[8] = "-baz=three";
	av[9] = "-bar=1";
	av[10] = "-bar=2";
	av[11] = "-bar";
	av[12] = "3";
	av[13] = "4";
	av[14] = "-foo=4";
	av[15] = "--baz";
	av[16] = "four";
	av[17] = "--";
	av[18] = "drei";
	av[19] = "vier";
	if (t4.parse(20, av) && checkArrays(foo, bar, baz, t4.leftovers()))
		ok++;

	foo.clear();
	bar.clear();
	baz.clear();
	ArgParse t5;
	t5.argInts("foo", "", &foo, ',');
	t5.argFloats("bar", "", &bar, ',');
	t5.argStrings("baz", "", &baz, ',');
	av[0] = "-foo";
	av[1] = "1,2";
	av[2] = "eins";
	av[3] = "-baz=one,two,three";
	av[4] = "zwei";
	av[5] = "-bar:1,2,3,4";
	av[6] = "--baz=four";
	av[7] = "drei";
	av[8] = "-foo";
	av[9] = "3,4";
	av[10] = "vier";
	if (t5.parse(11, av) && checkArrays(foo, bar, baz, t5.leftovers()))
		ok++;

	if (ok == 3)
	{
		cout << "PASS" << endl;
	}
	else
	{
		cout << "FAIL" << endl;
		bad++;
	}

	return bad;
}
Example #26
-1
int
main (int argc, const char *argv[])
{
    Filesystem::convert_native_arguments (argc, (const char **)argv);
    ArgParse ap;
    ap.options ("iinfo -- print information about images\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  iinfo [options] filename...",
                "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose output",
                "-m %s", &metamatch, "Metadata names to print (default: all)",
                "-f", &filenameprefix, "Prefix each line with the filename",
                "-s", &sum, "Sum the image sizes",
                "-a", &subimages, "Print info about all subimages",
                "--hash", &compute_sha1, "Print SHA-1 hash of pixel values",
                "--stats", &compute_stats, "Print image pixel statistics (data window)",
                NULL);
    if (ap.parse(argc, argv) < 0 || filenames.empty()) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        return EXIT_FAILURE;
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (! metamatch.empty())
        field_re.assign (metamatch,
                         boost::regex::extended | boost::regex_constants::icase);

    // Find the longest filename
    size_t longestname = 0;
    BOOST_FOREACH (const std::string &s, filenames)
        longestname = std::max (longestname, s.length());
    longestname = std::min (longestname, (size_t)40);

    long long totalsize = 0;
    BOOST_FOREACH (const std::string &s, filenames) {
        ImageInput *in = ImageInput::open (s.c_str());
        if (! in) {
            std::string err = geterror();
            if (err.empty())
                err = Strutil::format ("Could not open \"%s\"", s.c_str());
            std::cerr << "iinfo: " << err << "\n";
            continue;
        }
        ImageSpec spec = in->spec();
        print_info (s, longestname, in, spec, verbose, sum, totalsize);
        in->close ();
        delete in;
    }