Example #1
1
QString AndroidToolChain::makeCommand(const Environment &env) const
{
    FileName makePath = AndroidConfigurations::currentConfig().makePath();
    if (makePath.exists())
        return makePath.toString();
    const Utils::FileNameList extraDirectories
            = Utils::transform(AndroidConfigurations::currentConfig().makeExtraSearchDirectories(),
                               [](const QString &s) { return Utils::FileName::fromString(s); });
    if (HostOsInfo::isWindowsHost()) {
        makePath = env.searchInPath("ma-make.exe", extraDirectories);
        if (!makePath.isEmpty())
            return makePath.toString();
        makePath = env.searchInPath("mingw32-make", extraDirectories);
        return makePath.isEmpty() ? QLatin1String("mingw32-make") : makePath.toString();
    }

    makePath = env.searchInPath("make", extraDirectories);
    return makePath.isEmpty() ? "make" : makePath.toString();
}
void QmakeKitInformation::setup(Kit *k)
{
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
    if (!version)
        return;

    FileName spec = QmakeKitInformation::mkspec(k);
    if (spec.isEmpty())
        spec = version->mkspec();

    ToolChain *tc = ToolChainKitInformation::toolChain(k);

    if (!tc || (!tc->suggestedMkspecList().empty() && !tc->suggestedMkspecList().contains(spec))) {
        ToolChain *possibleTc = 0;
        foreach (ToolChain *current, ToolChainManager::toolChains()) {
            if (version->qtAbis().contains(current->targetAbi())) {
                possibleTc = current;
                if (current->suggestedMkspecList().contains(spec))
                    break;
            }
        }
        ToolChainKitInformation::setToolChain(k, possibleTc);
    }
Example #3
0
// DataIO_OpenDx::ReadData()
int DataIO_OpenDx::ReadData(FileName const& fname, 
                            DataSetList& datasetlist, std::string const& dsname)
{
  // Add grid data set. Default to float for now.
  DataSet* ds = datasetlist.AddSet( DataSet::GRID_FLT, dsname, "GRID" );
  if (ds==0) return 1;
  if (LoadGrid(fname.full(), *ds)) {
    // Load failed. Erase grid data set.
    datasetlist.RemoveSet( ds );
    return 1;
  }
  return 0;
}
Example #4
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    if (g_numThreads) 
      g_rtcore += ",threads=" + std::stringOf(g_numThreads);
    if (g_numBenchmarkFrames)
      g_rtcore += ",benchmark=1";

    /* load scene */
    if (filename.str() != "")
      loadOBJ(filename,one,g_obj_scene);

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* send model */
    set_scene(&g_obj_scene);
    
    /* benchmark mode */
    if (g_numBenchmarkFrames)
      renderBenchmark(outFilename);
    
    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);
    
    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop();
    }

    return 0;
  }
