Esempio n. 1
0
std::string Suppressions::parseFile(std::istream &istr)
{
    // Change '\r' to '\n' in the istr
    std::string filedata;
    std::string line;
    while (std::getline(istr, line))
        filedata += line + "\n";
    std::replace(filedata.begin(), filedata.end(), '\r', '\n');

    // Parse filedata..
    std::istringstream istr2(filedata);
    while (std::getline(istr2, line)) {
        // Skip empty lines
        if (line.empty())
            continue;

        // Skip comments
        if (line.length() >= 2 && line[0] == '/' && line[1] == '/')
            continue;

        const std::string errmsg(addSuppressionLine(line));
        if (!errmsg.empty())
            return errmsg;
    }

    return "";
}
Esempio n. 2
0
std::string Settings::Suppressions::parseFile(std::istream &istr)
{
    // Change '\r' to '\n' in the istr
    std::string filedata;
    std::string line;
    while (std::getline(istr, line))
        filedata += line + "\n";
    while (filedata.find("\r") != std::string::npos)
        filedata[filedata.find("\r")] = '\n';

    // Parse filedata..
    std::istringstream istr2(filedata);
    while (std::getline(istr2, line))
    {
        // Skip empty lines
        if (line.empty())
            continue;

        // Skip comments
        if (line.length() >= 2 && line[0] == '/' && line[1] == '/')
            continue;

        const std::string errmsg(addSuppressionLine(line));
        if (!errmsg.empty())
            return errmsg;
    }

    return "";
}
Esempio n. 3
0
//---------------------------------------------------------------------------
//Reading the parameters of simulation
int Input::Read_simulation_parameters(struct Simu_para &simu_para, ifstream &infile)
{
    if(simu_para.mark)
    {
        cout << "Attention: \"" << simu_para.keywords << "\" has been input!" << endl;
        hout << "Attention: \"" << simu_para.keywords << "\" has been input!" << endl;
        return 0;
    }
    else simu_para.mark = true;

    istringstream istr0(Get_Line(infile));
    istr0 >> simu_para.simu_name;			//Read the name of simulation

    istringstream istr1(Get_Line(infile));
    istr1 >> simu_para.sample_num;			//Read the number of samples
    if(simu_para.sample_num<1)	 {
        hout << "Error: the number of samples less than 1." << endl;
        return 0;
    }

    istringstream istr2(Get_Line(infile));
    istr2 >> simu_para.create_read_network;		//Read a signal to show if create a new network or read a previouse network from a file
    if(simu_para.create_read_network!="Create_Network"&&simu_para.create_read_network!="Read_Network")
    {
        hout << "Error: the 'create_read_network' is neither 'Create_Network' nor 'Read_Network'." << endl;
        return 0;
    }

    return 1;
}
bool YuvSourceFilter::setDimensions( const std::string& sDimensions )
{
  size_t pos = sDimensions.find( "x" );
  if (pos != std::string::npos ) 
  {
    int iWidth = 0, iHeight = 0;
    std::istringstream istr( sDimensions.substr( 0, pos ) );
    istr >> iWidth;
    std::istringstream istr2( sDimensions.substr( pos + 1) );
    istr2 >> iHeight;
    return updatePictureBuffer(iWidth, iHeight, m_dBytesPerPixel);
  }
Esempio n. 5
0
unsigned int CppCheck::processFile(const std::string& filename, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings.quiet == false) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::list<std::string> configurations;
        std::string filedata;

        {
            Timer t("Preprocessor::preprocess", _settings.showtime, &S_timerResults);
            preprocessor.preprocess(fileStream, filedata, configurations, filename, _settings.includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist == "define") {
                Tokenizer tokenizer2(&_settings, this);
                std::istringstream istr2(filedata);
                tokenizer2.list.createTokens(istr2, filename);

                for (const Token *tok = tokenizer2.list.front(); tok; tok = tok->next()) {
                    if (tok->str() == "#define") {
                        std::string code = std::string(tok->linenr()-1U, '\n');
                        for (const Token *tok2 = tok; tok2 && tok2->linenr() == tok->linenr(); tok2 = tok2->next())
                            code += " " + tok2->str();
                        Tokenizer tokenizer3(&_settings, this);
                        std::istringstream istr3(code);
                        tokenizer3.list.createTokens(istr3, tokenizer2.list.file(tok));
                        executeRules("define", tokenizer3);
                    }
                }
                break;
            }
        }

        if (!_settings.userDefines.empty() && _settings.maxConfigs==1U) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(filename + ".dump");
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings.quiet == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
            std::string codeWithoutCfg = preprocessor.getcode(filedata, cfg, filename);
            t.Stop();

            codeWithoutCfg += _settings.append();

            if (_settings.preprocessOnly) {
                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                // Create tokens, skip rest of iteration if failed
                std::istringstream istr(codeWithoutCfg);
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                bool result = _tokenizer.createTokens(istr, filename.c_str());
                timer.Stop();
                if (!result)
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << cfg << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end())
                        continue;
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                if (_settings.isEnabled("information") && (_settings.debug || _settings.verbose))
                    purgedConfigurationMessage(filename, cfg);
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename.c_str()));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                const ErrorLogger::ErrorMessage errmsg(locationList,
                                                       Severity::error,
                                                       e.errorMessage,
                                                       e.id,
                                                       false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled("information") || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, unusedFunctionCheckIsEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
Esempio n. 6
0
unsigned int CppCheck::processFile(const std::string& filename, const std::string& fileContent)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings._errorsOnly == false) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    try {
        Preprocessor preprocessor(&_settings, this);
        std::list<std::string> configurations;
        std::string filedata = "";

        if (!fileContent.empty()) {
            // File content was given as a string (democlient)
            std::istringstream iss(fileContent);
            preprocessor.preprocess(iss, filedata, configurations, filename, _settings._includePaths);
        } else {
            // Only file name was given, read the content from file
            std::ifstream fin(filename.c_str());
            Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults);
            preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        // Run rules on this code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist == "define") {
                Tokenizer tokenizer2(&_settings, this);
                std::istringstream istr2(filedata);
                tokenizer2.list.createTokens(istr2, filename);

                for (const Token *tok = tokenizer2.list.front(); tok; tok = tok->next()) {
                    if (tok->str() == "#define") {
                        std::string code = std::string(tok->linenr()-1U, '\n');
                        for (const Token *tok2 = tok; tok2 && tok2->linenr() == tok->linenr(); tok2 = tok2->next())
                            code += " " + tok2->str();
                        Tokenizer tokenizer3(&_settings, this);
                        std::istringstream istr3(code);
                        tokenizer3.list.createTokens(istr3, tokenizer2.list.file(tok));
                        executeRules("define", tokenizer3);
                    }
                }
                break;
            }
        }

        if (!_settings.userDefines.empty() && _settings._maxConfigs==1U) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings._force && configurations.size() > _settings._maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings._force && ++checkCount > _settings._maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings._errorsOnly == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("..."));
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            Timer t("Preprocessor::getcode", _settings._showtime, &S_timerResults);
            const std::string codeWithoutCfg = preprocessor.getcode(filedata, cfg, filename);
            t.Stop();

            const std::string &appendCode = _settings.append();

            if (_settings.debugFalsePositive) {
                if (findError(codeWithoutCfg + appendCode, filename.c_str())) {
                    return exitcode;
                }
            } else {
                checkFile(codeWithoutCfg + appendCode, filename.c_str());
            }
        }
    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
    }

    if (_settings.isEnabled("information") || _settings.checkConfiguration)
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename));

    _errorList.clear();
    return exitcode;
}
Esempio n. 7
0
//---------------------------------------------------------------------------
//Reading geometric information of the RVE
int Input::Read_rve_geometry(struct Geom_RVE &geom_rve, ifstream &infile)
{
    if(geom_rve.mark)
    {
        cout << "Attention: \"" << geom_rve.keywords << "\" has been input!" << endl;
        hout << "Attention: \"" << geom_rve.keywords << "\" has been input!" << endl;
        return 0;
    }
    else geom_rve.mark = true;

    //-----------------------------------------------------------------------------------------------------------------------------------------
    //Define the domain of RVE: the lower-left corner point of RVE and the length, width and height of RVE
    istringstream istr0(Get_Line(infile));
    istr0 >> geom_rve.origin.x >> geom_rve.origin.y >> geom_rve.origin.z;
    istr0 >> geom_rve.len_x >> geom_rve.wid_y >> geom_rve.hei_z;
    if(geom_rve.len_x<=0||geom_rve.wid_y<=0||geom_rve.hei_z<=0)
    {
        cout << "Error: the sizes of RVE should be positive!" << endl;
        hout << "Error: the sizes of RVE should be positive!" << endl;
        return 0;
    }
    geom_rve.volume = geom_rve.len_x*geom_rve.wid_y*geom_rve.hei_z;

    //-----------------------------------------------------------------------------------------------------------------------------------------
    //Define the size range of the observation window and descrement by every step in x, y and z directions
    istringstream istr1(Get_Line(infile));
    istr1 >> geom_rve.win_max_x >> geom_rve.win_max_y >> geom_rve.win_max_z;
    istringstream istr2(Get_Line(infile));
    istr2 >> geom_rve.win_delt_x >> geom_rve.win_delt_y >> geom_rve.win_delt_z;
    istringstream istr3(Get_Line(infile));
    istr3 >> geom_rve.win_min_x >> geom_rve.win_min_y >> geom_rve.win_min_z;

    if(geom_rve.win_max_x<=0.0||geom_rve.win_max_y<=0.0||geom_rve.win_max_z<=0.0||
            geom_rve.win_max_x>geom_rve.len_x||geom_rve.win_max_y>geom_rve.wid_y||geom_rve.win_max_z>geom_rve.hei_z)
    {
        cout << "Error: the win_max in each direction of RVE should be positive and must be smaller than the size of RVE." << endl;
        hout << "Error: the win_max in each direction of RVE should be positive and must be smaller than the size of RVE." << endl;
        return 0;
    }
    if(geom_rve.win_min_x<=0.0||geom_rve.win_min_y<=0.0||geom_rve.win_min_z<=0.0||
            geom_rve.win_min_x>geom_rve.win_max_x||geom_rve.win_min_y>geom_rve.win_max_y||geom_rve.win_min_z>geom_rve.win_max_z)
    {
        cout << "Error: the win_min in each direction of RVE should be positive and must be smaller than max." << endl;
        hout << "Error: the win_min in each direction of RVE should be positive and must be smaller than max." << endl;
        return 0;
    }
    if(geom_rve.win_delt_x<=0.0||geom_rve.win_delt_y<=0.0||geom_rve.win_delt_z<=0.0)
    {
        cout << "Error: the win_delt in each direction of RVE should be positive." << endl;
        hout << "Error: the win_delt in each direction of RVE should be positive." << endl;
        return 0;
    }

    //Details: +Zero for reducing the error of division
    int num[3] = {	(int)((geom_rve.win_max_x-geom_rve.win_min_x + Zero)/geom_rve.win_delt_x),
                    (int)((geom_rve.win_max_y-geom_rve.win_min_y + Zero)/geom_rve.win_delt_y),
                    (int)((geom_rve.win_max_z-geom_rve.win_min_z + Zero)/geom_rve.win_delt_z)
                 };

    if(num[0]!=num[1]||num[0]!=num[2])
    {
        cout << "Error: the numbers of cutoff times are different in three directions (x, y, z)." << endl;
        hout << "Error: the numbers of cutoff times are different in three directions (x, y, z)." << endl;
        return 0;
    }
    else geom_rve.cut_num = num[0];

    //-----------------------------------------------------------------------------------------------------------------------------------------
    //Define the minimum size for background grids (looking for contact points)
    istringstream istr4(Get_Line(infile));
    istr4 >> geom_rve.gs_minx >> geom_rve.gs_miny >> geom_rve.gs_minz;
    if(geom_rve.gs_minx<=0||geom_rve.gs_miny<=0||geom_rve.gs_minz<=0)
    {
        cout << "Error: the number of segments in each direction of RVE should be positive!" << endl;
        hout << "Error: the number of segments in each direction of RVE should be positive" << endl;
        return 0;
    }
    else if((int)(geom_rve.win_max_x/geom_rve.gs_minx)>500||
            (int)(geom_rve.win_max_y/geom_rve.gs_miny)>500||
            (int)(geom_rve.win_max_z/geom_rve.gs_minz)>500)
    {
        cout << "Error: the number of divisions in one of boundary is too big (>500), which leads to the memory problem!" << endl;
        hout << "Error: the number of divisions in one of boundary is too big (>500), which leads to the memory problem!" << endl;
        return 0;
    }

    return 1;
}
Esempio n. 8
0
unsigned int CppCheck::processFile(const std::string& filename, const std::string &cfgname, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (!_settings.quiet) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."));

        if (_settings.verbose) {
            _errorLogger.reportOut("Defines: " + _settings.userDefines);
            std::string includePaths;
            for (std::list<std::string>::const_iterator I = _settings.includePaths.begin(); I != _settings.includePaths.end(); ++I)
                includePaths += " -I" + *I;
            _errorLogger.reportOut("Includes:" + includePaths);
            _errorLogger.reportOut(std::string("Platform:") + _settings.platformString());
        }
    }

    if (plistFile.is_open()) {
        plistFile << ErrorLogger::plistFooter();
        plistFile.close();
    }

    CheckUnusedFunctions checkUnusedFunctions(nullptr, nullptr, nullptr);

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::set<std::string> configurations;

        simplecpp::OutputList outputList;
        std::vector<std::string> files;
        simplecpp::TokenList tokens1(fileStream, files, filename, &outputList);

        // If there is a syntax error, report it and stop
        for (simplecpp::OutputList::const_iterator it = outputList.begin(); it != outputList.end(); ++it) {
            bool err;
            switch (it->type) {
            case simplecpp::Output::ERROR:
            case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY:
            case simplecpp::Output::SYNTAX_ERROR:
            case simplecpp::Output::UNHANDLED_CHAR_ERROR:
                err = true;
                break;
            case simplecpp::Output::WARNING:
            case simplecpp::Output::MISSING_HEADER:
            case simplecpp::Output::PORTABILITY_BACKSLASH:
                err = false;
                break;
            };

            if (err) {
                const ErrorLogger::ErrorMessage::FileLocation loc1(it->location.file(), it->location.line);
                std::list<ErrorLogger::ErrorMessage::FileLocation> callstack;
                callstack.push_back(loc1);

                ErrorLogger::ErrorMessage errmsg(callstack,
                                                 "",
                                                 Severity::error,
                                                 it->msg,
                                                 "syntaxError",
                                                 false);
                _errorLogger.reportErr(errmsg);
                return 1;
            }
        }

        preprocessor.loadFiles(tokens1, files);

        if (!_settings.plistOutput.empty()) {
            std::string filename2;
            if (filename.find('/') != std::string::npos)
                filename2 = filename.substr(filename.rfind('/') + 1);
            else
                filename2 = filename;
            filename2 = _settings.plistOutput + filename2.substr(0, filename2.find('.')) + ".plist";
            plistFile.open(filename2);
            plistFile << ErrorLogger::plistHeader(version(), files);
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(_settings.dumpFile.empty() ? (filename + ".dump") : _settings.dumpFile);
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
                fdump << "  <platform"
                      << " name=\"" << _settings.platformString() << '\"'
                      << " char_bit=\"" << _settings.char_bit << '\"'
                      << " short_bit=\"" << _settings.short_bit << '\"'
                      << " int_bit=\"" << _settings.int_bit << '\"'
                      << " long_bit=\"" << _settings.long_bit << '\"'
                      << " long_long_bit=\"" << _settings.long_long_bit << '\"'
                      << " pointer_bit=\"" << (_settings.sizeof_pointer * _settings.char_bit) << '\"'
                      << "/>\n";
                fdump << "  <rawtokens>" << std::endl;
                for (unsigned int i = 0; i < files.size(); ++i)
                    fdump << "    <file index=\"" << i << "\" name=\"" << ErrorLogger::toxml(files[i]) << "\"/>" << std::endl;
                for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) {
                    fdump << "    <tok "
                          << "fileIndex=\"" << tok->location.fileIndex << "\" "
                          << "linenr=\"" << tok->location.line << "\" "
                          << "str=\"" << ErrorLogger::toxml(tok->str) << "\""
                          << "/>" << std::endl;
                }
                fdump << "  </rawtokens>" << std::endl;
            }
        }

        // Parse comments and then remove them
        preprocessor.inlineSuppressions(tokens1);
        tokens1.removeComments();
        preprocessor.removeComments();

        if (!_settings.buildDir.empty()) {
            // Get toolinfo
            std::string toolinfo;
            toolinfo += CPPCHECK_VERSION_STRING;
            toolinfo += _settings.isEnabled(Settings::WARNING) ? 'w' : ' ';
            toolinfo += _settings.isEnabled(Settings::STYLE) ? 's' : ' ';
            toolinfo += _settings.isEnabled(Settings::PERFORMANCE) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::PORTABILITY) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::INFORMATION) ? 'i' : ' ';
            toolinfo += _settings.userDefines;

            // Calculate checksum so it can be compared with old checksum / future checksums
            const unsigned int checksum = preprocessor.calculateChecksum(tokens1, toolinfo);
            std::list<ErrorLogger::ErrorMessage> errors;
            if (!analyzerInformation.analyzeFile(_settings.buildDir, filename, cfgname, checksum, &errors)) {
                while (!errors.empty()) {
                    reportErr(errors.front());
                    errors.pop_front();
                }
                return exitcode;  // known results => no need to reanalyze file
            }
        }

        // Get directives
        preprocessor.setDirectives(tokens1);
        preprocessor.simplifyPragmaAsm(&tokens1);

        preprocessor.setPlatformInfo(&tokens1);

        // Get configurations..
        if (_settings.userDefines.empty() || _settings.force) {
            Timer t("Preprocessor::getConfigs", _settings.showtime, &S_timerResults);
            configurations = preprocessor.getConfigs(tokens1);
        } else {
            configurations.insert(_settings.userDefines);
        }

        if (_settings.checkConfiguration) {
            for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it)
                (void)preprocessor.getcode(tokens1, *it, files, true);

            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist != "define")
                continue;

            std::string code;
            const std::list<Directive> &directives = preprocessor.getDirectives();
            for (std::list<Directive>::const_iterator dir = directives.begin(); dir != directives.end(); ++dir) {
                if (dir->str.compare(0,8,"#define ") == 0)
                    code += "#line " + MathLib::toString(dir->linenr) + " \"" + dir->file + "\"\n" + dir->str + '\n';
            }
            Tokenizer tokenizer2(&_settings, this);
            std::istringstream istr2(code);
            tokenizer2.list.createTokens(istr2);
            executeRules("define", tokenizer2);
            break;
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled(Settings::INFORMATION)) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (!_settings.quiet && (!cfg.empty() || it != configurations.begin())) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            if (_settings.preprocessOnly) {
                Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
                std::string codeWithoutCfg = preprocessor.getcode(tokens1, cfg, files, true);
                t.Stop();

                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                bool result;

                // Create tokens, skip rest of iteration if failed
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, cfg, files);
                _tokenizer.createTokens(&tokensP);
                timer.Stop();
                if (tokensP.empty())
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << ErrorLogger::toxml(cfg) << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end()) {
                        if (_settings.isEnabled(Settings::INFORMATION) && (_settings.debug || _settings.verbose))
                            purgedConfigurationMessage(filename, cfg);
                        continue;
                    }
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // Analyze info..
                if (!_settings.buildDir.empty())
                    checkUnusedFunctions.parseTokens(_tokenizer, filename.c_str(), &_settings, false);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                ErrorLogger::ErrorMessage errmsg(locationList,
                                                 _tokenizer.list.getSourceFilePath(),
                                                 Severity::error,
                                                 e.errorMessage,
                                                 e.id,
                                                 false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const std::bad_alloc &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    analyzerInformation.setFileInfo("CheckUnusedFunctions", checkUnusedFunctions.analyzerInfo());
    analyzerInformation.close();

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled(Settings::INFORMATION) || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, isUnusedFunctionCheckEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
Esempio n. 9
0
int main()
{
   //---
   // Test ossiIpt::operator>>
   //---
   std::string is1(" ( 0, 1 )");
   std::string is2(" (2,3)");
   std::string is3(" ( 4, 5 )");
   std::string is4_5_6_7(" ( 6, 7 )(8, 9) ( 10, 11 ) ( 12, 13) 9876");

   ossimIpt ip1;
   ossimIpt ip2;
   ossimIpt ip3;
   ossimIpt ip4;
   ossimIpt ip5;
   ossimIpt ip6;
   ossimIpt ip7;
   

   ip1.toPoint(is1);
   ip2.toPoint(is2);
   ip3.toPoint(is3);
   int i;

   std::istringstream istr(is4_5_6_7);
   istr >> ip4 >> ip5 >> ip6 >> ip7 >> i;

   //---
   // Test ossiDpt::operator>>
   //---
   std::string ds1(" ( 0.0, 1.1 )");
   std::string ds2(" (2.2,3.3)");
   std::string ds3(" ( 4.4, 5.5 )");
   std::string ds4_5_6_7(" ( 6.6, 7.7 )(8.8, 9.9) ( 10.0, 11.0 ) ( 12.0, 13.0) 9876.12345678");
   std::string ds8("12 20");

   ossimDpt dp1;
   ossimDpt dp2;
   ossimDpt dp3;
   ossimDpt dp4;
   ossimDpt dp5;
   ossimDpt dp6;
   ossimDpt dp7;
   ossimDpt dp8;

   dp1.toPoint(ds1);
   dp2.toPoint(ds2);
   dp3.toPoint(ds3);
   double d;

   std::istringstream istr2(ds4_5_6_7);
   istr2 >> dp4 >> dp5 >> dp6 >> dp7 >> d;

   dp8.toPoint(ds8); // Test an invalid string "12 20"

    //---
   // Test ossiDpt3d
   //---
   std::string ds3d1  = " ( 0.0, 1.1, 2.2 )";
   std::string ds3d2 = "(1.0,2.0,3.0)";
   
   ossimDpt3d dp3d1;
   ossimDpt3d dp3d2;
   dp3d1.toPoint(ds3d1);
   dp3d2.toPoint(ds3d2);


   //---
   // Test ossiGpt::operator>>
   //---
   std::string gs1("(0.0,0.0,0.0,WGE)");
   std::string gs2("(1.1,2.2,3.3,NAR-C)");
   std::string gs3(" (4.4,5.5,6.6,NAS-C )");
   std::string gs4_5_6_7(" (4.4,5.5,6.6,NAS-C )( 10.0, 10.0 ,5.0, TOY-C ) (17, -89, 50.0, xxx) (28.2, -44.5, 10000.0, NAS-B) 12345.6789");

   ossimGpt gp1;
   ossimGpt gp2;
   ossimGpt gp3;
   ossimGpt gp4;
   ossimGpt gp5;
   ossimGpt gp6;
   ossimGpt gp7;
   double d2;

   gp1.toPoint(gs1);
   gp2.toPoint(gs2);
   gp3.toPoint(gs3);

   std::istringstream istr4(gs4_5_6_7);
   istr4 >> gp4 >> gp5 >> gp6 >> gp7 >> d2;


   //---
   // Test ossimEcefPoint toString and toPoint methods.
   //---
   std::string es1("(1.0,2.0,3.0)");
   ossimEcefPoint ep1;
   ep1.toPoint(es1);
   std::string es2 = ep1.toString(10).string();

   //---
   // Test ossimEcefPoint toString and toPoint methods.
   //---
   ossimEcefVector ev1;
   ev1.toPoint(es1);
   std::string es3 = ev1.toString(10).string();
  
   std::cout
      << "\nis1:       " << is1
      << "\nip1:       " << ip1
      << "\nis2:       " << is2
      << "\nip2:       " << ip2
      << "\nis3:       " << is3
      << "\nip3:       " << ip3
      << "\nis4_5_6_7: " << is4_5_6_7
      << "\nip4:       " << ip4
      << "\nip5:       " << ip5
      << "\nip6:       " << ip6
      << "\nip7:       " << ip7
      << "\ni:         " << i

      << "\n\n\nds1:       " << ds1
      << "\ndp1:       " << dp1
      << "\nds2:       " << ds2
      << "\ndp2:       " << dp2
      << "\nds3:       " << ds3
      << "\ndp3:       " << dp3
      << "\nds4_5_6_7: " << ds4_5_6_7
      << "\ndp4:       " << dp4
      << "\ndp5:       " << dp5
      << "\ndp6:       " << dp6
      << "\ndp7:       " << dp7
      << "\nds8:       " << ds8
      << "\ndp8:       " << dp8
      << "\nd:         " << d

      << "\n\nds3d1:       " << ds3d1
      << "\nds3d2:     " << ds3d2
      << "\ndp3d1:     " << dp3d1
      << "\ndp3d2:     " << dp3d2

      << "\n\n\ngs1:       " << gs1
      << "\ngp1:       " << gp1
      << "\ngs2:       " << gs2
      << "\ngp2:       " << gp2
      << "\ngs3:       " << gs3
      << "\ngp3:       " << gp3
      << "\ngs4_5_6_7: " << gs4_5_6_7
      << "\ngp4:       " << gp4
      << "\ngp5:       " << gp5
      << "\ngp6:       " << gp6
      << "\ngp7:       " << gp7
      << "\nd2:         " << d2

      << "\n\n\nes1:       " << es1
      << "\nep1:       " << ep1
      << "\nes2:       " << es2
      << "\nev1:       " << ev1
      << "\nes3:       " << es3

      << std::endl;

   return 0;
}
Esempio n. 10
0
//---------------------------------------------------------------------------
void EllipseMade::ellip_generation(ifstream &infile,string output_file,string data_file,double mod)
{
    struct  point_type
    {
        double	x;
        double	y;
        double	z;
    };

    double	x,y,z;
    double	x1,y1,z1;
    double	A,B,C;
    double	a_max,a_min,b_min,c_min;		// the ellipse the max a and the min a and the min b,a is half of the long axis,b is the half of the short axis.
    double  sita,phi;
    double  alpha1,beta1,alpha2;
    double	sign;
    double  d,f;								// the distance between two ellipses center
    double  vol_ratio;
    int		times;
    int		k1,K,l1,L;

    istringstream istr0(Get_Line(infile));		//长方体区域的六条边
    istr0	>> space.x0 >> space.x >> space.y0 >> space.y >> space.z0 >> space.z;

    istringstream istr2(Get_Line(infile));		//椭球长中短轴信息
    istr2 >> a_min >> a_max >> b_min >> c_min;
    if (a_min>a_max)
    {
        hout << "输入的椭球长轴最小值大于最大值!" << endl;
        exit(0);
    }

    istringstream istr6(Get_Line(infile));		//体积百分比
    istr6 >> vol_ratio;
//@
    //	int in;
    //	ifstream o("num.dat");
    //	o>>in;
    //	o.close();
    //if(in>10) in=in-10;
    //else if(in>5) in=in-5;
    //vol_ratio=vol_ratio*in;

    //-------------------------------------------------------------
    //椭球生成计数器
    double delt_h = 2*sqrt(pow(c_min,2)*(pow(a_max,2)-pow(a_max-(a_min+c_min)*epsilon,2))/pow(a_max,2))/pi;
    double cell_volume = (space.x-space.x0)*(space.y-space.y0)*(space.z-space.z0);
    double ellip_volume = 0.0;
    ellip_ratio = 0.0;
    times=0;

    //用于随机生成的起始时间
    srand((unsigned int)time(0));

    do
    {
        //-------------------------------------------------------------
        //产生椭球
        struct elliparam ell_temp;

        ell_temp.x=((double)(rand())/RAND_MAX)*(space.x-space.x0)+space.x0;
        ell_temp.y=((double)(rand())/RAND_MAX)*(space.y-space.y0)+space.y0;
        ell_temp.z=((double)(rand())/RAND_MAX)*(space.z-space.z0)+space.z0;

        ell_temp.a=((double)(rand())/RAND_MAX)*(a_max-a_min)+a_min;
        if(!(b_min==0&&c_min==0))
        {
            ell_temp.b=((double)(rand())/RAND_MAX)*(ell_temp.a-b_min)+b_min;
            ell_temp.c=((double)(rand())/RAND_MAX)*(ell_temp.a-c_min)+c_min;
        }
        else
        {
            ell_temp.b=ell_temp.a;
            ell_temp.c=ell_temp.a;
        }

        alpha1 =((double)(rand())/RAND_MAX)*pi;
        if(alpha1>pi/2.0)
        {
            beta1  =((double)(rand())/RAND_MAX)*(2*(pi-alpha1))+(alpha1-pi/2.0);
        }
        else
        {
            beta1  =((double)(rand())/RAND_MAX)*(2*alpha1)+(pi/2.0-alpha1);
        }
        ell_temp.alpha1 =cos(alpha1);																// r1 from 0 to pi
        ell_temp.beta1  =cos(beta1);																	// r2 from (pi/2-r1) to (pi/2+r1)
        ell_temp.gamma1 =(int)pow(-1.0,(int)fmod(rand(),2.0)+1)*sqrt(1-pow(ell_temp.alpha1,2)-pow(ell_temp.beta1,2));	// choose one in both, minus value or positive value

        if(alpha1>pi/2.0)
        {
            alpha2  =((double)(rand())/RAND_MAX)*(2*(pi-alpha1))+(alpha1-pi/2.0);
        }
        else
        {
            alpha2  =((double)(rand())/RAND_MAX)*(2*alpha1)+(pi/2.0-alpha1);
        }
        ell_temp.alpha2=cos(alpha2);

        A=1+pow(ell_temp.beta1/ell_temp.gamma1,2);
        B=2*(ell_temp.alpha1*ell_temp.alpha2*ell_temp.beta1)/pow(ell_temp.gamma1,2);
        C=pow(ell_temp.alpha1*ell_temp.alpha2/ell_temp.gamma1,2)+pow(ell_temp.alpha2,2)-1.0;

        ell_temp.beta2	 =(-B+(int)pow(-1.0,(int)fmod(rand(),2.0)+1)*sqrt(pow(B,2)-4*A*C))/(2.0*A);
        ell_temp.gamma2 =-(ell_temp.beta1/ell_temp.gamma1)*ell_temp.beta2-(ell_temp.alpha1*ell_temp.alpha2/ell_temp.gamma1);

        sign=(ell_temp.alpha1*ell_temp.beta2)/fabs(ell_temp.alpha1*ell_temp.beta2);
        ell_temp.alpha3 =sign*sqrt(1-pow(ell_temp.alpha1,2)-pow(ell_temp.alpha2,2));
        ell_temp.beta3	 =-(ell_temp.alpha1*ell_temp.beta1+ell_temp.alpha2*ell_temp.beta2)/ell_temp.alpha3;
        ell_temp.gamma3 =-(ell_temp.alpha1*ell_temp.gamma1+ell_temp.alpha2*ell_temp.gamma2)/ell_temp.alpha3;

        ell_temp.a=(1+epsilon)*ell_temp.a;
        ell_temp.b=(1+epsilon)*ell_temp.b;
        ell_temp.c=(1+epsilon)*ell_temp.c;
        //---------------------------------------------------------------------------
        //check this ellipse
        //---------------------------------------------------------------------------
        //whether this ellipse intersect with other ellipses
        k1=(int)(sqrt(pow(ell_temp.a,2)+pow(ell_temp.b,2))/delt_h);
        K=4*(k1+1);
        sita=pi/(K/2.0);

        //(添加一段程序080414)考虑不与边界相交的情况
        //for(int j=1;j<=K/2;j++)
        //{
        //	l1=(int)(sqrt(pow(ell_temp.a*sin(j*sita),2)+pow(ell_temp.b*sin(j*sita),2))/delt_h);
        //	L=4*(l1+1);
        //	phi=2*pi/L;

        //	for(int m=1;m<=L;m++)
        //	{
        //		x=ell_temp.a*sin(j*sita)*cos(m*phi);
        //		y=ell_temp.b*sin(j*sita)*sin(m*phi);
        //		z=ell_temp.c*cos(j*sita);

        //		x1=ell_temp.x+x*ell_temp.alpha1+y*ell_temp.alpha2+z*ell_temp.alpha3;
        //		y1=ell_temp.y+x*ell_temp.beta1+y*ell_temp.beta2+z*ell_temp.beta3;
        //		z1=ell_temp.z+x*ell_temp.gamma1+y*ell_temp.gamma2+z*ell_temp.gamma3;

        //		x=x1;
        //		y=y1;
        //		z=z1;

        //		if(x1<=space.x0+0.04||x1>=space.x-0.04||y1<=space.y0+0.04||y1>=space.y-0.04||z1<=space.z0+0.04||z1>=space.z-0.04)
        //		{
        //			times=times+1;
        //			goto gen_again;
        //		}
        //	}
        //}

        for(int i=0; i<int(ellip.size()); i++)
        {
            //probably estimate
            d=sqrt(pow(ell_temp.x-ellip[i].x,2)+pow(ell_temp.y-ellip[i].y,2)+pow(ell_temp.z-ellip[i].z,2));

            if(d>=ell_temp.a+ellip[i].a+2*epsi)
            {
                goto gene;
            }
            else if((d<ell_temp.b+ellip[i].b+2*epsi*(ellip[i].b/ellip[i].a))&&(d<ell_temp.c+ellip[i].c+2*epsi*(ellip[i].c/ellip[i].a)))
            {
                times=times+1;
                goto gen_again;
            }
            else
            {
                //exactly compute
                for(int j=1; j<=K/2; j++)
                {
                    l1=(int)(sqrt(pow(ell_temp.a*sin(j*sita),2)+pow(ell_temp.b*sin(j*sita),2))/delt_h);
                    L=4*(l1+1);
                    phi=2*pi/L;

                    for(int m=1; m<=L; m++)
                    {
                        x=ell_temp.a*sin(j*sita)*cos(m*phi);
                        y=ell_temp.b*sin(j*sita)*sin(m*phi);
                        z=ell_temp.c*cos(j*sita);

                        x1=ell_temp.x+x*ell_temp.alpha1+y*ell_temp.alpha2+z*ell_temp.alpha3;
                        y1=ell_temp.y+x*ell_temp.beta1+y*ell_temp.beta2+z*ell_temp.beta3;
                        z1=ell_temp.z+x*ell_temp.gamma1+y*ell_temp.gamma2+z*ell_temp.gamma3;

                        x=x1;
                        y=y1;
                        z=z1;

                        x=x-ellip[i].x;
                        y=y-ellip[i].y;
                        z=z-ellip[i].z;

                        x1=x*ellip[i].alpha1+y*ellip[i].beta1+z*ellip[i].gamma1;
                        y1=x*ellip[i].alpha2+y*ellip[i].beta2+z*ellip[i].gamma2;
                        z1=x*ellip[i].alpha3+y*ellip[i].beta3+z*ellip[i].gamma3;

                        f=pow(x1,2)/pow(ellip[i].a,2)+pow(y1,2)/pow(ellip[i].b,2)+pow(z1,2)/pow(ellip[i].c,2)-1.0;

                        if(f<0.0)
                        {
                            times=times+1;
                            goto gen_again;
                        }
                    }
                }
            }
gene:
            ;
        }
        //---------------------------------------------------------------------
        //次数清零并插入椭球向量
        times=0;
        ellip.push_back(ell_temp);
        //---------------------------------------------------------------------
        //计算体积比
        ellip_volume = ellip_volume + ellipse_volume(ell_temp,epsilon);
        ellip_ratio = ellip_volume/cell_volume;
gen_again:
        ;
    } while(times<=N_times&&ellip_ratio<vol_ratio);

    //---------------------------------------------------------------------
    //椭球收缩
    for(int i=0; i<int(ellip.size()); i++)
    {
        ellip[i].a=ellip[i].a/(1+epsilon);
        ellip[i].b=ellip[i].b/(1+epsilon);
        ellip[i].c=ellip[i].c/(1+epsilon);
    }

    //---------------------------------------------------------------------
    //画图
//	if(mod!=0) draw_tecplot("generate_ellipse.dat",delt_h);

    //---------------------------------------------------------------------
    //输出数据
    if(mod!=0) output_EllipseData(output_file);

    //---------------------------------------------------------------------
    //输入到样本数据文件
    output_Datafile(data_file);

}
Esempio n. 11
0
//---------------------------------------------------------------------------
//背景六面体网格生成
int Mesher::Brick_background_mesh(ifstream &infile, struct RVE_Geo &cell_geo)
{
	//-----------------------------------------------------------------------------------------------------------------------------------------
	//读入单胞的长、宽和高的分割细度
	istringstream istr2(Get_Line(infile));	
	istr2 >> dx >> dy >> dz;
	if(dx<0||dy<0||dz<0)
	{
		hout << "RVE长宽高的分割细度输入错误! 请检查! ......... Brick_background_mesh" << endl;
		return 0;
	}

	//-----------------------------------------------------------------------------------------------------------------------------------------
	//背景网格(节点和单元)

	//生成各个方向的点数
	int x_sec_num = int(cell_geo.len_x/dx) +1;
	int y_sec_num = int(cell_geo.wid_y/dy)+1;
	int z_sec_num = int(cell_geo.hei_z/dz) +1;

	//微调整剖分步长,保证单胞的尺寸不变
	dx = cell_geo.len_x/(x_sec_num-1);
	dy = cell_geo.wid_y/(y_sec_num-1);
	dz = cell_geo.hei_z/(z_sec_num-1);

	//-----------------------------------------------------------------------------------------------------------------------------------------
	//记录分割细度到单胞信息中
	cell_geo.delt_x = dx;
	cell_geo.delt_y = dy;
	cell_geo.delt_z = dz;

	//-----------------------------------------------------------------------------------------------------------------------------------------
	//生成节点
	for( int i=0; i<z_sec_num; i++ )
	{
		double z = cell_geo.poi_min.z + i * dz ;
		for( int j=0; j<y_sec_num; j++ )
		{
			double y = cell_geo.poi_min.y + j * dy ;
			for( int k=0; k<x_sec_num; k++ )
			{
				double x = cell_geo.poi_min.x + k * dx ;

				Node nd(x,y,z);
				nd.type = Deter_node_type(i, j, k, z_sec_num-1, y_sec_num-1, x_sec_num-1);	//标注节点的位置(角点、边界线点、边界面点、内点)
				nodes.push_back(nd);
			}
		}
	}

	//-----------------------------------------------------------------------------------------------------------------------------------------
	//生成六面体单元

	//定义六面体向量
	for( int i=0; i<z_sec_num-1; i++ )
	{
		for( int j=0; j<y_sec_num-1; j++ )
		{
			for( int k=0; k<x_sec_num-1; k++ )
			{
				//六面体的八个顶点
				Element ele_temp;
				ele_temp.nodes_id.push_back(i * x_sec_num * y_sec_num + j * x_sec_num + k);
				ele_temp.nodes_id.push_back(i * x_sec_num * y_sec_num + j * x_sec_num + k + 1);
				ele_temp.nodes_id.push_back(i * x_sec_num * y_sec_num + ( j + 1 ) * x_sec_num + k + 1);
				ele_temp.nodes_id.push_back(i * x_sec_num * y_sec_num + ( j + 1 ) * x_sec_num + k);
				ele_temp.nodes_id.push_back(( i + 1 ) * x_sec_num * y_sec_num + j * x_sec_num + k );
				ele_temp.nodes_id.push_back(( i + 1 ) * x_sec_num * y_sec_num + j * x_sec_num + k + 1);
				ele_temp.nodes_id.push_back(( i + 1 ) * x_sec_num * y_sec_num + ( j + 1 ) * x_sec_num + k + 1);
				ele_temp.nodes_id.push_back(( i + 1 ) * x_sec_num * y_sec_num + ( j + 1 ) * x_sec_num + k);

				elements.push_back(ele_temp);
			}
		}
	}

	return 1;
}