FileNameList osgDB::listAllAvailablePlugins() { FileNameList pluginFiles; std::string validExtension = ADDQUOTES(OSG_PLUGIN_EXTENSION); std::string pluginDirectoryName = std::string("osgPlugins-")+std::string(osgGetVersion()); std::string fullPath = osgDB::findLibraryFile(pluginDirectoryName); if (!fullPath.empty()) { osgDB::DirectoryContents contents = getDirectoryContents(fullPath); for(DirectoryContents::iterator itr = contents.begin(); itr != contents.end(); ++itr) { std::string::size_type pos = itr->find("osgdb_"); if (pos==std::string::npos) { continue; } std::string ext = getFileExtensionIncludingDot(*itr); if (ext != validExtension) { continue; } pluginFiles.push_back(fullPath + std::string("/")+*itr); } } return pluginFiles; }
/// Returns the absolute pathnames of all lyx local sockets in /// file system encoding. /// Parts stolen from lyx::support::DirList(). FileNameList lyxSockets(string const & dir, string const & pid) { FileNameList dirlist; FileName dirpath(dir + "/"); if (!dirpath.exists() || !dirpath.isDirectory()) { lyxerr << dir << " does not exist or is not a directory." << endl; return dirlist; } FileNameList dirs = dirpath.dirList(""); FileNameList::const_iterator it = dirs.begin(); FileNameList::const_iterator end = dirs.end(); for (; it != end; ++it) { if (!it->isDirectory()) continue; string const tmpdir = it->absFileName(); if (!contains(tmpdir, "lyx_tmpdir" + pid)) continue; FileName lyxsocket(tmpdir + "/lyxsocket"); if (lyxsocket.exists()) dirlist.push_back(lyxsocket); } return dirlist; }
bool OSGA_Archive::getFileNames(FileNameList& fileNameList) const { SERIALIZER(); fileNameList.clear(); fileNameList.reserve(_indexMap.size()); for(FileNamePositionMap::const_iterator itr=_indexMap.begin(); itr!=_indexMap.end(); ++itr) { fileNameList.push_back(itr->first); } return !fileNameList.empty(); }
/* * Use rsync dry run mode to compare the local log files in log_directory * with the log files in rsync_target and return what's missing. */ Validation<FileNameList> FileOps::log_files_not_on_target( const string& log_directory, const FileNameList& files, const string& rsync_target) const { if (files.size() == 0) { return FileNameList(); } auto file_paths = join_path(log_directory, files); const auto rsync_dry_run = list_of<string>(rsync_executable_name) (rsync_dry_run_flag) .range(RSYNC_FLAGS) .range(file_paths) (rsync_target); const auto rsync_output = do_rsync(rsync_dry_run); if (rsync_output.first != 0 && rsync_output.first != PARTIAL_TRANSFER && rsync_output.first != PARTIAL_TRANSFER_DUE_VANISHED_SOURCE) { return BarnError(string("Failed to retrieve sync list: ") + rsync_output.second); } auto missing_files = get_rsync_candidates(rsync_output.second); sort(missing_files.begin(), missing_files.end()); return missing_files; }
bool GetSpecificExtFiles(FileNameList &files, const OJString &path, const OJString &ext, const bool withPath) { files.clear(); return GetSpecificExtFilesImpl(files, path, ext, withPath); }
void PhotoArchive::getImageFileNameList(FileNameList& filenameList) { for(PhotoIndexList::const_iterator itr=_photoIndex.begin(); itr!=_photoIndex.end(); ++itr) { filenameList.push_back(std::string(itr->filename)); } }
bool p3d::getFileNames(osg::ArgumentParser& arguments, FileNameList& xmlFiles, FileNameList& normalFiles) { // note currently doesn't delete the loaded file entries from the command line yet... for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { std::string ext = osgDB::getFileExtension(arguments[pos]); if (osgDB::equalCaseInsensitive(ext,"xml") || osgDB::equalCaseInsensitive(ext,"p3d")) { xmlFiles.push_back(arguments[pos]); } else { normalFiles.push_back(arguments[pos]); } } } return (!xmlFiles.empty() || !normalFiles.empty()); }
FileNameList TestProject::getDependentFiles(const FileNameList &files) const { FileNameList dependentFiles; FileNameList uncheckedFiles = files; while (!uncheckedFiles.isEmpty ()) { FileName file = uncheckedFiles.takeFirst (); if (dependentFiles.contains (file)) { continue; } dependentFiles << file; FileName newName = shortenFileName (file); FileNameList newFiles = dependencyTable_.value (newName); if (!newFiles.isEmpty ()) { dependentFiles += newFiles; uncheckedFiles += newFiles; } } dependentFiles.removeDuplicates (); return dependentFiles; }
void PhotoArchive::buildArchive(const std::string& filename, const FileNameList& imageList, unsigned int thumbnailSize, unsigned int maximumSize, bool /*compressed*/) { PhotoIndexList photoIndex; photoIndex.reserve(imageList.size()); for(FileNameList::const_iterator fitr=imageList.begin(); fitr!=imageList.end(); ++fitr) { PhotoHeader header; // set name strncpy(header.filename,fitr->c_str(),255); header.filename[255]=0; header.thumbnail_s = thumbnailSize; header.thumbnail_t = thumbnailSize; header.thumbnail_position = 0; header.fullsize_s = thumbnailSize; header.fullsize_t = thumbnailSize; header.fullsize_position = 0; photoIndex.push_back(header); } std::cout<<"Building photo archive containing "<<photoIndex.size()<<" pictures"<<std::endl; // open up the archive for writing to osgDB::ofstream out(filename.c_str(), std::ios::out | std::ios::binary); // write out file indentifier. out.write(FILE_IDENTIFER.c_str(),FILE_IDENTIFER.size()); unsigned int numPhotos = photoIndex.size(); out.write((char*)&numPhotos,sizeof(unsigned int)); // write the photo index to ensure we can the correct amount of space // available. unsigned int startOfPhotoIndex = out.tellp(); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); unsigned int photoCount=1; for(PhotoIndexList::iterator pitr=photoIndex.begin(); pitr!=photoIndex.end(); ++pitr,++photoCount) { PhotoHeader& photoHeader = *pitr; std::cout<<"Processing image "<<photoCount<<" of "<< photoIndex.size()<<" filename="<< photoHeader.filename << std::endl; std::cout<<" reading image...";std::cout.flush(); osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(photoHeader.filename); std::cout<<"done."<< std::endl; photoHeader.original_s = image->s(); photoHeader.original_t = image->t(); { std::cout<<" creating thumbnail image..."; // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(thumbnailSize,image->getPixelFormat(),image->getDataType(),image->getPacking())* thumbnailSize; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } osg::PixelStorageModes psm; psm.pack_alignment = image->getPacking(); psm.pack_row_length = image->getRowLength(); psm.unpack_alignment = image->getPacking(); GLint status = osg::gluScaleImage(&psm, image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), thumbnailSize, thumbnailSize, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<osg::gluErrorString((GLenum)status)<<std::endl; return; } // now set up the photo header. photoHeader.thumbnail_s = thumbnailSize; photoHeader.thumbnail_t = thumbnailSize; photoHeader.thumbnail_position = (unsigned int)out.tellp(); // set up image header ImageHeader imageHeader; imageHeader.s = thumbnailSize; imageHeader.t = thumbnailSize; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; // write out image header and image data. out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } { std::cout<<" creating fullsize image...";std::cout.flush(); photoHeader.fullsize_s = osg::minimum((unsigned int)image->s(),maximumSize); photoHeader.fullsize_t = osg::minimum((unsigned int)image->t(),maximumSize); photoHeader.fullsize_position = (unsigned int)out.tellp(); // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(photoHeader.fullsize_s,image->getPixelFormat(),image->getDataType(),image->getPacking())* photoHeader.fullsize_t; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } osg::PixelStorageModes psm; psm.pack_alignment = image->getPacking(); psm.pack_row_length = image->getRowLength(); psm.unpack_alignment = image->getPacking(); GLint status = osg::gluScaleImage(&psm, image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), photoHeader.fullsize_s, photoHeader.fullsize_t, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<osg::gluErrorString((GLenum)status)<<std::endl; return; } ImageHeader imageHeader; imageHeader.s = photoHeader.fullsize_s; imageHeader.t = photoHeader.fullsize_t; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); //out.write((char*)image->data(),imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } } // rewrite photo index now it has the correct sizes set out.seekp(startOfPhotoIndex); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is an application for collecting a set of seperate files into a single archive file that can be later read in OSG applications.."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } std::string archiveFilename; while (arguments.read("-a",archiveFilename) || arguments.read("--archive",archiveFilename)) { } bool insert = false; while (arguments.read("-i") || arguments.read("--insert")) { insert = true; } bool extract = false; while (arguments.read("-e") || arguments.read("--extract")) { extract = true; } bool list = false; while (arguments.read("-l") || arguments.read("--list")) { list = true; } typedef std::vector<std::string> FileNameList; FileNameList files; for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { if (insert) { std::string filePath = osgDB::findDataFile(arguments[pos]); osgDB::FileType fileType = osgDB::fileType(filePath); if (fileType==osgDB::REGULAR_FILE) { files.push_back(arguments[pos]); } else if (fileType==osgDB::DIRECTORY) { osgDB::DirectoryContents directory = osgDB::getDirectoryContents(arguments[pos]); osgDB::DirectoryContents::iterator it = directory.begin(); while( it != directory.end()) { files.push_back(filePath + "/" + (*it)); ++it; } } } else { files.push_back(arguments[pos]); } } } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (archiveFilename.empty()) { std::cout<<"Please specify an archive name using --archive filename"<<std::endl; return 1; } if (!insert && !extract && !list) { std::cout<<"Please specify an operation on the archive, either --insert, --extract or --list"<<std::endl; return 1; } if (insert && extract) { std::cout<<"Cannot insert and extract files from the archive at one time, please use either --insert or --extract."<<std::endl; return 1; } osg::ref_ptr<osgDB::Archive> archive; if (insert) { archive = osgDB::openArchive(archiveFilename, osgDB::Archive::WRITE); if (archive.valid()) { for (FileNameList::iterator itr=files.begin(); itr!=files.end(); ++itr) { std::cout<<"reading "<<*itr<<std::endl; osg::ref_ptr<osg::Object> obj = osgDB::readObjectFile(*itr); if (obj.valid()) { std::cout<<" write to archive "<<*itr<<std::endl; archive->writeObject(*obj, *itr); } } } } else { archive = osgDB::openArchive(archiveFilename, osgDB::Archive::READ); if (extract && archive.valid()) { for (FileNameList::iterator itr=files.begin(); itr!=files.end(); ++itr) { osg::Timer_t start = osg::Timer::instance()->tick(); osgDB::ReaderWriter::ReadResult result = archive->readObject(*itr); osg::ref_ptr<osg::Object> obj = result.getObject(); std::cout<<"readObejct time = "<<osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick())<<std::endl; if (obj.valid()) { osgDB::writeObjectFile(*obj, *itr); } } } } if (list && archive.valid()) { std::cout<<"List of files in archive:"<<std::endl; osgDB::Archive::FileNameList fileNames; if (archive->getFileNames(fileNames)) { for(osgDB::Archive::FileNameList::const_iterator itr=fileNames.begin(); itr!=fileNames.end(); ++itr) { std::cout<<" "<<*itr<<std::endl; } } std::cout<<std::endl; std::cout<<"Master file "<<archive->getMasterFileName()<<std::endl; } return 0; }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a utility for converting between various input and output databases formats."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); //arguments.getApplicationUsage()->addCommandLineOption("--formats","List supported file formats"); //arguments.getApplicationUsage()->addCommandLineOption("--plugins","List database olugins"); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { osg::setNotifyLevel(osg::NOTICE); usage( arguments.getApplicationName().c_str(), 0 ); //arguments.getApplicationUsage()->write(std::cout); return 1; } if (arguments.read("--help-env")) { arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE); return 1; } if (arguments.read("--plugins")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { std::cout<<"Plugin "<<*itr<<std::endl; } return 0; } std::string plugin; if (arguments.read("--plugin", plugin)) { osgDB::outputPluginDetails(std::cout, plugin); return 0; } std::string ext; if (arguments.read("--format", ext)) { plugin = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::outputPluginDetails(std::cout, plugin); return 0; } if (arguments.read("--formats")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { osgDB::outputPluginDetails(std::cout,*itr); } return 0; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } FileNameList fileNames; OrientationConverter oc; bool do_convert = false; if (arguments.read("--use-world-frame")) { oc.useWorldFrame(true); } std::string str; while (arguments.read("-O",str)) { osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options; options->setOptionString(str); osgDB::Registry::instance()->setOptions(options); } while (arguments.read("-e",ext)) { std::string libName = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::Registry::instance()->loadLibrary(libName); } std::string libName; while (arguments.read("-l",libName)) { osgDB::Registry::instance()->loadLibrary(libName); } while (arguments.read("-o",str)) { osg::Vec3 from, to; if( sscanf( str.c_str(), "%f,%f,%f-%f,%f,%f", &from[0], &from[1], &from[2], &to[0], &to[1], &to[2] ) != 6 ) { float degrees; osg::Vec3 axis; // Try deg-axis format if( sscanf( str.c_str(), "%f-%f,%f,%f", °rees, &axis[0], &axis[1], &axis[2] ) != 4 ) { usage( argv[0], "Orientation argument format incorrect." ); return 1; } else { oc.setRotation( degrees, axis ); do_convert = true; } } else { oc.setRotation( from, to ); do_convert = true; } } while (arguments.read("-s",str)) { osg::Vec3 scale(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &scale[0], &scale[1], &scale[2] ) != 3 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } oc.setScale( scale ); do_convert = true; } float simplifyPercent = 1.0; bool do_simplify = false; while ( arguments.read( "--simplify",str ) ) { float nsimp = 1.0; if( sscanf( str.c_str(), "%f", &nsimp ) != 1 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } std::cout << str << " " << nsimp << std::endl; simplifyPercent = nsimp; osg::notify( osg::INFO ) << "Simplifying with percentage: " << simplifyPercent << std::endl; do_simplify = true; } while (arguments.read("-t",str)) { osg::Vec3 trans(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &trans[0], &trans[1], &trans[2] ) != 3 ) { usage( argv[0], "Translation argument format incorrect." ); return 1; } oc.setTranslation( trans ); do_convert = true; } FixTransparencyVisitor::FixTransparencyMode fixTransparencyMode = FixTransparencyVisitor::NO_TRANSPARANCY_FIXING; std::string fixString; while(arguments.read("--fix-transparency")) fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; while(arguments.read("--fix-transparency-mode",fixString)) { if (fixString=="MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; if (fixString=="MAKE_ALL_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_ALL_STATESET_OPAQUE; }; bool pruneStateSet = false; while(arguments.read("--prune-StateSet")) pruneStateSet = true; osg::Texture::InternalFormatMode internalFormatMode = osg::Texture::USE_IMAGE_DATA_FORMAT; while(arguments.read("--compressed") || arguments.read("--compressed-arb")) { internalFormatMode = osg::Texture::USE_ARB_COMPRESSION; } while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; } while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; } while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; } bool smooth = false; while(arguments.read("--smooth")) { smooth = true; } bool addMissingColours = false; while(arguments.read("--addMissingColours") || arguments.read("--addMissingColors")) { addMissingColours = true; } bool do_overallNormal = false; while(arguments.read("--overallNormal") || arguments.read("--overallNormal")) { do_overallNormal = true; } bool enableObjectCache = false; while(arguments.read("--enable-object-cache")) { enableObjectCache = true; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { fileNames.push_back(arguments[pos]); } } if (enableObjectCache) { if (osgDB::Registry::instance()->getOptions()==0) osgDB::Registry::instance()->setOptions(new osgDB::Options()); osgDB::Registry::instance()->getOptions()->setObjectCacheHint(osgDB::Options::CACHE_ALL); } std::string fileNameOut("converted.osg"); if (fileNames.size()>1) { fileNameOut = fileNames.back(); fileNames.pop_back(); } osg::Timer_t startTick = osg::Timer::instance()->tick(); osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(fileNames); if (root.valid()) { osg::Timer_t endTick = osg::Timer::instance()->tick(); osg::notify(osg::INFO)<<"Time to load files "<<osg::Timer::instance()->delta_m(startTick, endTick)<<" ms"<<std::endl; } if (pruneStateSet) { PruneStateSetVisitor pssv; root->accept(pssv); } if (fixTransparencyMode != FixTransparencyVisitor::NO_TRANSPARANCY_FIXING) { FixTransparencyVisitor atv(fixTransparencyMode); root->accept(atv); } if ( root.valid() ) { if (smooth) { osgUtil::SmoothingVisitor sv; root->accept(sv); } if (addMissingColours) { AddMissingColoursToGeometryVisitor av; root->accept(av); } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(root.get()); if( do_convert ) root = oc.convert( root.get() ); if (internalFormatMode != osg::Texture::USE_IMAGE_DATA_FORMAT) { std::string ext = osgDB::getFileExtension(fileNameOut); CompressTexturesVisitor ctv(internalFormatMode); root->accept(ctv); ctv.compress(); osgDB::ReaderWriter::Options *options = osgDB::Registry::instance()->getOptions(); if (ext!="ive" || (options && options->getOptionString().find("noTexturesInIVEFile")!=std::string::npos)) { ctv.write(osgDB::getFilePath(fileNameOut)); } } // scrub normals if ( do_overallNormal ) { DefaultNormalsGeometryVisitor dngv; root->accept( dngv ); } // apply any user-specified simplification if ( do_simplify ) { osgUtil::Simplifier simple; simple.setSmoothing( smooth ); osg::notify( osg::ALWAYS ) << " smoothing: " << smooth << std::endl; simple.setSampleRatio( simplifyPercent ); root->accept( simple ); } osgDB::ReaderWriter::WriteResult result = osgDB::Registry::instance()->writeNode(*root,fileNameOut,osgDB::Registry::instance()->getOptions()); if (result.success()) { osg::notify(osg::NOTICE)<<"Data written to '"<<fileNameOut<<"'."<< std::endl; } else if (result.message().empty()) { osg::notify(osg::NOTICE)<<"Warning: file write to '"<<fileNameOut<<"' not supported."<< std::endl; } else { osg::notify(osg::NOTICE)<<result.message()<< std::endl; } } else { osg::notify(osg::NOTICE)<<"Error no data loaded."<< std::endl; return 1; } return 0; }
int main(int argc, char *argv[]) { using Teuchos::RCP; // Communicators Teuchos::GlobalMPISession mpiSession(&argc, &argv); const Albany_MPI_Comm nativeComm = Albany_MPI_COMM_WORLD; const RCP<const Teuchos::Comm<int> > teuchosComm = Albany::createTeuchosCommFromMpiComm(nativeComm); const RCP<const Epetra_Comm> epetraComm = Albany::createEpetraCommFromMpiComm(nativeComm); // Standard output const RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); // Parse command-line argument for input file const std::string firstArg = (argc > 1) ? argv[1] : ""; if (firstArg.empty() || firstArg == "--help") { *out << "AlbanyRBGen input-file-path\n"; return 0; } const std::string inputFileName = argv[1]; // Parse XML input file const RCP<Teuchos::ParameterList> topLevelParams = Teuchos::createParameterList("Albany Parameters"); Teuchos::updateParametersFromXmlFileAndBroadcast(inputFileName, topLevelParams.ptr(), *teuchosComm); // Create base discretization, used to retrieve the snapshot map and output the basis const Teuchos::RCP<Teuchos::ParameterList> baseTopLevelParams(new Teuchos::ParameterList(*topLevelParams)); const RCP<Albany::AbstractDiscretization> baseDisc = Albany::discretizationNew(baseTopLevelParams, epetraComm); const RCP<Teuchos::ParameterList> rbgenParams = Teuchos::sublist(topLevelParams, "Reduced Basis", /*sublistMustExist =*/ true); typedef Teuchos::Array<std::string> FileNameList; FileNameList snapshotFiles; { const RCP<Teuchos::ParameterList> snapshotSourceParams = Teuchos::sublist(rbgenParams, "Snapshot Sources"); snapshotFiles = snapshotSourceParams->get("File Names", snapshotFiles); } typedef Teuchos::Array<RCP<Albany::STKDiscretization> > DiscretizationList; DiscretizationList discretizations; if (snapshotFiles.empty()) { discretizations.push_back(Teuchos::rcp_dynamic_cast<Albany::STKDiscretization>(baseDisc, /*throw_on_fail =*/ true)); } else { discretizations.reserve(snapshotFiles.size()); for (FileNameList::const_iterator it = snapshotFiles.begin(), it_end = snapshotFiles.end(); it != it_end; ++it) { const Teuchos::RCP<Teuchos::ParameterList> localTopLevelParams(new Teuchos::ParameterList(*topLevelParams)); { // Replace discretization parameters to read snapshot file Teuchos::ParameterList localDiscParams; localDiscParams.set("Method", "Ioss"); localDiscParams.set("Exodus Input File Name", *it); localTopLevelParams->set("Discretization", localDiscParams); } const RCP<Albany::AbstractDiscretization> disc = Albany::discretizationNew(localTopLevelParams, epetraComm); discretizations.push_back(Teuchos::rcp_dynamic_cast<Albany::STKDiscretization>(disc, /*throw_on_fail =*/ true)); } } typedef Teuchos::Array<RCP<MOR::EpetraMVSource> > SnapshotSourceList; SnapshotSourceList snapshotSources; for (DiscretizationList::const_iterator it = discretizations.begin(), it_end = discretizations.end(); it != it_end; ++it) { snapshotSources.push_back(Teuchos::rcp(new Albany::StkEpetraMVSource(*it))); } MOR::ConcatenatedEpetraMVSource snapshotSource(*baseDisc->getMap(), snapshotSources); *out << "Total snapshot count = " << snapshotSource.vectorCount() << "\n"; const Teuchos::RCP<Epetra_MultiVector> rawSnapshots = snapshotSource.multiVectorNew(); // Isolate Dirichlet BC RCP<const Epetra_Vector> blockVector; if (rbgenParams->isSublist("Blocking")) { const RCP<const Teuchos::ParameterList> blockingParams = Teuchos::sublist(rbgenParams, "Blocking"); const Teuchos::Array<int> mySelectedLIDs = getMyBlockLIDs(*blockingParams, *baseDisc); *out << "Selected LIDs = " << mySelectedLIDs << "\n"; blockVector = MOR::isolateUniformBlock(mySelectedLIDs, *rawSnapshots); } // Preprocess raw snapshots const RCP<Teuchos::ParameterList> preprocessingParams = Teuchos::sublist(rbgenParams, "Snapshot Preprocessing"); MOR::SnapshotPreprocessorFactory preprocessorFactory; const Teuchos::RCP<MOR::SnapshotPreprocessor> snapshotPreprocessor = preprocessorFactory.instanceNew(preprocessingParams); snapshotPreprocessor->rawSnapshotSetIs(rawSnapshots); const RCP<const Epetra_MultiVector> modifiedSnapshots = snapshotPreprocessor->modifiedSnapshotSet(); const RCP<const Epetra_Vector> origin = snapshotPreprocessor->origin(); const bool nonzeroOrigin = Teuchos::nonnull(origin); *out << "After preprocessing, " << modifiedSnapshots->NumVectors() << " snapshot vectors and " << static_cast<int>(nonzeroOrigin) << " origin\n"; // By default, compute as many basis vectors as snapshots (void) Teuchos::sublist(rbgenParams, "Reduced Basis Method")->get("Basis Size", modifiedSnapshots->NumVectors()); // Compute reduced basis RBGen::EpetraMVMethodFactory methodFactory; const RCP<RBGen::Method<Epetra_MultiVector, Epetra_Operator> > method = methodFactory.create(*rbgenParams); method->Initialize(rbgenParams, modifiedSnapshots); method->computeBasis(); const RCP<const Epetra_MultiVector> basis = method->getBasis(); *out << "Computed " << basis->NumVectors() << " left-singular vectors\n"; // Compute discarded energy fraction for each left-singular vector // (relative residual energy corresponding to a basis truncation after current vector) const RCP<const RBGen::PODMethod<double> > pod_method = Teuchos::rcp_dynamic_cast<RBGen::PODMethod<double> >(method); const Teuchos::Array<double> singularValues = pod_method->getSingularValues(); *out << "Singular values: " << singularValues << "\n"; const Teuchos::Array<double> discardedEnergyFractions = MOR::computeDiscardedEnergyFractions(singularValues); *out << "Discarded energy fractions: " << discardedEnergyFractions << "\n"; // Output results { // Setup overlapping map and vector const Epetra_Map outputMap = *baseDisc->getOverlapMap(); const Epetra_Import outputImport(outputMap, snapshotSource.vectorMap()); Epetra_Vector outputVector(outputMap, /*zeroOut =*/ false); if (nonzeroOrigin) { const double stamp = -1.0; // Stamps must be increasing outputVector.Import(*origin, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } if (Teuchos::nonnull(blockVector)) { const double stamp = -1.0 + std::numeric_limits<double>::epsilon(); TEUCHOS_ASSERT(stamp != -1.0); outputVector.Import(*blockVector, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } for (int i = 0; i < basis->NumVectors(); ++i) { const double stamp = -discardedEnergyFractions[i]; // Stamps must be increasing const Epetra_Vector vec(View, *basis, i); outputVector.Import(vec, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } } }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a utility for converting between various input and output databases formats."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); //arguments.getApplicationUsage()->addCommandLineOption("--formats","List supported file formats"); //arguments.getApplicationUsage()->addCommandLineOption("--plugins","List database olugins"); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { osg::setNotifyLevel(osg::NOTICE); usage( arguments.getApplicationName().c_str(), 0 ); //arguments.getApplicationUsage()->write(std::cout); return 1; } if (arguments.read("--help-env")) { arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE); return 1; } if (arguments.read("--plugins")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { std::cout<<"Plugin "<<*itr<<std::endl; } return 0; } std::string plugin; if (arguments.read("--plugin", plugin)) { osgDB::outputPluginDetails(std::cout, plugin); return 0; } std::string ext; if (arguments.read("--format", ext)) { plugin = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::outputPluginDetails(std::cout, plugin); return 0; } if (arguments.read("--formats")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { osgDB::outputPluginDetails(std::cout,*itr); } return 0; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } FileNameList fileNames; OrientationConverter oc; bool do_convert = false; if (arguments.read("--use-world-frame")) { oc.useWorldFrame(true); } std::string str; while (arguments.read("-O",str)) { osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options; options->setOptionString(str); osgDB::Registry::instance()->setOptions(options); } while (arguments.read("-e",ext)) { std::string libName = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::Registry::instance()->loadLibrary(libName); } std::string libName; while (arguments.read("-l",libName)) { osgDB::Registry::instance()->loadLibrary(libName); } while (arguments.read("-o",str)) { osg::Vec3 from, to; if( sscanf( str.c_str(), "%f,%f,%f-%f,%f,%f", &from[0], &from[1], &from[2], &to[0], &to[1], &to[2] ) != 6 ) { float degrees; osg::Vec3 axis; // Try deg-axis format if( sscanf( str.c_str(), "%f-%f,%f,%f", °rees, &axis[0], &axis[1], &axis[2] ) != 4 ) { usage( argv[0], "Orientation argument format incorrect." ); return 1; } else { oc.setRotation( degrees, axis ); do_convert = true; } } else { oc.setRotation( from, to ); do_convert = true; } } while (arguments.read("-s",str)) { osg::Vec3 scale(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &scale[0], &scale[1], &scale[2] ) != 3 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } oc.setScale( scale ); do_convert = true; } float simplifyPercent = 1.0; bool do_simplify = false; while ( arguments.read( "--simplify",str ) ) { float nsimp = 1.0; if( sscanf( str.c_str(), "%f", &nsimp ) != 1 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } std::cout << str << " " << nsimp << std::endl; simplifyPercent = nsimp; osg::notify( osg::INFO ) << "Simplifying with percentage: " << simplifyPercent << std::endl; do_simplify = true; } while (arguments.read("-t",str)) { osg::Vec3 trans(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &trans[0], &trans[1], &trans[2] ) != 3 ) { usage( argv[0], "Translation argument format incorrect." ); return 1; } oc.setTranslation( trans ); do_convert = true; } FixTransparencyVisitor::FixTransparencyMode fixTransparencyMode = FixTransparencyVisitor::NO_TRANSPARANCY_FIXING; std::string fixString; while(arguments.read("--fix-transparency")) fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; while(arguments.read("--fix-transparency-mode",fixString)) { if (fixString=="MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; if (fixString=="MAKE_ALL_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_ALL_STATESET_OPAQUE; }; bool pruneStateSet = false; while(arguments.read("--prune-StateSet")) pruneStateSet = true; osg::Texture::InternalFormatMode internalFormatMode = osg::Texture::USE_IMAGE_DATA_FORMAT; while(arguments.read("--compressed") || arguments.read("--compressed-arb")) { internalFormatMode = osg::Texture::USE_ARB_COMPRESSION; } while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; } while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; } while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; } bool smooth = false; while(arguments.read("--smooth")) { smooth = true; } bool addMissingColours = false; while(arguments.read("--addMissingColours") || arguments.read("--addMissingColors")) { addMissingColours = true; } bool do_overallNormal = false; while(arguments.read("--overallNormal") || arguments.read("--overallNormal")) { do_overallNormal = true; } bool enableObjectCache = false; while(arguments.read("--enable-object-cache")) { enableObjectCache = true; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { fileNames.push_back(arguments[pos]); } } if (enableObjectCache) { if (osgDB::Registry::instance()->getOptions()==0) osgDB::Registry::instance()->setOptions(new osgDB::Options()); osgDB::Registry::instance()->getOptions()->setObjectCacheHint(osgDB::Options::CACHE_ALL); } std::string fileNameOut("converted.osg"); if (fileNames.size()>1) { fileNameOut = fileNames.back(); fileNames.pop_back(); } osg::Timer_t startTick = osg::Timer::instance()->tick(); osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(fileNames); if (root.valid()) { osg::Timer_t endTick = osg::Timer::instance()->tick(); osg::notify(osg::INFO)<<"Time to load files "<<osg::Timer::instance()->delta_m(startTick, endTick)<<" ms"<<std::endl; } if (pruneStateSet) { PruneStateSetVisitor pssv; root->accept(pssv); } if (fixTransparencyMode != FixTransparencyVisitor::NO_TRANSPARANCY_FIXING) { FixTransparencyVisitor atv(fixTransparencyMode); root->accept(atv); } if ( root.valid() ) { if (smooth) { osgUtil::SmoothingVisitor sv; root->accept(sv); } if (addMissingColours) { AddMissingColoursToGeometryVisitor av; root->accept(av); } auto to_lower = std::bind(&boost::to_lower_copy<std::string>,std::placeholders::_1,std::locale()); // all names to lower Utils::CommonVisitor<osg::Node> names_lower( [=](osg::Node& n)->void { n.setName(to_lower(n.getName())); }); root->accept(names_lower); // optimize the scene graph, remove rendundent nodes and state etc. osgUtil::Optimizer optimizer; FindNodeVisitor::nodeNamesList list_name; for(int i=0; i<sizeof(do_not_optimize::names)/sizeof(do_not_optimize::names[0]);++i) { list_name.push_back(do_not_optimize::names[i]); } FindNodeVisitor findNodes(list_name,FindNodeVisitor::not_exact); root->accept(findNodes); const FindNodeVisitor::nodeListType& wln_list = findNodes.getNodeList(); for(auto it = wln_list.begin(); it != wln_list.end(); ++it ) { optimizer.setPermissibleOptimizationsForObject(*it,0); } optimizer.optimize(root.get(), osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS | osgUtil::Optimizer::REMOVE_REDUNDANT_NODES | osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES | osgUtil::Optimizer::STATIC_OBJECT_DETECTION ); boost::filesystem::path pathFileOut(fileNameOut); std::string base_file_name = pathFileOut.parent_path().string() + "/" + pathFileOut.stem().string(); cg::point_3 offset; bool res = generateBulletFile(base_file_name + ".bullet", root, offset); if (res) { osg::notify(osg::NOTICE)<<"Data written to '"<< base_file_name + ".bullet"<<"'."<< std::endl; } else { osg::notify(osg::NOTICE)<< "Error Occurred While Writing to "<< base_file_name + ".bullet"<< std::endl; } osg::Group* newroot = dynamic_cast<osg::Group*>(findFirstNode(root,"Root")); if(newroot==nullptr) { newroot = new osg::Group; newroot->setName("Root"); newroot->addChild( root ); root = newroot; } std::ofstream filelogic( base_file_name + ".stbin", std::ios_base::binary ); std::ofstream logfile ( base_file_name + std::string("_structure") + ".txt" ); heilVisitor hv(filelogic, logfile, offset); hv.apply(*root.get()); if( do_convert ) root = oc.convert( root.get() ); FIXME(Without textures useless) #if 0 const std::string name = pathFileOut.stem().string(); osgDB::FilePathList fpl_; fpl_.push_back(pathFileOut.parent_path().string() + "/"); std::string mat_file_name = osgDB::findFileInPath(name+".dae.mat.xml", /*fpl.*/fpl_,osgDB::CASE_INSENSITIVE); MaterialVisitor::namesList nl; nl.push_back("building"); nl.push_back("default"); nl.push_back("tree"); nl.push_back("ground"); nl.push_back("concrete"); nl.push_back("mountain"); nl.push_back("sea"); nl.push_back("railing"); nl.push_back("panorama"); nl.push_back("plane"); //nl.push_back("rotor"); /// �ללללללללללללל נאסךמלוםעאנטע� ט הטםאלטקוסךטי ףבתועס� MaterialVisitor mv ( nl, std::bind(&creators::createMaterial,sp::_1,sp::_2,name,sp::_3,sp::_4),creators::computeAttributes,mat::reader::read(mat_file_name)); root->accept(mv); #endif if (internalFormatMode != osg::Texture::USE_IMAGE_DATA_FORMAT) { std::string ext = osgDB::getFileExtension(fileNameOut); CompressTexturesVisitor ctv(internalFormatMode); root->accept(ctv); ctv.compress(); osgDB::ReaderWriter::Options *options = osgDB::Registry::instance()->getOptions(); if (ext!="ive" || (options && options->getOptionString().find("noTexturesInIVEFile")!=std::string::npos)) { ctv.write(osgDB::getFilePath(fileNameOut)); } } // scrub normals if ( do_overallNormal ) { DefaultNormalsGeometryVisitor dngv; root->accept( dngv ); } // apply any user-specified simplification if ( do_simplify ) { osgUtil::Simplifier simple; simple.setSmoothing( smooth ); osg::notify( osg::ALWAYS ) << " smoothing: " << smooth << std::endl; simple.setSampleRatio( simplifyPercent ); root->accept( simple ); } osgDB::ReaderWriter::WriteResult result = osgDB::Registry::instance()->writeNode(*root,fileNameOut,osgDB::Registry::instance()->getOptions()); if (result.success()) { osg::notify(osg::NOTICE)<<"Data written to '"<<fileNameOut<<"'."<< std::endl; } else if (result.message().empty()) { osg::notify(osg::NOTICE)<<"Warning: file write to '"<<fileNameOut<<"' not supported."<< std::endl; } else { osg::notify(osg::NOTICE)<<result.message()<< std::endl; } } else {
int main(int argc, char * argv[]) { using namespace lyx; lyxerr.setStream(cerr); char const * const lyxsocket = getenv("LYXSOCKET"); if (lyxsocket) cmdline::serverAddress = from_local8bit(lyxsocket); CmdLineParser args; args.helper["-h"] = cmdline::h; args.helper["-c"] = cmdline::c; args.helper["-g"] = cmdline::g; args.helper["-n"] = cmdline::n; args.helper["-a"] = cmdline::a; args.helper["-t"] = cmdline::t; args.helper["-p"] = cmdline::p; // Command line failure conditions: if ((!args.parse(argc, argv)) || (args.isset["-c"] && args.isset["-g"]) || (args.isset["-a"] && args.isset["-p"])) { cmdline::usage(); return 1; } scoped_ptr<LyXDataSocket> server; if (!cmdline::serverAddress.empty()) { server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress)))); if (!server->connected()) { cerr << "lyxclient: " << "Could not connect to " << to_utf8(cmdline::serverAddress) << endl; return EXIT_FAILURE; } } else { // We have to look for an address. // serverPid can be empty. FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid); FileNameList::const_iterator addr = addrs.begin(); FileNameList::const_iterator end = addrs.end(); for (; addr != end; ++addr) { // Caution: addr->string() is in filesystem encoding server.reset(new LyXDataSocket(*addr)); if (server->connected()) break; lyxerr << "lyxclient: " << "Could not connect to " << addr->absFileName() << endl; } if (addr == end) { lyxerr << "lyxclient: No suitable server found." << endl; return EXIT_FAILURE; } cerr << "lyxclient: " << "Connected to " << addr->absFileName() << endl; } int const serverfd = server->fd(); IOWatch iowatch; iowatch.addfd(serverfd); // Used to read from server string answer; // Send greeting server->writeln("HELLO:" + to_utf8(cmdline::clientName)); // wait at most 2 seconds until server responds iowatch.wait(2.0); if (iowatch.isset(serverfd) && server->readln(answer)) { if (prefixIs(answer, "BYE:")) { cerr << "lyxclient: Server disconnected." << endl; cout << answer << endl; return EXIT_FAILURE; } } else { cerr << "lyxclient: No answer from server." << endl; return EXIT_FAILURE; } if (args.isset["-g"] || args.isset["-c"]) { server->writeln(to_utf8(cmdline::singleCommand)); iowatch.wait(2.0); if (iowatch.isset(serverfd) && server->readln(answer)) { cout << answer; if (prefixIs(answer, "ERROR:")) return EXIT_FAILURE; return EXIT_SUCCESS; } else { cerr << "lyxclient: No answer from server." << endl; return EXIT_FAILURE; } } // Take commands from stdin iowatch.addfd(0); // stdin bool saidbye = false; while ((!saidbye) && server->connected()) { iowatch.wait(); if (iowatch.isset(0)) { string command; getline(cin, command); if (command.empty()) continue; if (command == "BYE:") { server->writeln("BYE:"); saidbye = true; } else { server->writeln("LYXCMD:" + command); } } if (iowatch.isset(serverfd)) { while(server->readln(answer)) cout << answer << endl; } } return EXIT_SUCCESS; }