Example #5
0
///
/// Returns all arguments
/// That is: possbile subpath
/// spec
/// config arguemnts
/// moreArguments
/// user arguments
QString QMakeStep::allArguments(bool shorted)
{
    QmakeBuildConfiguration *bc = qmakeBuildConfiguration();
    QStringList arguments;
    if (bc->subNodeBuild())
        arguments << QDir::toNativeSeparators(bc->subNodeBuild()->path());
    else if (shorted)
        arguments << QDir::toNativeSeparators(QFileInfo(project()->projectFilePath()).fileName());
    else
        arguments << QDir::toNativeSeparators(project()->projectFilePath());

    arguments << QLatin1String("-r");
    bool userProvidedMkspec = false;
    for (QtcProcess::ConstArgIterator ait(m_userArgs); ait.next(); ) {
        if (ait.value() == QLatin1String("-spec")) {
            if (ait.next()) {
                userProvidedMkspec = true;
                break;
            }
        }
    }
    FileName specArg = mkspec();
    if (!userProvidedMkspec && !specArg.isEmpty())
        arguments << QLatin1String("-spec") << specArg.toUserOutput();

    // Find out what flags we pass on to qmake
    arguments << bc->configCommandLineArguments();

    arguments << deducedArguments();

    QString args = QtcProcess::joinArgs(arguments);
    // User arguments
    QtcProcess::addArgs(&args, m_userArgs);
    // moreArgumentsAfter
    foreach (const QString &arg, deducedArgumentsAfter())
        QtcProcess::addArg(&args, arg);
    return args;
}
Example #6
0
SubversionResponse SubversionPlugin::runSvn(const QString &workingDir,
                          const QStringList &arguments, int timeOut,
                          unsigned flags, QTextCodec *outputCodec) const
{
    const FileName executable = m_settings.binaryPath();
    SubversionResponse response;
    if (executable.isEmpty()) {
        response.error = true;
        response.message =tr("No subversion executable specified.");
        return response;
    }

    const SynchronousProcessResponse sp_resp =
            VcsBasePlugin::runVcs(workingDir, executable, arguments, timeOut,
                                           flags, outputCodec);

    response.error = sp_resp.result != SynchronousProcessResponse::Finished;
    if (response.error)
        response.message = sp_resp.exitMessage(executable.toString(), timeOut);
    response.stdErr = sp_resp.stdErr;
    response.stdOut = sp_resp.stdOut;
    return response;
}
Example #7
0
void TestProject::checkCurrent()
{
  Project* project = SessionManager::startupProject ();
  CustomRunConfiguration* configuration = parse (project);
  if (configuration == NULL)
  {
    return;
  }

  IDocument* document = EditorManager::currentDocument ();
  if (document == NULL)
  {
    return;
  }
  FileName file = document->filePath();
  QStringList files = project->files (Project::ExcludeGeneratedFiles);
  if (!files.contains (file.toString ()))
  {
    return;
  }

  runTestsForFiles (FileNameList () << file, configuration);
}
Example #8
0
  /*! store an EXR file to disk */
  void storeExr(const Ref<Image>& img, const FileName& filename)
  {
    Imf::Array2D<Imf::Rgba> pixels(img->height,img->width);
    for (size_t y=0; y<img->height; y++) {
      for (size_t x=0; x<img->width; x++) {
        const Color4 c = img->get(x,y);
        pixels[y][x] = Imf::Rgba(c.r,c.g,c.b,c.a);
      }
    }

    Imf::RgbaOutputFile file(filename.c_str(), img->width, img->height, Imf::WRITE_RGBA);
    file.setFrameBuffer(&pixels[0][0], 1, img->width);
    file.writePixels(img->height);
  }
Example #9
0
bool IOMapOTMM::loadMap(Map& map, const FileName& identifier, bool showdialog) {
	if(showdialog) gui.CreateLoadBar(wxT("Loading OTMM map..."));
	DiskNodeFileReadHandle f(nstr(identifier.GetFullPath()));
	if(f.isOk() == false) {
		error(wxT("Couldn't open file for reading\nThe error reported was: ") + wxstr(f.getErrorMessage()));
		return false;
	}

	bool ret = loadMap(map, f, identifier, showdialog);

	if(showdialog) gui.DestroyLoadBar();

	return ret;
}
Example #10
0
bool Materials::unserializeMaterials(const FileName& filename, pugi::xml_node node, wxString& error, wxArrayString& warnings)
{
	wxString warning;
	pugi::xml_attribute attribute;
	for(pugi::xml_node childNode = node.first_child(); childNode; childNode = childNode.next_sibling()) {
		const std::string& childName = as_lower_str(childNode.name());
		if(childName == "include") {
			if(!(attribute = childNode.attribute("file"))) {
				continue;
			}

			FileName includeName;
			includeName.SetPath(filename.GetPath());
			includeName.SetFullName(wxString(attribute.as_string(), wxConvUTF8));

			wxString subError;
			if(!loadMaterials(includeName, subError, warnings)) {
				warnings.push_back("Error while loading file \"" + includeName.GetFullName() + "\": " + subError);
			}
		} else if(childName == "metaitem") {
			g_items.loadMetaItem(childNode);
		} else if(childName == "border") {
			g_brushes.unserializeBorder(childNode, warnings);
			if(warning.size()) {
				warnings.push_back("materials.xml: " + warning);
			}
		} else if(childName == "brush") {
			g_brushes.unserializeBrush(childNode, warnings);
			if(warning.size()) {
				warnings.push_back("materials.xml: " + warning);
			}
		} else if(childName == "tileset") {
			unserializeTileset(childNode, warnings);
		}
	}
	return true;
}
Example #11
0
bool ConverterCache::copy(FileName const & orig_from, string const & to_format,
		FileName const & dest) const
{
	if (!lyxrc.use_converter_cache || orig_from.empty() || dest.empty())
		return false;
	LYXERR(Debug::FILES, orig_from << ' ' << to_format << ' ' << dest);

	// FIXME: Should not hardcode this (see bug 3819 for details)
	if (to_format == "pstex") {
		FileName const dest_eps(changeExtension(dest.absFileName(), "eps"));
		if (!copy(orig_from, "eps", dest_eps))
			return false;
	} else if (to_format == "pdftex") {
		FileName const dest_pdf(changeExtension(dest.absFileName(), "pdf"));
		if (!copy(orig_from, "pdf", dest_pdf))
			return false;
	}

	CacheItem * const item = pimpl_->find(orig_from, to_format);
	LASSERT(item, /**/);
	Mover const & mover = getMover(to_format);
	return mover.copy(item->cache_name, dest,
	                  onlyFileName(dest.absFileName()));
}
void QtVersionManager::extensionsInitialized()
{
    bool success = restoreQtVersions();
    m_instance->updateFromInstaller(false);
    if (!success) {
        // We did neither restore our settings or upgraded
        // in that case figure out if there's a qt in path
        // and add it to the Qt versions
        findSystemQt();
    }

    emit m_instance->qtVersionsLoaded();
    emit m_instance->qtVersionsChanged(m_versions.keys(), QList<int>(), QList<int>());
    saveQtVersions();

    const FileName configFileName = globalSettingsFileName();
    if (configFileName.toFileInfo().exists()) {
        m_configFileWatcher = new FileSystemWatcher(m_instance);
        connect(m_configFileWatcher, SIGNAL(fileChanged(QString)),
                m_fileWatcherTimer, SLOT(start()));
        m_configFileWatcher->addFile(configFileName.toString(),
                                     FileSystemWatcher::WatchModifiedDate);
    } // exists
}
Example #13
0
int MetaDataTable::read(const FileName &filename, const std::string &name, std::vector<EMDLabel> *desiredLabels)
{

    // Clear current table
    clear();

    std::ifstream in(filename.data(), std::ios_base::in);
    if (in.fail())
        REPORT_ERROR( (std::string) "MetaDataTable::read: File " + filename + " does not exists" );

    FileName ext = filename.getFileFormat();
    if (ext =="star")
    {
        //REPORT_ERROR("readSTAR not implemented yet...");
        return readStar(in, name, desiredLabels);
    }
    else
    {
        REPORT_ERROR("MetaDataTable::read ERROR: metadatatable should have .star extension");
    }

    in.close();

}
Example #14
0
///
/// Returns all arguments
/// That is: possbile subpath
/// spec
/// config arguemnts
/// moreArguments
/// user arguments
QString QMakeStep::allArguments(const BaseQtVersion *v, bool shorted) const
{
    QmakeBuildConfiguration *bc = qmakeBuildConfiguration();
    QStringList arguments;
    if (bc->subNodeBuild())
        arguments << bc->subNodeBuild()->filePath().toUserOutput();
    else if (shorted)
        arguments << project()->projectFilePath().fileName();
    else
        arguments << project()->projectFilePath().toUserOutput();

    if (v->qtVersion() < QtVersionNumber(5, 0, 0))
        arguments << QLatin1String("-r");
    bool userProvidedMkspec = false;
    for (QtcProcess::ConstArgIterator ait(m_userArgs); ait.next(); ) {
        if (ait.value() == QLatin1String("-spec")) {
            if (ait.next()) {
                userProvidedMkspec = true;
                break;
            }
        }
    }
    FileName specArg = mkspec();
    if (!userProvidedMkspec && !specArg.isEmpty())
        arguments << QLatin1String("-spec") << specArg.toUserOutput();

    // Find out what flags we pass on to qmake
    arguments << bc->configCommandLineArguments();

    arguments << deducedArguments().toArguments();

    QString args = QtcProcess::joinArgs(arguments);
    // User arguments
    QtcProcess::addArgs(&args, m_userArgs);
    return args;
}
Example #15
0
AbstractFSProvider::status_t ZIPProvider::dir(const FileName & url, std::list<
		FileName> & result, uint8_t flags) {
	std::lock_guard<std::mutex> lock(handlesMutex);
	std::string archiveFileName;
	FileName localPath;
	decomposeURL(url, archiveFileName, localPath);
	ZIPHandle * handle = getZIPHandle(archiveFileName);
	if (handle == nullptr) {
		return FAILURE;
	}

	// Make sure all data has been written.
	if (handle->isChanged()) {
		delete handle;
		openHandles.erase(archiveFileName);
		handle = getZIPHandle(archiveFileName);
	}

	if (handle == nullptr) {
		return OK;
	}

	return handle->dir(localPath.getDir(), result, flags);
}
Example #16
0
AbstractFSProvider::status_t ZIPProvider::ZIPHandle::readFile(const FileName & file, std::vector<uint8_t> & data) {
	if (file.getFile().empty()) {
		return FAILURE;
	}

	const size_t size = fileSize(file);
	if (size == 0) {
		return FAILURE;
	}

	zip_file * fileHandle = zip_fopen(handle, file.getPath().c_str(), 0);
	if (fileHandle == nullptr) {
		WARN(zip_strerror(handle));
		return FAILURE;
	}

	data.resize(size);
	const int bytesRead = zip_fread(fileHandle, data.data(), data.size());
	if (bytesRead == -1) {
		WARN(zip_strerror(handle));
		zip_fclose(fileHandle);
		return FAILURE;
	}
	if (static_cast<size_t>(bytesRead) != size) {
		WARN("Sizes differ during read.");
		zip_fclose(fileHandle);
		return FAILURE;
	}

	if (zip_fclose(fileHandle) == -1) {
		WARN(zip_strerror(handle));
		return FAILURE;
	}

	return OK;
}
Example #17
0
// -----------------------------------------------------------------------------
File::NameArray File::ExpandToFilenames(std::string const& fnameArg) {
  NameArray fnames;
#ifdef _WIN32
  fnames.push_back( fnameArg );
#else
  if (fnameArg.empty()) return fnames;
  wordexp_t expanded;
  int err = wordexp( fnameArg.c_str(), &expanded, WRDE_NOCMD );
  WexpErr( err );
  if ( err == 0 ) {
    for (unsigned int i = 0; i != expanded.we_wordc; i++) {
      if (expanded.we_wordv[i] == 0)
        mprinterr("Internal Error: Bad expansion at %i\n", i);
      else {
        FileName fn;
        fn.SetFileName_NoExpansion( expanded.we_wordv[i] );
        fnames.push_back( fn );
      }
    }
    wordfree( &expanded );
  }
#endif /* _WIN32 */
  return fnames;
}
Example #18
0
  /**
   * Opens and loads the list of files from a file.
   *
   * @param list Name of the file to open that contains the list of files.
   *
   * @throws Isis::iException::Io - Cannot open file
   */
  void FileList::read(FileName listFile) {
    // Open the file
    ifstream istm;
    istm.open(listFile.toString().toAscii().data(), std::ios::in);
    if(!istm) {
      QString message = Isis::Message::FileOpen(listFile.toString());
      throw IException(IException::Io, message, _FILEINFO_);
    }

    // Internalize
    try {
      read(istm);

      // Close the file
      istm.close();
    }
    catch (IException &e) {
      printf("debugB\n");
      istm.close();
      QString msg = "File [" + listFile.toString() + "] contains no data";
      throw IException(IException::User, msg, _FILEINFO_);
    }

  }
Example #19
0
//-----------------------------------------------------------------------------
// ExtractorApp::GetInputFiles
//-----------------------------------------------------------------------------
void ExtractorApp::GetInputFiles(std::set<String> *psetSources)
{
    FileName fnPathArg;

    for( int i = 0; i < CommandLine::ArgCount(); i++ )
    {
        String strPattern;
        bool bDoEnum = false;

        // Reads next argument
        fnPathArg.Set(CommandLine::Arg(i));

        if( fnPathArg.IsPathName() )
            // Consider full directory content
            bDoEnum = true;
        else if( fnPathArg.NameExt().find_first_of("*?") != string::npos )
        {
            // Consider only file whose name match the given pattern
            bDoEnum = true;
            strPattern = fnPathArg.NameExt();
        }

        if( bDoEnum )
        {   // Directory enumeration
            FileEnum feDir(fnPathArg.Path(), FileEnum::ENUM_FILE);
            while( feDir.Find() )
            {
                if( strPattern.empty() || feDir.NameExt().Match(PSZ(strPattern)) )
                    psetSources->insert(feDir.FullName());
            }
        }
        else
        {
            if( fnPathArg.FileExists() )
                psetSources->insert(fnPathArg.FullName());
            else
                cerr << "Input file '" << fnPathArg.FullName() << " not found." << endl;
        }
    }
}
Example #20
0
   bool State::parseFile(const FileName& fileName)
  {
    FILE* f = fopen(fileName.c_str(),"r");
    if (f == nullptr) return false;
    Ref<Stream<int> > file = new FileStream(f,fileName);

    std::vector<std::string> syms;
	  for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++) 
      syms.push_back(symbols[i]);

    Ref<TokenStream> cin = new TokenStream(new LineCommentFilter(file,"#"),
                                           TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
                                           TokenStream::separators,syms);
    parse(cin);
    return true;
  }
Example #21
0
bool File::openStream(const FileName &fileName, FILE_MODE mode)
{
	this->fileName = fileName;

	const char *pszMode = getModeString(mode);

	stream = fopen(fileName.c_str(), pszMode);

	if(stream==0 || ferror(stream))
	{
		// Failed to open file stream
		return false;
	}

	return true;
}
Example #22
0
  FileName FileName::addExtension(const QString &newExtension) const {
    FileName result = *this;

    if (result.extension() != newExtension) {
      QString attributesStr = result.attributes();

      if (attributesStr == "")
        result = FileName(result.originalPath() + "/" + result.name() + "." + newExtension);
      else
        result = FileName(result.originalPath() + "/" + result.name() + "." + newExtension
                          + "+" + attributesStr);
    }

    return result;
  }
Example #23
0
QString AndroidToolChain::makeCommand(const Environment &env) const
{
    QStringList extraDirectories = AndroidConfigurations::currentConfig().makeExtraSearchDirectories();
    if (HostOsInfo::isWindowsHost()) {
        FileName tmp = env.searchInPath(QLatin1String("ma-make.exe"), extraDirectories);
        if (!tmp.isEmpty())
            return QString();
        tmp = env.searchInPath(QLatin1String("mingw32-make"), extraDirectories);
        return tmp.isEmpty() ? QLatin1String("mingw32-make") : tmp.toString();
    }

    QString make = QLatin1String("make");
    FileName tmp = env.searchInPath(make, extraDirectories);
    return tmp.isEmpty() ? make : tmp.toString();
}
Example #24
0
FileName IosRunConfiguration::bundleDirectory() const
{
    FileName res;
    Core::Id devType = DeviceTypeKitInformation::deviceTypeId(target()->kit());
    bool isDevice = (devType == Constants::IOS_DEVICE_TYPE);
    if (!isDevice && devType != Constants::IOS_SIMULATOR_TYPE) {
        qCWarning(iosLog) << "unexpected device type in bundleDirForTarget: " << devType.toString();
        return res;
    }
    QmakeBuildConfiguration *bc =
            qobject_cast<QmakeBuildConfiguration *>(target()->activeBuildConfiguration());
    if (bc) {
        QmakeProject *pro = qobject_cast<QmakeProject *>(target()->project());
        const QmakeProFileNode *node = 0;
        if (pro)
            node = pro->rootProjectNode();
        if (node)
            node = node->findProFileFor(profilePath());
        if (node) {
            TargetInformation ti = node->targetInformation();
            if (ti.valid)
                res = FileName::fromString(ti.buildDir);
        }
        if (res.isEmpty())
            res = bc->buildDirectory();
        switch (bc->buildType()) {
        case BuildConfiguration::Debug :
        case BuildConfiguration::Unknown :
            if (isDevice)
                res.appendPath(QLatin1String("Debug-iphoneos"));
            else
                res.appendPath(QLatin1String("Debug-iphonesimulator"));
            break;
        case BuildConfiguration::Profile :
        case BuildConfiguration::Release :
            if (isDevice)
                res.appendPath(QLatin1String("Release-iphoneos"));
            else
                res.appendPath(QLatin1String("Release-iphonesimulator"));
            break;
        default:
            qCWarning(iosLog) << "IosBuildStep had an unknown buildType "
                     << target()->activeBuildConfiguration()->buildType();
        }
    }
    res.appendPath(applicationName() + QLatin1String(".app"));
    return res;
}
Example #25
0
bool Materials::unserializeMaterials(const FileName& filename, xmlNodePtr root, wxString& error, wxArrayString& warnings)
{
	xmlNodePtr materialNode = root->children;
	wxString warning;

	while(materialNode)
	{
		warning = wxT("");

		if(xmlStrcmp(materialNode->name,(const xmlChar*)"include") == 0)
		{
			std::string include_file;
			if(readXMLValue(materialNode, "file", include_file))
			{
				FileName include_name;
				include_name.SetPath(filename.GetPath());
				include_name.SetFullName(wxstr(include_file));
				wxString suberror;
				bool success = loadMaterials(include_name, suberror, warnings);
				if(!success)
					warnings.push_back(wxT("Error while loading file \"") + wxstr(include_file) + wxT("\": ") + suberror);
			}
		}
		else if(xmlStrcmp(materialNode->name,(const xmlChar*)"metaitem") == 0)
		{
			item_db.loadMetaItem(materialNode);
		}
		else if(xmlStrcmp(materialNode->name,(const xmlChar*)"border") == 0)
		{
			brushes.unserializeBorder(materialNode, warnings);
			if(warning.size()) warnings.push_back(wxT("materials.xml: ") + warning);
		}
		else if(xmlStrcmp(materialNode->name,(const xmlChar*)"brush") == 0)
		{
			brushes.unserializeBrush(materialNode, warnings);
			if(warning.size()) warnings.push_back(wxT("materials.xml: ") + warning);
		}
		else if(xmlStrcmp(materialNode->name,(const xmlChar*)"tileset") == 0)
		{
			unserializeTileset(materialNode, warnings);
		}
		materialNode = materialNode->next;
	}
	return true;
}
Example #26
0
//-------------------------------------------------------------------------
void XList::save(const FileName& f, const Config& c) const
{
  std::ofstream ff(f.c_str(), std::ios::out);
  if (!ff)
    throw IOException("Cannot open file", __FILE__, __LINE__, f);
  for (unsigned long i=0; i<getLineCount(); i++)
  {
    XLine& line = _vector.getObject(i);
    unsigned long  count = line.getElementCount();
    for (unsigned long j=0; j<count; j++)
    {
      ff << line.getElement(j, false); // false = does not change current seg
      if (j+1<count)
        ff << " ";
    }
    ff << std::endl;
  }
}
Example #27
0
/*!
  \class CMakeProject
*/
CMakeProject::CMakeProject(CMakeManager *manager, const FileName &fileName)
    : m_manager(manager),
      m_activeTarget(0),
      m_fileName(fileName),
      m_rootNode(new CMakeProjectNode(fileName)),
      m_watcher(new QFileSystemWatcher(this))
{
    setId(Constants::CMAKEPROJECT_ID);
    setProjectContext(Core::Context(CMakeProjectManager::Constants::PROJECTCONTEXT));
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));

    m_rootNode->setDisplayName(fileName.parentDir().fileName());

    m_file = new CMakeFile(this, fileName);

    connect(this, &CMakeProject::buildTargetsChanged, this, &CMakeProject::updateRunConfigurations);
    connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &CMakeProject::fileChanged);
}
Example #28
0
  Ref<Image> loadMagick(const FileName& fileName)
  {
    Magick::Image image(fileName.c_str());
    Image* out = new Image4uc(image.columns(),image.rows(),fileName);
    float rcpMaxRGB = 1.0f/float(MaxRGB);
    Magick::Pixels pixel_cache(image);
    Magick::PixelPacket* pixels = pixel_cache.get(0,0,out->width,out->height);

    switch (image.orientation()) 
    {
    case UndefinedOrientation:
    case TopLeftOrientation: {
      for (size_t y=0; y<out->height; y++) {
        for (size_t x=0; x<out->width; x++) {
          Color4 c;
          c.r = float(pixels[y*out->width+x].red)*rcpMaxRGB;
          c.g = float(pixels[y*out->width+x].green)*rcpMaxRGB;
          c.b = float(pixels[y*out->width+x].blue)*rcpMaxRGB;
          c.a = float(pixels[y*out->width+x].opacity)*rcpMaxRGB;
          out->set(x,out->height-y-1,c);
        }
      }
      break;
    }
    case BottomLeftOrientation: {
      for (size_t y=0; y<out->height; y++) {
        for (size_t x=0; x<out->width; x++) {
          Color4 c;
          c.r = float(pixels[y*out->width+x].red)*rcpMaxRGB;
          c.g = float(pixels[y*out->width+x].green)*rcpMaxRGB;
          c.b = float(pixels[y*out->width+x].blue)*rcpMaxRGB;
          c.a = float(pixels[y*out->width+x].opacity)*rcpMaxRGB;
          out->set(x,y,c);
        }
      }
      break;
    }
    default: {
      throw std::runtime_error("not supported image orientation");
    }
    }

    return out;
  }
Example #29
-1
  int loadHairBin(const FileName& fileName, OBJScene::HairSet* hairset, Vec3fa& offset)
  {  
    FILE* fin = fopen(fileName.c_str(),"rb");
    if (!fin) THROW_RUNTIME_ERROR("could not open " + fileName.str());
    int magick; fread(&magick,sizeof(int),1,fin);
    if (magick != hair_bin_magick)
      THROW_RUNTIME_ERROR("invalid binary hair file " + fileName.str());
    int numHairs; fread(&numHairs,sizeof(int),1,fin);
    int numPoints; fread(&numPoints,sizeof(int),1,fin);
    int numSegments; fread(&numSegments,sizeof(int),1,fin);
    hairset->v.resize(numPoints);
    hairset->hairs.resize(numSegments);
    if (numPoints) fread(&hairset->v[0],sizeof(Vec3fa),numPoints,fin);
    if (numSegments) fread(&hairset->hairs[0],sizeof(OBJScene::Hair),numSegments,fin);
    fclose(fin);

    for (size_t i=0; i<numPoints; i++) {
      hairset->v[i].x-=offset.x;
      hairset->v[i].y-=offset.y;
      hairset->v[i].z-=offset.z;
    }
    return numHairs;
  }
//-------------------------------------------------------------------------
void ULongVector::load(const FileName& f) {
      try {
            ifstream inputVect(f.c_str(),ios::in|ios::binary);
            if(!inputVect)
                throw IOException("Cannot open file", __FILE__, __LINE__,f);
            inputVect.read((char*)&_size,sizeof(_size));
			if (_capacity != 0) delete[] _array;
			_array = new unsigned long[_size];
			if (!_array)
				throw Exception("Memory allocation exception", __FILE__, __LINE__);
			_capacity=_size;
            inputVect.read((char*)_array,_size*sizeof(unsigned long));
            inputVect.close();
          }
          catch (Exception& e) {cout << e.toString().c_str() << endl;}
}