<commit_before>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2017-2019 Matthias Fehring <mf@huessenbergnetz.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "utils.h"
#include "../objects/skaffarierror.h"
#include <Cutelyst/Context>
#include <Cutelyst/Request>
#include <Cutelyst/Response>
#include <Cutelyst/Plugins/Session/Session>
#include <QTimeZone>
#include <QLocale>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QJsonObject>
#include <cmath>
#include <limits>

Utils::Utils()
{

}

Utils::~Utils()
{

}

QDateTime Utils::toUserTZ(Cutelyst::Context *c, const QDateTime &dt)
{
    QDateTime retVal;

    const QTimeZone userTz(Cutelyst::Session::value(c, QStringLiteral("tz"), QStringLiteral("UTC")).toByteArray());

    if (userTz != QTimeZone::utc()) {
        QDateTime _dt = dt;
        _dt.setTimeSpec(Qt::UTC);
        retVal = _dt.toTimeZone(userTz);
    } else {
        retVal = dt;
    }

    return retVal;
}

QString Utils::humanBinarySize(Cutelyst::Context *c, quota_size_t sizeInByte)
{
    QString sizeStr;

#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))

    if (sizeInByte < static_cast<quota_size_t>(std::numeric_limits<qint64>::max())) {
        sizeStr = c->locale().formattedDataSize(static_cast<qint64>(sizeInByte));
    } else {

#endif

        if (sizeInByte < Q_UINT64_C(1048576)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1024.0, 'f', 2);
            sizeStr.append(QLatin1String(" KiB"));
        } else if (sizeInByte < Q_UINT64_C(1073741824)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1048576.0, 'f', 2);
            sizeStr.append(QLatin1String(" MiB"));
        } else if (sizeInByte < Q_UINT64_C(1099511627776)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1073741824.0, 'f', 2);
            sizeStr.append(QLatin1String(" GiB"));
        } else if (sizeInByte < Q_UINT64_C(1125899906842624)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1099511627776.0, 'f', 2);
            sizeStr.append(QLatin1String(" TiB"));
        } else if (sizeInByte < Q_UINT64_C(1152921504606846976)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1125899906842624.0, 'f', 2);
            sizeStr.append(QLatin1String(" PiB"));
        } else {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1152921504606846976.0, 'f', 2);
            sizeStr.append(QLatin1String(" EiB"));
        }

#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
    }
#endif

    return sizeStr;
}

bool Utils::checkCheckbox(const Cutelyst::ParamsMultiMap &params, const QString &field)
{
    bool ret = false;

    if (params.contains(field)) {
        static QStringList allowedVals({QStringLiteral("1"), QStringLiteral("true"), QStringLiteral("on")});
        ret = allowedVals.contains(params.value(field), Qt::CaseInsensitive);
    }

    return ret;
}

bool Utils::ajaxPostOnly(Cutelyst::Context *c, bool isAjax)
{
    if (isAjax && !c->req()->isPost()) {
        c->response()->setStatus(Cutelyst::Response::MethodNotAllowed);
        c->response()->setHeader(QStringLiteral("Allow"), QStringLiteral("POST"));
        c->response()->setJsonObjectBody({{QStringLiteral("error_msg"), c->translate("Skaffari::Utils", "For AJAX requests, this route is only available via POST requests.")}});
        return true;
    } else {
        return false;
    }
}

dbid_t Utils::strToDbid(const QString &str, bool *ok, const QString &errorMsg, Cutelyst::Context *c)
{
#ifndef QT_NO_DEBUG
    if (!errorMsg.isEmpty() && !c) {
        Q_ASSERT_X(false, "string to db id", "invalid context object");
    }
#endif

    dbid_t val = 0;
    bool _ok = true;
    const qlonglong tmpval = str.toLongLong(&_ok);
    if (_ok) {
        if (Q_UNLIKELY(tmpval < static_cast<qlonglong>(std::numeric_limits<dbid_t>::min()) || tmpval > static_cast<qlonglong>(std::numeric_limits<dbid_t>::max()))) {
            _ok = false;
        } else {
            val = static_cast<dbid_t>(tmpval);
        }
    }
    if (ok) {
        *ok = _ok;
    }
    if (!errorMsg.isEmpty() && c) {
        SkaffariError::toStash(c, SkaffariError::InputError, errorMsg, true);
    }
    return val;
}

void Utils::setError(Cutelyst::Context *c, QJsonObject &json, const QString &errorMsg, Cutelyst::Response::HttpStatus status)
{
    Q_ASSERT_X(c, "set error", "invalid context object");

    if (c->req()->xhr()) {
        json.insert(QStringLiteral("error_msg"), errorMsg);
    } else {
        c->setStash(QStringLiteral("error_msg"), errorMsg);
    }
    c->res()->setStatus(status);
}

void Utils::setError(Cutelyst::Context *c, QJsonObject &json, const SkaffariError &error)
{
    Utils::setError(c, json, error.errorText(), error.status());
}
<commit_msg>Fix Utils::strToDbid() not detaching as intended<commit_after>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2017-2019 Matthias Fehring <mf@huessenbergnetz.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "utils.h"
#include "../objects/skaffarierror.h"
#include <Cutelyst/Context>
#include <Cutelyst/Request>
#include <Cutelyst/Response>
#include <Cutelyst/Plugins/Session/Session>
#include <QTimeZone>
#include <QLocale>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QJsonObject>
#include <cmath>
#include <limits>

Utils::Utils()
{

}

Utils::~Utils()
{

}

QDateTime Utils::toUserTZ(Cutelyst::Context *c, const QDateTime &dt)
{
    QDateTime retVal;

    const QTimeZone userTz(Cutelyst::Session::value(c, QStringLiteral("tz"), QStringLiteral("UTC")).toByteArray());

    if (userTz != QTimeZone::utc()) {
        QDateTime _dt = dt;
        _dt.setTimeSpec(Qt::UTC);
        retVal = _dt.toTimeZone(userTz);
    } else {
        retVal = dt;
    }

    return retVal;
}

QString Utils::humanBinarySize(Cutelyst::Context *c, quota_size_t sizeInByte)
{
    QString sizeStr;

#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))

    if (sizeInByte < static_cast<quota_size_t>(std::numeric_limits<qint64>::max())) {
        sizeStr = c->locale().formattedDataSize(static_cast<qint64>(sizeInByte));
    } else {

#endif

        if (sizeInByte < Q_UINT64_C(1048576)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1024.0, 'f', 2);
            sizeStr.append(QLatin1String(" KiB"));
        } else if (sizeInByte < Q_UINT64_C(1073741824)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1048576.0, 'f', 2);
            sizeStr.append(QLatin1String(" MiB"));
        } else if (sizeInByte < Q_UINT64_C(1099511627776)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1073741824.0, 'f', 2);
            sizeStr.append(QLatin1String(" GiB"));
        } else if (sizeInByte < Q_UINT64_C(1125899906842624)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1099511627776.0, 'f', 2);
            sizeStr.append(QLatin1String(" TiB"));
        } else if (sizeInByte < Q_UINT64_C(1152921504606846976)) {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1125899906842624.0, 'f', 2);
            sizeStr.append(QLatin1String(" PiB"));
        } else {
            sizeStr = c->locale().toString(static_cast<double>(sizeInByte)/1152921504606846976.0, 'f', 2);
            sizeStr.append(QLatin1String(" EiB"));
        }

#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
    }
#endif

    return sizeStr;
}

bool Utils::checkCheckbox(const Cutelyst::ParamsMultiMap &params, const QString &field)
{
    bool ret = false;

    if (params.contains(field)) {
        static QStringList allowedVals({QStringLiteral("1"), QStringLiteral("true"), QStringLiteral("on")});
        ret = allowedVals.contains(params.value(field), Qt::CaseInsensitive);
    }

    return ret;
}

bool Utils::ajaxPostOnly(Cutelyst::Context *c, bool isAjax)
{
    if (isAjax && !c->req()->isPost()) {
        c->response()->setStatus(Cutelyst::Response::MethodNotAllowed);
        c->response()->setHeader(QStringLiteral("Allow"), QStringLiteral("POST"));
        c->response()->setJsonObjectBody({{QStringLiteral("error_msg"), c->translate("Skaffari::Utils", "For AJAX requests, this route is only available via POST requests.")}});
        return true;
    } else {
        return false;
    }
}

dbid_t Utils::strToDbid(const QString &str, bool *ok, const QString &errorMsg, Cutelyst::Context *c)
{
#ifndef QT_NO_DEBUG
    if (!errorMsg.isEmpty() && !c) {
        Q_ASSERT_X(false, "string to db id", "invalid context object");
    }
#endif

    dbid_t val = 0;
    bool _ok = true;
    const qlonglong tmpval = str.toLongLong(&_ok);
    if (_ok) {
        if (Q_UNLIKELY(tmpval < static_cast<qlonglong>(std::numeric_limits<dbid_t>::min()) || tmpval > static_cast<qlonglong>(std::numeric_limits<dbid_t>::max()))) {
            _ok = false;
        } else {
            val = static_cast<dbid_t>(tmpval);
        }
    }
    if (ok) {
        *ok = _ok;
    }
    if (!ok && !errorMsg.isEmpty() && c) {
        SkaffariError::toStash(c, SkaffariError::InputError, errorMsg, true);
    }
    return val;
}

void Utils::setError(Cutelyst::Context *c, QJsonObject &json, const QString &errorMsg, Cutelyst::Response::HttpStatus status)
{
    Q_ASSERT_X(c, "set error", "invalid context object");

    if (c->req()->xhr()) {
        json.insert(QStringLiteral("error_msg"), errorMsg);
    } else {
        c->setStash(QStringLiteral("error_msg"), errorMsg);
    }
    c->res()->setStatus(status);
}

void Utils::setError(Cutelyst::Context *c, QJsonObject &json, const SkaffariError &error)
{
    Utils::setError(c, json, error.errorText(), error.status());
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////
//
// CoinVault
//
// versioninfo.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "versioninfo.h"
#include "../BuildInfo.h"

// Definitions
const int VERSIONPADDINGRIGHT = 20;
const int VERSIONPADDINGBOTTOM = 30;

const QString VERSIONTEXT("Version 0.5.1 beta");

const QString commitHash(COMMIT_HASH);
const QString shortCommitHash(QString(COMMIT_HASH).left(6));

// Accessors
int getVersionPaddingRight() { return VERSIONPADDINGRIGHT; }
int getVersionPaddingBottom() { return VERSIONPADDINGBOTTOM; }

const QString& getVersionText() { return VERSIONTEXT; }

const QString& getCommitHash() { return commitHash; }
const QString& getShortCommitHash() { return shortCommitHash; }
<commit_msg>v0.5.2<commit_after>///////////////////////////////////////////////////////////////////
//
// CoinVault
//
// versioninfo.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "versioninfo.h"
#include "../BuildInfo.h"

// Definitions
const int VERSIONPADDINGRIGHT = 20;
const int VERSIONPADDINGBOTTOM = 30;

const QString VERSIONTEXT("Version 0.5.2 beta");

const QString commitHash(COMMIT_HASH);
const QString shortCommitHash(QString(COMMIT_HASH).left(6));

// Accessors
int getVersionPaddingRight() { return VERSIONPADDINGRIGHT; }
int getVersionPaddingBottom() { return VERSIONPADDINGBOTTOM; }

const QString& getVersionText() { return VERSIONTEXT; }

const QString& getCommitHash() { return commitHash; }
const QString& getShortCommitHash() { return shortCommitHash; }
<|endoftext|>


<commit_before>#include <iomanip>
#include <iterator>
#include <numeric>
#include <random>
#include <chrono>

#include "./parser.hpp"
#include "./input.hpp"
#include "./wlconf.hpp"

void dispInput(std::shared_ptr<Input> in){
	//  [INPUT]
	std::cout << "EMIN          : " << in->getDataByString("EMIN") << std::endl;
	std::cout << "EMAX          : " << in->getDataByString("EMAX") << std::endl;
	std::cout << "BIN           : " << in->getDataByString("BIN")  << std::endl;
	std::cout << "MCSTEP        : " << in->getDataByString("MCSTEP")        << std::endl;
	std::cout << "FLATCHECKSTEP : " << in->getDataByString("FLATCHECKSTEP") << std::endl;
	std::cout << "LOGFACTOR     : " << in->getDataByString("LOGFACTOR")     << std::endl;
	std::cout << "FLATCRITERION : " << in->getDataByString("FLATCRITERION") << std::endl;

	//  [OPTION]
	std::cout << "CHEMIPOT      : " << in->getDataByString("CHEMIPOT")  << std::endl;
	std::cout << "SPININPUT     : " << in->getDataByString("SPININPUT") << std::endl;
	std::cout << "SETRANDOM     : " << in->getDataByString("SETRANDOM") << std::endl;
}

double wl_step(WLconf::WLconf& conf, const std::vector<double>& dos){
	conf.setTotalEnergy();
	conf.setIndex();
	int index_before = conf.getIndex();
	int index_after  = index_before;

	conf.setNewConf();
	index_after  = conf.getIndex();

	double b = exp(dos.at(index_before) - dos.at(index_after));
	if(b>=1.0 or b>conf.RandReal()){
	} else {
		conf.Memento();
	}
	return conf.getTotalEnergy();
}

int main(int argc, char* argv[]){
	std::shared_ptr<Input> in(new Input("wang-landau.ini"));

	int mcstep, bin, flatcheck_step, minstep=0;
	double logfactor, logflimit, emin, emax, edelta, flat_criterion;
	double low_cutoff = 1.0;
	int is_restart=0, is_output_tunnelingtime=0;

	std::string filename_spin_input;

	in->setData("BIN",  bin, true);
	in->setData("MCSTEP", mcstep, true);

	in->setData("EMIN", emin, true);
	in->setData("EMAX", emax, true);
	edelta = (emax - emin) / (double)bin;

	in->setData("FLATCHECKSTEP", flatcheck_step, true);
	in->setData("LOGFACTOR", logfactor, true);
	in->setData("LOGFLIMIT", logflimit, true);
	in->setData("FLATCRITERION", flat_criterion, true);

	in->setData("SPININPUT", filename_spin_input);

	in->setData("MINSTEP",   minstep);
	in->setData("LOWCUTOFF", low_cutoff);
	in->setData("OUTTUNNELINGTIME", is_output_tunnelingtime);

	in->setData("RESTART", is_restart);

	const ParseEcicar ecicar("./ecicar");
	const ParseClusterOut cluster("./cluster.out", ecicar.getIndex());

	WLconf::WLconf PoscarSpin("./poscar.spin", in, cluster.getLabel(), cluster.getCluster(), ecicar.getEci());

	const int N = PoscarSpin.getSpins().size();

	std::vector<int> index_neglect_bin = PoscarSpin.getNeglectBinIndex();

	std::cout << "----------  initial correlation functions" << std::endl;
	PoscarSpin.dispCorr();
	std::cout << std::endl;
	std::cout << std::endl;

	std::cout << "----------  Information about [wang-landau.ini]" << std::endl;
	in->disp();

	if( index_neglect_bin.size() and  filename_spin_input.size() ){
		std::cout << "NEGLECT BIN INDEX :" << std::endl;
		std::cout << " ";
		for(auto i : index_neglect_bin) std::cout << i << " ";
		std::cout << std::endl;
	}
	std::cout << std::endl;
	std::cout << std::endl;

	auto start = std::chrono::system_clock::now();

	std::cout << "----------  Log  ----------" << std::endl;
	std::cout << std::endl;

	std::vector<double>  dos(bin, 0);

	std::string filename_rep_macrostate = "macrostate.out";
	std::ofstream ofs_macrostate(filename_rep_macrostate);
	ofs_macrostate.setf(std::ios_base::fixed, std::ios_base::floatfield);
	ofs_macrostate.close();

	unsigned int fstep = 0;
	unsigned int tstep = 0;
	unsigned int mc_time = 0;
	unsigned int tunneling_time_start = 0;
	unsigned int tunneling_time_end   = 0;

	bool isConverged = false;

	start = std::chrono::system_clock::now();

	auto f_start = std::chrono::system_clock::now();
	auto f_end   = std::chrono::system_clock::now();

	/*  set lowest/highest index for tunneling-time calculation  */
	int index_lowest = 0, index_highest = bin-1;
	if( is_restart>0 ){
		WLconf::restart(fstep, logfactor, dos, index_neglect_bin);

		if( index_neglect_bin.size()>0 ){

			for(int i=0; i<bin; ++i){
				if( i != index_neglect_bin[i] ){
					index_lowest = i;
					break;
				}
			}

			for(int i=bin; i>=0; --i){
				if( i != index_neglect_bin[i] ){
					index_highest = i;
					break;
				}
			}

		}

	}

	enum class TunnelingTimeStartPoint
	{
		Lowest,
		Highest,
	};
	TunnelingTimeStartPoint randomwalk_start_point = TunnelingTimeStartPoint::Lowest;
	std::ofstream ofs_tunneling_time("tunneling_time.out");
	ofs_tunneling_time.setf(std::ios_base::fixed, std::ios_base::floatfield);

 	int final_mcsweep = 0;
 	while(logflimit < logfactor){
		std::vector<double> histogram(bin, 0);
		std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
		std::cout << std::setprecision(10) << "--- fstep " << fstep << " --  log(factor) = " << logfactor << std::endl;
		for(int i=1; ; ++i, ++mc_time){
			for(int j=0; j<N ; ++j){  // start a MC sweep

				int before_index = PoscarSpin.getIndex();

				wl_step(PoscarSpin, dos);
				PoscarSpin.setIndex();
				int index = PoscarSpin.getIndex();

				if( dos[index] == 0 ){
					auto it = find( index_neglect_bin.begin(), index_neglect_bin.end() , index);
					if( it != index_neglect_bin.end() ){
						dos[index] = dos[PoscarSpin.getBeforeIndex()];
						histogram[index] = histogram[PoscarSpin.getBeforeIndex()];
						index_neglect_bin.erase(it);
						PoscarSpin.outputEnergySpin(index, filename_rep_macrostate);

						if( index < index_lowest  ) index_lowest  = index;
						if( index > index_highest ) index_highest = index;

					}
				}

				if( index == index_lowest and randomwalk_start_point == TunnelingTimeStartPoint::Highest ){
					tunneling_time_end   = mc_time;
					ofs_tunneling_time << fstep << " " << index << " " << tunneling_time_end - tunneling_time_start << std::endl;
					tunneling_time_start = tunneling_time_end;
					randomwalk_start_point =  TunnelingTimeStartPoint::Lowest;
				} else if ( index == index_highest and randomwalk_start_point == TunnelingTimeStartPoint::Lowest ){
					tunneling_time_end   = mc_time;
					ofs_tunneling_time << fstep << " " << index << " " << tunneling_time_end - tunneling_time_start << std::endl;
					tunneling_time_start = tunneling_time_end;
					randomwalk_start_point =  TunnelingTimeStartPoint::Highest;
				}

				dos.at(index) += logfactor;
				histogram.at(index) += 1;

			}  /*  end a MC sweep */

			if((i % mcstep) == 0){
				WLconf::outputHistogram(dos,  histogram, emin, edelta, fstep);
				PoscarSpin.outputPoscar("latest");
				std::cout << i << "sweep done " << std::endl;
			}
			if((i % flatcheck_step) == 0 and WLconf::checkHistogramFlat(histogram, index_neglect_bin, flat_criterion, minstep, low_cutoff)){
				WLconf::outputHistogram(dos,  histogram, emin, edelta, fstep);
				final_mcsweep = i;
				break;
			}
		}
		f_end = std::chrono::system_clock::now();
		auto f_sec = std::chrono::duration_cast<std::chrono::seconds>(f_end-f_start).count();
		std::cout << " fstep = " << fstep << " " << f_sec << " seconds "<< final_mcsweep << " sweeps" << std::endl;
		f_start = std::chrono::system_clock::now();
		logfactor/=2.0;
		++fstep;
	}

	ofs_tunneling_time.close();
	auto end = std::chrono::system_clock::now();
	auto sec = std::chrono::duration_cast<std::chrono::seconds>(end-start).count();
	std::cout << "Time for calculating the DOS is " << sec << " seconds. "<< std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << "check final correlation functions" << std::endl;
	PoscarSpin.dispCorr();
	std::cout << "---------------------------" << std::endl;
	PoscarSpin.setInitialCorrelationFunction();
	PoscarSpin.dispCorr();

	return 0;
}
<commit_msg>add NUMIGNOREEDGEINDEX tag to calculate tunneling-time in canonical ensemble within given time<commit_after>#include <iomanip>
#include <iterator>
#include <numeric>
#include <random>
#include <chrono>

#include "./parser.hpp"
#include "./input.hpp"
#include "./wlconf.hpp"

void dispInput(std::shared_ptr<Input> in){
	//  [INPUT]
	std::cout << "EMIN          : " << in->getDataByString("EMIN") << std::endl;
	std::cout << "EMAX          : " << in->getDataByString("EMAX") << std::endl;
	std::cout << "BIN           : " << in->getDataByString("BIN")  << std::endl;
	std::cout << "MCSTEP        : " << in->getDataByString("MCSTEP")        << std::endl;
	std::cout << "FLATCHECKSTEP : " << in->getDataByString("FLATCHECKSTEP") << std::endl;
	std::cout << "LOGFACTOR     : " << in->getDataByString("LOGFACTOR")     << std::endl;
	std::cout << "FLATCRITERION : " << in->getDataByString("FLATCRITERION") << std::endl;

	//  [OPTION]
	std::cout << "CHEMIPOT      : " << in->getDataByString("CHEMIPOT")  << std::endl;
	std::cout << "SPININPUT     : " << in->getDataByString("SPININPUT") << std::endl;
	std::cout << "SETRANDOM     : " << in->getDataByString("SETRANDOM") << std::endl;
}

double wl_step(WLconf::WLconf& conf, const std::vector<double>& dos){
	conf.setTotalEnergy();
	conf.setIndex();
	int index_before = conf.getIndex();
	int index_after  = index_before;

	conf.setNewConf();
	index_after  = conf.getIndex();

	double b = exp(dos.at(index_before) - dos.at(index_after));
	if(b>=1.0 or b>conf.RandReal()){
	} else {
		conf.Memento();
	}
	return conf.getTotalEnergy();
}

int main(int argc, char* argv[]){
	std::shared_ptr<Input> in(new Input("wang-landau.ini"));

	int mcstep, bin, flatcheck_step, num_ignore_edge_index=0, minstep=0;
	double logfactor, logflimit, emin, emax, edelta, flat_criterion;
	double low_cutoff = 1.0;
	int is_restart=0, is_output_tunnelingtime=0;

	std::string filename_spin_input;

	in->setData("BIN",  bin, true);
	in->setData("MCSTEP", mcstep, true);

	in->setData("EMIN", emin, true);
	in->setData("EMAX", emax, true);
	edelta = (emax - emin) / (double)bin;

	in->setData("FLATCHECKSTEP", flatcheck_step, true);
	in->setData("LOGFACTOR", logfactor, true);
	in->setData("LOGFLIMIT", logflimit, true);
	in->setData("FLATCRITERION", flat_criterion, true);

	in->setData("SPININPUT", filename_spin_input);

	in->setData("MINSTEP",   minstep);
	in->setData("NUMIGNOREEDGEINDEX",   minstep);
	in->setData("LOWCUTOFF", low_cutoff);
	in->setData("OUTTUNNELINGTIME", is_output_tunnelingtime);

	in->setData("RESTART", is_restart);

	const ParseEcicar ecicar("./ecicar");
	const ParseClusterOut cluster("./cluster.out", ecicar.getIndex());

	WLconf::WLconf PoscarSpin("./poscar.spin", in, cluster.getLabel(), cluster.getCluster(), ecicar.getEci());

	const int N = PoscarSpin.getSpins().size();

	std::vector<int> index_neglect_bin = PoscarSpin.getNeglectBinIndex();

	std::cout << "----------  initial correlation functions" << std::endl;
	PoscarSpin.dispCorr();
	std::cout << std::endl;
	std::cout << std::endl;

	std::cout << "----------  Information about [wang-landau.ini]" << std::endl;
	in->disp();

	if( index_neglect_bin.size() and  filename_spin_input.size() ){
		std::cout << "NEGLECT BIN INDEX :" << std::endl;
		std::cout << " ";
		for(auto i : index_neglect_bin) std::cout << i << " ";
		std::cout << std::endl;
	}
	std::cout << std::endl;
	std::cout << std::endl;

	auto start = std::chrono::system_clock::now();

	std::cout << "----------  Log  ----------" << std::endl;
	std::cout << std::endl;

	std::vector<double>  dos(bin, 0);

	std::string filename_rep_macrostate = "macrostate.out";
	std::ofstream ofs_macrostate(filename_rep_macrostate);
	ofs_macrostate.setf(std::ios_base::fixed, std::ios_base::floatfield);
	ofs_macrostate.close();

	unsigned int fstep = 0;
	unsigned int tstep = 0;
	unsigned int mc_time = 0;
	unsigned int tunneling_time_start = 0;
	unsigned int tunneling_time_end   = 0;

	bool isConverged = false;

	start = std::chrono::system_clock::now();

	auto f_start = std::chrono::system_clock::now();
	auto f_end   = std::chrono::system_clock::now();

	/*  set lowest/highest index for tunneling-time calculation  */
	int index_lowest = bin-1, index_highest = 0;
	if( is_restart>0 ){
		WLconf::restart(fstep, logfactor, dos, index_neglect_bin);

		if( index_neglect_bin.size()>0 ){

			for(int i=0; i<bin; ++i){
				if( i != index_neglect_bin[i] ){
					index_lowest = i;
					break;
				}
			}

			for(int i=bin; i>=0; --i){
				if( i != index_neglect_bin[i] ){
					index_highest = i;
					break;
				}
			}

		}

	}

	enum class TunnelingTimeStartPoint
	{
		Lowest,
		Highest,
	};
	TunnelingTimeStartPoint randomwalk_start_point = TunnelingTimeStartPoint::Lowest;
	std::ofstream ofs_tunneling_time("tunneling_time.out");
	ofs_tunneling_time.setf(std::ios_base::fixed, std::ios_base::floatfield);

 	int final_mcsweep = 0;
 	while(logflimit < logfactor){
		std::vector<double> histogram(bin, 0);
		std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
		std::cout << std::setprecision(10) << "--- fstep " << fstep << " --  log(factor) = " << logfactor << std::endl;
		for(int i=1; ; ++i, ++mc_time){
			for(int j=0; j<N ; ++j){  // start a MC sweep

				int before_index = PoscarSpin.getIndex();

				wl_step(PoscarSpin, dos);
				PoscarSpin.setIndex();
				int index = PoscarSpin.getIndex();

				if( dos[index] == 0 ){
					auto it = find( index_neglect_bin.begin(), index_neglect_bin.end() , index);
					if( it != index_neglect_bin.end() ){
						dos[index] = dos[PoscarSpin.getBeforeIndex()];
						histogram[index] = histogram[PoscarSpin.getBeforeIndex()];
						index_neglect_bin.erase(it);
						PoscarSpin.outputEnergySpin(index, filename_rep_macrostate);

						if( index < index_lowest  ) index_lowest  = index;
						if( index > index_highest ) index_highest = index;

					}
				}

				if( index <= (index_lowest+num_ignore_edge_index) and randomwalk_start_point == TunnelingTimeStartPoint::Highest ){
					tunneling_time_end   = mc_time;
					ofs_tunneling_time << fstep << " " << index << " " << tunneling_time_end - tunneling_time_start << std::endl;
					tunneling_time_start = tunneling_time_end;
					randomwalk_start_point =  TunnelingTimeStartPoint::Lowest;
				} else if ( index >= (index_highest-num_ignore_edge_index) and randomwalk_start_point == TunnelingTimeStartPoint::Lowest ){
					tunneling_time_end   = mc_time;
					ofs_tunneling_time << fstep << " " << index << " " << tunneling_time_end - tunneling_time_start << std::endl;
					tunneling_time_start = tunneling_time_end;
					randomwalk_start_point =  TunnelingTimeStartPoint::Highest;
				}

				dos[index] += logfactor;
				histogram[index] += 1;

			}  /*  end a MC sweep */

			if((i % mcstep) == 0){
				WLconf::outputHistogram(dos,  histogram, emin, edelta, fstep);
				PoscarSpin.outputPoscar("latest");
				std::cout << i << "sweep done " << std::endl;
			}
			if((i % flatcheck_step) == 0 and WLconf::checkHistogramFlat(histogram, index_neglect_bin, flat_criterion, minstep, low_cutoff)){
				WLconf::outputHistogram(dos,  histogram, emin, edelta, fstep);
				final_mcsweep = i;
				break;
			}
		}
		f_end = std::chrono::system_clock::now();
		auto f_sec = std::chrono::duration_cast<std::chrono::seconds>(f_end-f_start).count();
		std::cout << " fstep = " << fstep << " " << f_sec << " seconds "<< final_mcsweep << " sweeps" << std::endl;
		f_start = std::chrono::system_clock::now();
		logfactor/=2.0;
		++fstep;
	}

	ofs_tunneling_time.close();
	auto end = std::chrono::system_clock::now();
	auto sec = std::chrono::duration_cast<std::chrono::seconds>(end-start).count();
	std::cout << "Time for calculating the DOS is " << sec << " seconds. "<< std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << "check final correlation functions" << std::endl;
	PoscarSpin.dispCorr();
	std::cout << "---------------------------" << std::endl;
	PoscarSpin.setInitialCorrelationFunction();
	PoscarSpin.dispCorr();

	return 0;
}
<|endoftext|>


<commit_before>/**
 * @file Cosa/RTC.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_RTC_HH__
#define __COSA_RTC_HH__

#include <avr/sleep.h>
#include "Cosa/Types.h"
#include "Cosa/Board.hh"

/**
 * Real-time clock; Arduino/ATmega328P Timer0 for micro/milli-
 * second timing.
 *
 * @section Limitations
 * Coexists with the Arduino timer 0 interrupt handler. Alternative
 * design where the counter match interrupt is used.
 */
class RTC {
  /**
   * Milli-second interrupt handler callback function prototype.
   * @param[in] env interrupt handler environment.
   */
  typedef void (*InterruptHandler)(void* env);

private:
  static uint8_t s_initiated;
  static volatile uint32_t s_uticks;
  static volatile uint32_t s_ms;
  static volatile uint16_t s_mticks;
  static volatile uint32_t s_sec;
  static InterruptHandler s_handler;
  static void* s_env;

  /**
   * Interrupt handlers are friends.
   */
  friend void TIMER0_COMPA_vect(void);
  friend void TIMER0_COMPB_vect(void);

  /**
   * Do not allow instances. This is a static singleton; name space.
   */
  RTC() {}

public:
  /**
   * Start the Real-Time Clock.
   * @param[in] handler of milli-second interrupts.
   * @param[in] env handler environment.
   * @return bool true(1) if successful otherwise false(0).
   */
  static bool begin(InterruptHandler handler = 0, void* env = 0);

  /**
   * Stop the Real-Time Clock.
   * @return bool true(1) if successful otherwise false(0).
   */
  static bool end();

  /**
   * Get number of micro-seconds per tick.
   * @return micro-seconds.
   */
  static uint16_t us_per_tick();

  /**
   * Set milli-second timeout interrupt handler.
   * @param[in] fn interrupt handler.
   * @param[in] env environment pointer.
   */
  static void set(InterruptHandler fn, void* env = 0)
  {
    synchronized {
      s_handler = fn;
      s_env = env;
    }
  }

  /**
   * Set clock (seconds) to real-time (for instance seconds from a
   * given date).
   * @param[in] sec.
   */
  static void set(uint32_t sec)
  {
    synchronized {
      s_sec = sec;
    }
  }

  /**
   * Returns number of milli-seconds from given start.
   * @param[in] start
   * @return (now - start)
   */
  static uint32_t since(uint32_t start)
  {
    return ((((uint32_t) -1L) - start) + RTC::millis());
  }

  /**
   * Return the current clock in micro-seconds.
   * @return micro-seconds.
   */
  static uint32_t micros();

  /**
   * Return the current clock in milli-seconds.
   * @return milli-seconds.
   */
  static uint32_t millis();

  /**
   * Return the current clock in seconds.
   * @return seconds.
   */
  static uint32_t seconds()
  {
    uint32_t res;
    synchronized {
      res = s_sec;
    }
    return (res);
  }

  /**
   * Delay using the real-time clock.
   * @param[in] ms sleep period in milli-seconds.
   */
  static void delay(uint16_t ms, uint8_t mode = SLEEP_MODE_IDLE);
};

#endif

<commit_msg>Adding difference between two timestamps.<commit_after>/**
 * @file Cosa/RTC.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_RTC_HH__
#define __COSA_RTC_HH__

#include <avr/sleep.h>
#include "Cosa/Types.h"
#include "Cosa/Board.hh"

/**
 * Real-time clock; Arduino/ATmega328P Timer0 for micro/milli-
 * second timing.
 *
 * @section Limitations
 * Coexists with the Arduino timer 0 interrupt handler. Alternative
 * design where the counter match interrupt is used.
 */
class RTC {
  /**
   * Milli-second interrupt handler callback function prototype.
   * @param[in] env interrupt handler environment.
   */
  typedef void (*InterruptHandler)(void* env);

private:
  static uint8_t s_initiated;
  static volatile uint32_t s_uticks;
  static volatile uint32_t s_ms;
  static volatile uint16_t s_mticks;
  static volatile uint32_t s_sec;
  static InterruptHandler s_handler;
  static void* s_env;

  /**
   * Interrupt handlers are friends.
   */
  friend void TIMER0_COMPA_vect(void);
  friend void TIMER0_COMPB_vect(void);

  /**
   * Do not allow instances. This is a static singleton; name space.
   */
  RTC() {}

public:
  /**
   * Start the Real-Time Clock.
   * @param[in] handler of milli-second interrupts.
   * @param[in] env handler environment.
   * @return bool true(1) if successful otherwise false(0).
   */
  static bool begin(InterruptHandler handler = 0, void* env = 0);

  /**
   * Stop the Real-Time Clock.
   * @return bool true(1) if successful otherwise false(0).
   */
  static bool end();

  /**
   * Get number of micro-seconds per tick.
   * @return micro-seconds.
   */
  static uint16_t us_per_tick();

  /**
   * Set milli-second timeout interrupt handler.
   * @param[in] fn interrupt handler.
   * @param[in] env environment pointer.
   */
  static void set(InterruptHandler fn, void* env = 0)
  {
    synchronized {
      s_handler = fn;
      s_env = env;
    }
  }

  /**
   * Set clock (seconds) to real-time (for instance seconds from a
   * given date).
   * @param[in] sec.
   */
  static void set(uint32_t sec)
  {
    synchronized {
      s_sec = sec;
    }
  }

  /**
   * Returns difference between given time stamps.
   * @param[in] x
   * @param[in] y
   * @return (x - y)
   */
  static uint32_t diff(uint32_t x, uint32_t y)
  {
    return ((((uint32_t) -1L) - y) + x);
  }

  /**
   * Returns number of milli-seconds from given start.
   * @param[in] start
   * @return (millis()- start)
   */
  static uint32_t since(uint32_t start)
  {
    return (diff(millis(), start));
  }

  /**
   * Return the current clock in micro-seconds.
   * @return micro-seconds.
   */
  static uint32_t micros();

  /**
   * Return the current clock in milli-seconds.
   * @return milli-seconds.
   */
  static uint32_t millis();

  /**
   * Return the current clock in seconds.
   * @return seconds.
   */
  static uint32_t seconds()
  {
    uint32_t res;
    synchronized {
      res = s_sec;
    }
    return (res);
  }

  /**
   * Delay using the real-time clock.
   * @param[in] ms sleep period in milli-seconds.
   */
  static void delay(uint16_t ms, uint8_t mode = SLEEP_MODE_IDLE);
};

#endif

<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <SFML/Network.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>

#include "vectorUtils.h"
#include "resources.h"
#include "soundManager.h"
#include "random.h"

#define MAX_SOUNDS 16

SoundManager* soundManager;

SoundManager::SoundManager()
{
    //By creating a SoundBuffer we force SFML to load the sound subsystem. Else this is done when the first sound is loaded, causing a delay at that point.
    sf::SoundBuffer forceLoadBuffer;

    for(unsigned int n=0; n<MAX_SOUNDS; n++)
        activeSoundList.push_back(sf::Sound());

    music_volume = 100.0;
    positional_sound_enabled = false;
}

SoundManager::~SoundManager()
{
}

void SoundManager::playMusic(string name)
{
    music_set.clear();
    P<ResourceStream> stream = getResourceStream(name);
    if (stream)
        startMusic(stream, true);
}

void SoundManager::playMusicSet(std::vector<string> filenames)
{
    music_set = filenames;
    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
}

void SoundManager::stopMusic()
{
    music_set.clear();
    primary_music.music.stop();
    secondary_music.music.stop();
}

void SoundManager::setMusicVolume(float volume)
{
    if (music_volume != volume)
    {
        music_volume = volume;
        if (primary_music.mode == None)
            primary_music.music.setVolume(music_volume);
        if (secondary_music.mode == None)
            secondary_music.music.setVolume(music_volume);
    }
}

float SoundManager::getMusicVolume()
{
    return music_volume;
}

void SoundManager::playSound(string name, float pitch, float volume)
{
    sf::SoundBuffer* data = soundMap[name];
    if (data == NULL)
        data = loadSound(name);

    playSoundData(data, pitch, volume);
}

void SoundManager::setListenerPosition(sf::Vector2f position, float angle)
{
    sf::Vector2f listen_vector = sf::vector2FromAngle(angle);
    sf::Listener::setPosition(position.x, 0, position.y);
    sf::Listener::setDirection(listen_vector.x, 0, listen_vector.y);
    positional_sound_enabled = true;
}

void SoundManager::disablePositionalSound()
{
    positional_sound_enabled = false;
}

void SoundManager::playSound(string name, sf::Vector2f position, float min_distance, float attenuation, float pitch, float volume)
{
    if (!positional_sound_enabled)
        return;
    sf::SoundBuffer* data = soundMap[name];
    if (data == NULL)
        data = loadSound(name);
    if (data->getChannelCount() > 1)
        LOG(WARNING) << name << ": Used as positional sound but has more then 1 channel.";

    for(unsigned int n=0; n<activeSoundList.size(); n++)
    {
        sf::Sound& sound = activeSoundList[n];
        if (sound.getStatus() == sf::Sound::Stopped)
        {
            sound.setBuffer(*data);
            sound.setRelativeToListener(false);
            sound.setMinDistance(min_distance);
            sound.setAttenuation(attenuation);
            sound.setPosition(position.x, 0, position.y);
            sound.setPitch(pitch);
            sound.setVolume(volume);
            sound.play();
            return;
        }
    }
}

void SoundManager::setTextToSpeachVoice(string name)
{
}

string url_encode(const string &value) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
        string::value_type c = (*i);
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
        }
        else if (c == ' ')  {
            escaped << '+';
        }
        else {
            escaped << '%' << std::setw(2) << ((int) c) << std::setw(0);
        }
    }

    return escaped.str();
}

void SoundManager::playTextToSpeech(string text)
{
    string name = "TTS:" + text;
    sf::SoundBuffer* data = soundMap[name];
    if (data != NULL)
    {
        playSoundData(data, 1.0, 100.0);
        return;
    }

    sf::Http http("localhost", 59125);
    sf::Http::Request request("process?INPUT_TEXT=" + url_encode(text) + "&INPUT_TYPE=TEXT&OUTPUT_TYPE=AUDIO&AUDIO=WAVE_FILE&LOCALE=en_US&VOICE=dfki-prudence");
    sf::Http::Response response = http.sendRequest(request);

    sf::Http::Response::Status status = response.getStatus();
    if (status == sf::Http::Response::Ok)
    {
        string wave = response.getBody();
        sf::SoundBuffer* data = new sf::SoundBuffer();
        data->loadFromMemory(wave.data(), wave.size());
        soundMap[name] = data;
        playSoundData(data, 1.0, 100.0);
    }
    else
    {
        std::cout << "Error requesting text to speech from Mary server: " << status << std::endl;
    }
}

void SoundManager::playSoundData(sf::SoundBuffer* data, float pitch, float volume)
{
    for(unsigned int n=0; n<activeSoundList.size(); n++)
    {
        sf::Sound& sound = activeSoundList[n];
        if (sound.getStatus() == sf::Sound::Stopped)
        {
            sound.setBuffer(*data);
            sound.setRelativeToListener(true);
            sound.setMinDistance(1);
            sound.setAttenuation(0);
            sound.setPitch(pitch);
            sound.setVolume(volume);
            sound.setPosition(0, 0, 0);
            sound.play();
            return;
        }
    }
}

sf::SoundBuffer* SoundManager::loadSound(string name)
{
    sf::SoundBuffer* data = soundMap[name];
    if (data)
        return data;

    data = new sf::SoundBuffer();

    P<ResourceStream> stream = getResourceStream(name);
    if (!stream) stream = getResourceStream(name + ".wav");
    if (!stream || !data->loadFromStream(**stream))
    {
        LOG(WARNING) << "Failed to load: " << name;
        soundMap[name] = data;
        return data;
    }

    LOG(INFO) << "Loaded: " << name << " of " << data->getDuration().asSeconds() << " seconds";
    soundMap[name] = data;
    return data;
}

void SoundManager::startMusic(P<ResourceStream> stream, bool loop)
{
    if (!stream)
        return;

    MusicChannel* channel = &primary_music;
    MusicChannel* other_channel = &secondary_music;

    if (primary_music.music.getStatus() != sf::Music::Stopped)
    {
        channel = &secondary_music;
        other_channel = &primary_music;
    }

    channel->music.stop();
    channel->mode = FadeIn;
    channel->fade_delay = fade_music_time;
    channel->music.openFromStream(**stream);
    channel->stream = stream;
    channel->music.setLoop(loop);
    channel->music.setVolume(0);
    channel->music.play();

    if (other_channel->music.getStatus() != sf::Music::Stopped)
    {
        other_channel->mode = FadeOut;
        other_channel->fade_delay = fade_music_time;
    }
}

void SoundManager::updateTick()
{
    float delta = clock.restart().asSeconds();
    updateChannel(primary_music, delta);
    updateChannel(secondary_music, delta);

    if (music_set.size() > 0)
    {
        if (primary_music.music.getStatus() == sf::Music::Playing && primary_music.mode == None)
        {
            if (secondary_music.music.getStatus() == sf::Music::Stopped)
            {
                if (primary_music.music.getPlayingOffset() > primary_music.music.getDuration() - sf::seconds(fade_music_time))
                {
                    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
                }
            }
        }

        if (secondary_music.music.getStatus() == sf::Music::Playing && secondary_music.mode == None)
        {
            if (primary_music.music.getStatus() == sf::Music::Stopped)
            {
                if (secondary_music.music.getPlayingOffset() > secondary_music.music.getDuration() - sf::seconds(fade_music_time))
                {
                    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
                }
            }
        }
    }
}

void SoundManager::updateChannel(MusicChannel& channel, float delta)
{
    switch(channel.mode)
    {
    case None:
        break;
    case FadeIn:
        channel.fade_delay -= delta;
        if (channel.fade_delay > 0.0)
        {
            channel.music.setVolume(music_volume * (1.0 - (channel.fade_delay / fade_music_time)));
        }else{
            channel.music.setVolume(music_volume);
            channel.mode = None;
        }
        break;
    case FadeOut:
        channel.fade_delay -= delta;
        if (channel.fade_delay > 0.0)
        {
            channel.music.setVolume(music_volume * (channel.fade_delay / fade_music_time));
        }else{
            channel.music.stop();
            channel.mode = None;
        }
        break;
    }
}
<commit_msg>Small uninitialize fix.<commit_after>#include <stdio.h>
#include <string.h>
#include <SFML/Network.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>

#include "vectorUtils.h"
#include "resources.h"
#include "soundManager.h"
#include "random.h"

#define MAX_SOUNDS 16

SoundManager* soundManager;

SoundManager::SoundManager()
{
    //By creating a SoundBuffer we force SFML to load the sound subsystem. Else this is done when the first sound is loaded, causing a delay at that point.
    sf::SoundBuffer forceLoadBuffer;

    for(unsigned int n=0; n<MAX_SOUNDS; n++)
        activeSoundList.push_back(sf::Sound());

    music_volume = 100.0;
    positional_sound_enabled = false;
    primary_music.mode = None;
    secondary_music.mode = None;
}

SoundManager::~SoundManager()
{
}

void SoundManager::playMusic(string name)
{
    music_set.clear();
    P<ResourceStream> stream = getResourceStream(name);
    if (stream)
        startMusic(stream, true);
}

void SoundManager::playMusicSet(std::vector<string> filenames)
{
    music_set = filenames;
    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
}

void SoundManager::stopMusic()
{
    music_set.clear();
    primary_music.music.stop();
    secondary_music.music.stop();
}

void SoundManager::setMusicVolume(float volume)
{
    if (music_volume != volume)
    {
        music_volume = volume;
        if (primary_music.mode == None)
            primary_music.music.setVolume(music_volume);
        if (secondary_music.mode == None)
            secondary_music.music.setVolume(music_volume);
    }
}

float SoundManager::getMusicVolume()
{
    return music_volume;
}

void SoundManager::playSound(string name, float pitch, float volume)
{
    sf::SoundBuffer* data = soundMap[name];
    if (data == NULL)
        data = loadSound(name);

    playSoundData(data, pitch, volume);
}

void SoundManager::setListenerPosition(sf::Vector2f position, float angle)
{
    sf::Vector2f listen_vector = sf::vector2FromAngle(angle);
    sf::Listener::setPosition(position.x, 0, position.y);
    sf::Listener::setDirection(listen_vector.x, 0, listen_vector.y);
    positional_sound_enabled = true;
}

void SoundManager::disablePositionalSound()
{
    positional_sound_enabled = false;
}

void SoundManager::playSound(string name, sf::Vector2f position, float min_distance, float attenuation, float pitch, float volume)
{
    if (!positional_sound_enabled)
        return;
    sf::SoundBuffer* data = soundMap[name];
    if (data == NULL)
        data = loadSound(name);
    if (data->getChannelCount() > 1)
        LOG(WARNING) << name << ": Used as positional sound but has more then 1 channel.";

    for(unsigned int n=0; n<activeSoundList.size(); n++)
    {
        sf::Sound& sound = activeSoundList[n];
        if (sound.getStatus() == sf::Sound::Stopped)
        {
            sound.setBuffer(*data);
            sound.setRelativeToListener(false);
            sound.setMinDistance(min_distance);
            sound.setAttenuation(attenuation);
            sound.setPosition(position.x, 0, position.y);
            sound.setPitch(pitch);
            sound.setVolume(volume);
            sound.play();
            return;
        }
    }
}

void SoundManager::setTextToSpeachVoice(string name)
{
}

string url_encode(const string &value) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
        string::value_type c = (*i);
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
        }
        else if (c == ' ')  {
            escaped << '+';
        }
        else {
            escaped << '%' << std::setw(2) << ((int) c) << std::setw(0);
        }
    }

    return escaped.str();
}

void SoundManager::playTextToSpeech(string text)
{
    string name = "TTS:" + text;
    sf::SoundBuffer* data = soundMap[name];
    if (data != NULL)
    {
        playSoundData(data, 1.0, 100.0);
        return;
    }

    sf::Http http("localhost", 59125);
    sf::Http::Request request("process?INPUT_TEXT=" + url_encode(text) + "&INPUT_TYPE=TEXT&OUTPUT_TYPE=AUDIO&AUDIO=WAVE_FILE&LOCALE=en_US&VOICE=dfki-prudence");
    sf::Http::Response response = http.sendRequest(request);

    sf::Http::Response::Status status = response.getStatus();
    if (status == sf::Http::Response::Ok)
    {
        string wave = response.getBody();
        sf::SoundBuffer* data = new sf::SoundBuffer();
        data->loadFromMemory(wave.data(), wave.size());
        soundMap[name] = data;
        playSoundData(data, 1.0, 100.0);
    }
    else
    {
        std::cout << "Error requesting text to speech from Mary server: " << status << std::endl;
    }
}

void SoundManager::playSoundData(sf::SoundBuffer* data, float pitch, float volume)
{
    for(unsigned int n=0; n<activeSoundList.size(); n++)
    {
        sf::Sound& sound = activeSoundList[n];
        if (sound.getStatus() == sf::Sound::Stopped)
        {
            sound.setBuffer(*data);
            sound.setRelativeToListener(true);
            sound.setMinDistance(1);
            sound.setAttenuation(0);
            sound.setPitch(pitch);
            sound.setVolume(volume);
            sound.setPosition(0, 0, 0);
            sound.play();
            return;
        }
    }
}

sf::SoundBuffer* SoundManager::loadSound(string name)
{
    sf::SoundBuffer* data = soundMap[name];
    if (data)
        return data;

    data = new sf::SoundBuffer();

    P<ResourceStream> stream = getResourceStream(name);
    if (!stream) stream = getResourceStream(name + ".wav");
    if (!stream || !data->loadFromStream(**stream))
    {
        LOG(WARNING) << "Failed to load: " << name;
        soundMap[name] = data;
        return data;
    }

    LOG(INFO) << "Loaded: " << name << " of " << data->getDuration().asSeconds() << " seconds";
    soundMap[name] = data;
    return data;
}

void SoundManager::startMusic(P<ResourceStream> stream, bool loop)
{
    if (!stream)
        return;

    MusicChannel* channel = &primary_music;
    MusicChannel* other_channel = &secondary_music;

    if (primary_music.music.getStatus() != sf::Music::Stopped)
    {
        channel = &secondary_music;
        other_channel = &primary_music;
    }

    channel->music.stop();
    channel->mode = FadeIn;
    channel->fade_delay = fade_music_time;
    channel->music.openFromStream(**stream);
    channel->stream = stream;
    channel->music.setLoop(loop);
    channel->music.setVolume(0);
    channel->music.play();

    if (other_channel->music.getStatus() != sf::Music::Stopped)
    {
        other_channel->mode = FadeOut;
        other_channel->fade_delay = fade_music_time;
    }
}

void SoundManager::updateTick()
{
    float delta = clock.restart().asSeconds();
    updateChannel(primary_music, delta);
    updateChannel(secondary_music, delta);

    if (music_set.size() > 0)
    {
        if (primary_music.music.getStatus() == sf::Music::Playing && primary_music.mode == None)
        {
            if (secondary_music.music.getStatus() == sf::Music::Stopped)
            {
                if (primary_music.music.getPlayingOffset() > primary_music.music.getDuration() - sf::seconds(fade_music_time))
                {
                    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
                }
            }
        }

        if (secondary_music.music.getStatus() == sf::Music::Playing && secondary_music.mode == None)
        {
            if (primary_music.music.getStatus() == sf::Music::Stopped)
            {
                if (secondary_music.music.getPlayingOffset() > secondary_music.music.getDuration() - sf::seconds(fade_music_time))
                {
                    startMusic(getResourceStream(music_set[irandom(0, music_set.size() - 1)]), false);
                }
            }
        }
    }
}

void SoundManager::updateChannel(MusicChannel& channel, float delta)
{
    switch(channel.mode)
    {
    case None:
        break;
    case FadeIn:
        channel.fade_delay -= delta;
        if (channel.fade_delay > 0.0)
        {
            channel.music.setVolume(music_volume * (1.0 - (channel.fade_delay / fade_music_time)));
        }else{
            channel.music.setVolume(music_volume);
            channel.mode = None;
        }
        break;
    case FadeOut:
        channel.fade_delay -= delta;
        if (channel.fade_delay > 0.0)
        {
            channel.music.setVolume(music_volume * (channel.fade_delay / fade_music_time));
        }else{
            channel.music.stop();
            channel.mode = None;
        }
        break;
    }
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <qmdnsengine/dns.h>
#include <qmdnsengine/hostname.h>
#include <qmdnsengine/mdns.h>
#include <qmdnsengine/message.h>
#include <qmdnsengine/prober.h>
#include <qmdnsengine/provider.h>
#include <qmdnsengine/query.h>
#include <qmdnsengine/server.h>

#include "provider_p.h"

using namespace QMdnsEngine;

ProviderPrivate::ProviderPrivate(QObject *parent, Server *server, Hostname *hostname)
    : QObject(parent),
      server(server),
      hostname(hostname),
      prober(nullptr),
      initialized(false),
      confirmed(false)
{
    connect(server, &Server::messageReceived, this, &ProviderPrivate::onMessageReceived);
    connect(hostname, &Hostname::hostnameChanged, this, &ProviderPrivate::onHostnameChanged);

    browsePtrProposed.setName(MdnsBrowseType);
    browsePtrProposed.setType(PTR);
    ptrProposed.setType(PTR);
    srvProposed.setType(SRV);
    txtProposed.setType(TXT);
}

ProviderPrivate::~ProviderPrivate()
{
    if (confirmed) {
        farewell();
    }
}

void ProviderPrivate::announce()
{
    // Broadcast a message with each of the records

    Message message;
    message.setResponse(true);
    message.addRecord(ptrRecord);
    message.addRecord(srvRecord);
    message.addRecord(txtRecord);
    server->broadcastMessage(message);
}

void ProviderPrivate::confirm()
{
    // Confirm that the desired name is unique through probing

    if (prober) {
        delete prober;
    }
    prober = new Prober(server, srvProposed, this);
    connect(prober, &Prober::nameConfirmed, [this](const QByteArray &name) {

        // If existing records were confirmed, indicate that they are no
        // longer valid
        if (confirmed) {
            farewell();
        } else {
            confirmed = true;
        }

        // Update the proposed records
        ptrProposed.setTarget(name);
        srvProposed.setName(name);
        txtProposed.setName(name);

        // Publish the proposed records and announce them
        publish();

        delete prober;
        prober = nullptr;
    });
}

void ProviderPrivate::farewell()
{
    // Send a message indicating that the existing records are no longer valid
    // by setting their TTL to 0

    ptrRecord.setTtl(0);
    srvRecord.setTtl(0);
    txtRecord.setTtl(0);
    announce();
}

void ProviderPrivate::publish()
{
    // Copy the proposed records over and announce them

    browsePtrRecord = browsePtrProposed;
    ptrRecord = ptrProposed;
    srvRecord = srvProposed;
    txtRecord = txtProposed;
    announce();
}

void ProviderPrivate::onMessageReceived(const Message &message)
{
    if (!confirmed || message.isResponse()) {
        return;
    }

    bool sendBrowsePtr = false;
    bool sendPtr = false;
    bool sendSrv = false;
    bool sendTxt = false;

    // Determine which records to send based on the queries
    foreach (Query query, message.queries()) {
        if (query.type() == PTR && query.name() == MdnsBrowseType) {
            sendBrowsePtr = true;
        } else if (query.type() == PTR && query.name() == ptrRecord.name()) {
            sendPtr = sendSrv = sendTxt = true;
        } else if (query.type() == SRV && query.name() == srvRecord.name()) {
            sendSrv = true;
        } else if (query.type() == TXT && query.name() == txtRecord.name()) {
            sendTxt = true;
        }
    }

    // Remove records to send if they are already known
    foreach (Record record, message.records()) {
        if (record == ptrRecord) {
            sendPtr = false;
        } else if (record == srvRecord) {
            sendSrv = false;
        } else if (record == txtRecord) {
            sendTxt = false;
        }
    }

    // If any records should be sent, compose a message reply
    if (sendBrowsePtr || sendPtr || sendSrv || sendTxt) {
        Message reply;
        reply.reply(message);
        if (sendBrowsePtr) {
            reply.addRecord(browsePtrRecord);
        }
        if (sendPtr) {
            reply.addRecord(ptrRecord);
        }
        if (sendSrv) {
            reply.addRecord(srvRecord);
        }
        if (sendTxt) {
            reply.addRecord(txtRecord);
        }
        server->sendMessage(reply);
    }
}

void ProviderPrivate::onHostnameChanged(const QByteArray &hostname)
{
    // Update the proposed SRV record
    srvProposed.setTarget(hostname);

    // If initialized, confirm the record
    if (initialized) {
        confirm();
    }
}

Provider::Provider(Server *server, Hostname *hostname, QObject *parent)
    : QObject(parent),
      d(new ProviderPrivate(this, server, hostname))
{
}

void Provider::update(const Service &service)
{
    d->initialized = true;

    // Update the proposed records
    QByteArray fqName = service.name() + "." + service.type();
    d->browsePtrProposed.setTarget(service.type());
    d->ptrProposed.setName(service.type());
    d->ptrProposed.setTarget(fqName);
    d->srvProposed.setName(fqName);
    d->srvProposed.setPort(service.port());
    d->srvProposed.setTarget(d->hostname->hostname());
    d->txtProposed.setName(fqName);
    d->txtProposed.setAttributes(service.attributes());

    // Assuming a valid hostname exists, check to see if the new service uses
    // a different name - if so, it must first be confirmed
    if (d->hostname->isRegistered()) {
        if (!d->confirmed || fqName != d->srvRecord.name()) {
            d->confirm();
        } else {
            d->publish();
        }
    }
}
<commit_msg>Eliminate the need to send unnecessary records.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <qmdnsengine/dns.h>
#include <qmdnsengine/hostname.h>
#include <qmdnsengine/mdns.h>
#include <qmdnsengine/message.h>
#include <qmdnsengine/prober.h>
#include <qmdnsengine/provider.h>
#include <qmdnsengine/query.h>
#include <qmdnsengine/server.h>

#include "provider_p.h"

using namespace QMdnsEngine;

ProviderPrivate::ProviderPrivate(QObject *parent, Server *server, Hostname *hostname)
    : QObject(parent),
      server(server),
      hostname(hostname),
      prober(nullptr),
      initialized(false),
      confirmed(false)
{
    connect(server, &Server::messageReceived, this, &ProviderPrivate::onMessageReceived);
    connect(hostname, &Hostname::hostnameChanged, this, &ProviderPrivate::onHostnameChanged);

    browsePtrProposed.setName(MdnsBrowseType);
    browsePtrProposed.setType(PTR);
    ptrProposed.setType(PTR);
    srvProposed.setType(SRV);
    txtProposed.setType(TXT);
}

ProviderPrivate::~ProviderPrivate()
{
    if (confirmed) {
        farewell();
    }
}

void ProviderPrivate::announce()
{
    // Broadcast a message with each of the records

    Message message;
    message.setResponse(true);
    message.addRecord(ptrRecord);
    message.addRecord(srvRecord);
    message.addRecord(txtRecord);
    server->broadcastMessage(message);
}

void ProviderPrivate::confirm()
{
    // Confirm that the desired name is unique through probing

    if (prober) {
        delete prober;
    }
    prober = new Prober(server, srvProposed, this);
    connect(prober, &Prober::nameConfirmed, [this](const QByteArray &name) {

        // If existing records were confirmed, indicate that they are no
        // longer valid
        if (confirmed) {
            farewell();
        } else {
            confirmed = true;
        }

        // Update the proposed records
        ptrProposed.setTarget(name);
        srvProposed.setName(name);
        txtProposed.setName(name);

        // Publish the proposed records and announce them
        publish();

        delete prober;
        prober = nullptr;
    });
}

void ProviderPrivate::farewell()
{
    // Send a message indicating that the existing records are no longer valid
    // by setting their TTL to 0

    ptrRecord.setTtl(0);
    srvRecord.setTtl(0);
    txtRecord.setTtl(0);
    announce();
}

void ProviderPrivate::publish()
{
    // Copy the proposed records over and announce them

    browsePtrRecord = browsePtrProposed;
    ptrRecord = ptrProposed;
    srvRecord = srvProposed;
    txtRecord = txtProposed;
    announce();
}

void ProviderPrivate::onMessageReceived(const Message &message)
{
    if (!confirmed || message.isResponse()) {
        return;
    }

    bool sendBrowsePtr = false;
    bool sendPtr = false;
    bool sendSrv = false;
    bool sendTxt = false;

    // Determine which records to send based on the queries
    foreach (Query query, message.queries()) {
        if (query.type() == PTR && query.name() == MdnsBrowseType) {
            sendBrowsePtr = true;
        } else if (query.type() == PTR && query.name() == ptrRecord.name()) {
            sendPtr = true;
        } else if (query.type() == SRV && query.name() == srvRecord.name()) {
            sendSrv = true;
        } else if (query.type() == TXT && query.name() == txtRecord.name()) {
            sendTxt = true;
        }
    }

    // Remove records to send if they are already known
    foreach (Record record, message.records()) {
        if (record == ptrRecord) {
            sendPtr = false;
        } else if (record == srvRecord) {
            sendSrv = false;
        } else if (record == txtRecord) {
            sendTxt = false;
        }
    }

    // Include the SRV and TXT if the PTR is being sent
    if (sendPtr) {
        sendSrv = sendTxt = true;
    }

    // If any records should be sent, compose a message reply
    if (sendBrowsePtr || sendPtr || sendSrv || sendTxt) {
        Message reply;
        reply.reply(message);
        if (sendBrowsePtr) {
            reply.addRecord(browsePtrRecord);
        }
        if (sendPtr) {
            reply.addRecord(ptrRecord);
        }
        if (sendSrv) {
            reply.addRecord(srvRecord);
        }
        if (sendTxt) {
            reply.addRecord(txtRecord);
        }
        server->sendMessage(reply);
    }
}

void ProviderPrivate::onHostnameChanged(const QByteArray &hostname)
{
    // Update the proposed SRV record
    srvProposed.setTarget(hostname);

    // If initialized, confirm the record
    if (initialized) {
        confirm();
    }
}

Provider::Provider(Server *server, Hostname *hostname, QObject *parent)
    : QObject(parent),
      d(new ProviderPrivate(this, server, hostname))
{
}

void Provider::update(const Service &service)
{
    d->initialized = true;

    // Update the proposed records
    QByteArray fqName = service.name() + "." + service.type();
    d->browsePtrProposed.setTarget(service.type());
    d->ptrProposed.setName(service.type());
    d->ptrProposed.setTarget(fqName);
    d->srvProposed.setName(fqName);
    d->srvProposed.setPort(service.port());
    d->srvProposed.setTarget(d->hostname->hostname());
    d->txtProposed.setName(fqName);
    d->txtProposed.setAttributes(service.attributes());

    // Assuming a valid hostname exists, check to see if the new service uses
    // a different name - if so, it must first be confirmed
    if (d->hostname->isRegistered()) {
        if (!d->confirmed || fqName != d->srvRecord.name()) {
            d->confirm();
        } else {
            d->publish();
        }
    }
}
<|endoftext|>


<commit_before>//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like "dwarfdump".
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/RelocVisitor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
#include <algorithm>
#include <cstring>
#include <list>
#include <string>

using namespace llvm;
using namespace object;

static cl::list<std::string>
InputFilenames(cl::Positional, cl::desc("<input object files>"),
               cl::ZeroOrMore);

static cl::opt<unsigned long long>
Address("address", cl::init(-1ULL),
        cl::desc("Print line information for a given address"));

static cl::opt<bool>
PrintFunctions("functions", cl::init(false),
               cl::desc("Print function names as well as line information "
                        "for a given address"));

static cl::opt<bool>
PrintInlining("inlining", cl::init(false),
              cl::desc("Print all inlined frames for a given address"));

static void PrintDILineInfo(DILineInfo dli) {
  if (PrintFunctions)
    outs() << (dli.getFunctionName() ? dli.getFunctionName() : "<unknown>")
           << "\n";
  outs() << (dli.getFileName() ? dli.getFileName() : "<unknown>") << ':'
         << dli.getLine() << ':' << dli.getColumn() << '\n';
}

static void DumpInput(const StringRef &Filename) {
  OwningPtr<MemoryBuffer> Buff;

  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
    errs() << Filename << ": " << ec.message() << "\n";
    return;
  }

  OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
  OwningPtr<DIContext> dictx(DIContext::getDWARFContext(Obj.get()));

  if (Address == -1ULL) {
    outs() << Filename
           << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
    // Dump the complete DWARF structure.
    dictx->dump(outs());
  } else {
    // Print line info for the specified address.
    int SpecFlags = DILineInfoSpecifier::FileLineInfo |
                    DILineInfoSpecifier::AbsoluteFilePath;
    if (PrintFunctions)
      SpecFlags |= DILineInfoSpecifier::FunctionName;
    if (PrintInlining) {
      DIInliningInfo InliningInfo =
        dictx->getInliningInfoForAddress(Address, SpecFlags);
      uint32_t n = InliningInfo.getNumberOfFrames();
      if (n == 0) {
        // Print one empty debug line info in any case.
        PrintDILineInfo(DILineInfo());
      } else {
        for (uint32_t i = 0; i < n; i++) {
          DILineInfo dli = InliningInfo.getFrame(i);
          PrintDILineInfo(dli);
        }
      }
    } else {
      DILineInfo dli = dictx->getLineInfoForAddress(Address, SpecFlags);
      PrintDILineInfo(dli);
    }
  }
}

int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n");

  // Defaults to a.out if no filenames specified.
  if (InputFilenames.size() == 0)
    InputFilenames.push_back("a.out");

  std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput);

  return 0;
}
<commit_msg>Rename variable to be more comprehensible and follow naming convention<commit_after>//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like "dwarfdump".
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/RelocVisitor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
#include <algorithm>
#include <cstring>
#include <list>
#include <string>

using namespace llvm;
using namespace object;

static cl::list<std::string>
InputFilenames(cl::Positional, cl::desc("<input object files>"),
               cl::ZeroOrMore);

static cl::opt<unsigned long long>
Address("address", cl::init(-1ULL),
        cl::desc("Print line information for a given address"));

static cl::opt<bool>
PrintFunctions("functions", cl::init(false),
               cl::desc("Print function names as well as line information "
                        "for a given address"));

static cl::opt<bool>
PrintInlining("inlining", cl::init(false),
              cl::desc("Print all inlined frames for a given address"));

static void PrintDILineInfo(DILineInfo dli) {
  if (PrintFunctions)
    outs() << (dli.getFunctionName() ? dli.getFunctionName() : "<unknown>")
           << "\n";
  outs() << (dli.getFileName() ? dli.getFileName() : "<unknown>") << ':'
         << dli.getLine() << ':' << dli.getColumn() << '\n';
}

static void DumpInput(const StringRef &Filename) {
  OwningPtr<MemoryBuffer> Buff;

  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
    errs() << Filename << ": " << ec.message() << "\n";
    return;
  }

  OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
  OwningPtr<DIContext> DICtx(DIContext::getDWARFContext(Obj.get()));

  if (Address == -1ULL) {
    outs() << Filename
           << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
    // Dump the complete DWARF structure.
    DICtx->dump(outs());
  } else {
    // Print line info for the specified address.
    int SpecFlags = DILineInfoSpecifier::FileLineInfo |
                    DILineInfoSpecifier::AbsoluteFilePath;
    if (PrintFunctions)
      SpecFlags |= DILineInfoSpecifier::FunctionName;
    if (PrintInlining) {
      DIInliningInfo InliningInfo =
        DICtx->getInliningInfoForAddress(Address, SpecFlags);
      uint32_t n = InliningInfo.getNumberOfFrames();
      if (n == 0) {
        // Print one empty debug line info in any case.
        PrintDILineInfo(DILineInfo());
      } else {
        for (uint32_t i = 0; i < n; i++) {
          DILineInfo dli = InliningInfo.getFrame(i);
          PrintDILineInfo(dli);
        }
      }
    } else {
      DILineInfo dli = DICtx->getLineInfoForAddress(Address, SpecFlags);
      PrintDILineInfo(dli);
    }
  }
}

int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n");

  // Defaults to a.out if no filenames specified.
  if (InputFilenames.size() == 0)
    InputFilenames.push_back("a.out");

  std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput);

  return 0;
}
<|endoftext|>


<commit_before>#include <sstream>
#include <Timer.h>
#include <FullStVKSimulator.h>
#include <zjucad/matrix/matrix.h>
#include <common/vtk.h>
#include <jtflib/mesh/util.h>
#include <Objmesh.h>
#include "interpolator/interpolator.h"
#include "shell_deformer/cluster.h"
#include "shell_deformer/deformer.h"
#include "conf_para.h"
#include "objio.h"

using namespace UTILITY;
using namespace SIMULATOR;

void cacu_gravity(const pTetMesh tet_mesh, VectorXd& fext, int axis_index, bool isnegtive=true)
{
  const VVec4i& tets = tet_mesh->tets();
  std::vector<double> rho = tet_mesh->material()._rho;
  int tet_size = tets.size();
  assert(tet_size == rho.size());
  if (tet_size != rho.size()) { cerr << "error" << endl; exit(0); }
  for (int i=0; i<tet_size; ++i) {
    double tmp_g = 25.5*rho[i]*tet_mesh->volume(i);
    if (isnegtive) {
      fext[tets[i][0]*3+axis_index] -= tmp_g;
      fext[tets[i][1]*3+axis_index] -= tmp_g;
      fext[tets[i][2]*3+axis_index] -= tmp_g;
      fext[tets[i][3]*3+axis_index] -= tmp_g;
    } else {
      fext[tets[i][0]*3+axis_index] += tmp_g;
      fext[tets[i][1]*3+axis_index] += tmp_g;
      fext[tets[i][2]*3+axis_index] += tmp_g;
      fext[tets[i][3]*3+axis_index] += tmp_g;
    }
  }
}

/**
 * front true is collision in the front face of that axis
 */
void collision_plane(const VVec3d &nodes, VectorXd &v, VectorXd &u, double kd, int plane_index, double plane_height, bool front)
{
  if (front) {
    for (int i=0; i<nodes.size(); ++i)
      {
        if (nodes[i][plane_index] + u[i*3+plane_index] < plane_height)
          {
            u[i*3+plane_index] = plane_height - nodes[i][plane_index];
            v[i*3+plane_index] = -kd*v[i*3+plane_index];
            // v[i*3+plane_index] = 0;
          }
      }
  }
  else {
    for (int i=0; i<nodes.size(); ++i) {
      if (nodes[i][plane_index] + u[i*3+plane_index] > plane_height)
        {
          u[i*3+plane_index] = plane_height - nodes[i][plane_index];
          v[i*3+plane_index] = -kd*v[i*3+plane_index];
          // v[i*3+plane_index] = 0;
        }
    }
  }
}

void collision_ball(const VVec3d &nodes, VectorXd &v, VectorXd &u, const double kd, Vector3d &center, Vector3d &vball, double r, int surface_index, double surface_height, double limit_intersect,
                    double kstiffness, double time_step)
{
  // step forward
  double intersect = surface_height - center[surface_index] - r;
  vball[surface_index] =  vball[surface_index] - 9.8 * time_step + kstiffness * intersect;
  center += vball * time_step;

  intersect = surface_height - (center[surface_index] - r);
  if (intersect > 0) {
    if (intersect > limit_intersect) {
      vball[surface_index] = 0.0;
      center[surface_index] = surface_height - limit_intersect + r;
    }

    // for (int i=0; i<nodes.size(); ++i) {
    //   Vector3d diff = nodes[i] + u.segment<3>(i*3) - center;
    //   if (diff.norm() < r) {
    //     u.segment<3>(i*3) += (r-diff.norm())*(diff/diff.norm());
    //     v(i*3+surface_index) = vball[surface_index];
    //   }
    // }
  }
}

void case_common(const char *ini_file)
{
  // open init json file
  JsonFilePaser jsonf;
  int steps = 1;
  int output_steps = 1;
  int plane_index = 2;
  bool front_collision = true;
  double plane_height = 0;
  double kd = 0;
  string output_file;

  bool succ = jsonf.open(ini_file);
  assert(succ);

  {// output setting
    succ &= jsonf.read("steps", steps);
    succ &= jsonf.read("output_steps", output_steps);
    succ &= jsonf.read("output_file", output_file);
  }
  assert(succ);

  {// colision setting
    succ &= jsonf.read("plane_index", plane_index);
    succ &= jsonf.read("plane_height", plane_height);
    succ &= jsonf.read("front_collision", front_collision);
    succ &= jsonf.read("kd", kd);
  }
  assert(succ);

  pTetMesh tet_mesh = pTetMesh(new TetMesh());
  { // init tetrahedron mesh.
    string vol_file;
    succ = jsonf.readFilePath("vol_file",vol_file);
    assert(succ);
    succ = tet_mesh->load(vol_file);
    cout << "tet size:" << tet_mesh->tets().size() << endl;
    assert(succ);

    string mtl_file;
    jsonf.readFilePath("elastic_mtl",mtl_file);
    succ = tet_mesh->loadElasticMtl(mtl_file);
    assert(succ);
  }

  pSimulator simulator = pSimulator(new FullStVKSimulator());
  { // init simulator
    succ = simulator->init(ini_file);
    assert(succ);
    simulator->setVolMesh(tet_mesh);
    simulator->precompute();
  }

  string con_file;
  if( jsonf.readFilePath("con_nodes", con_file) )
    { // load and set fixed nodes
      vector<int> nodes;
      succ = UTILITY::loadVec(con_file.c_str(), nodes,UTILITY::TEXT);
      assert(succ);
      cout << "num of fixed nodes: " << nodes.size() << endl;
      simulator->setConNodes(nodes);
      VectorXd uc(nodes.size()*3);
      uc.setZero();
      simulator->setUc(uc);
    }

  // simulation for 200 steps, record displacements
  vector<VectorXd> record_u;
  cout << "nodes size:" << tet_mesh->nodes().size() << endl;
  const VVec3d &nodes = tet_mesh->nodes();
  const VVec4i &tets = tet_mesh->tets();
  zjucad::matrix::matrix<size_t> tet_cell(4, tets.size());
  zjucad::matrix::matrix<double> tet_nodes(3, nodes.size());
  for (int i=0; i<tets.size(); ++i)  {
    tet_cell(0,i) = tets[i][0];
    tet_cell(1,i) = tets[i][1];
    tet_cell(2,i) = tets[i][2];
    tet_cell(3,i) = tets[i][3];
  }
  for (int i=0; i<nodes.size(); ++i) {
    tet_nodes(0,i) = nodes[i][0];
    tet_nodes(1,i) = nodes[i][1];
    tet_nodes(2,i) = nodes[i][2];
  }

  zjucad::matrix::matrix<size_t> shell_cell;
  zjucad::matrix::matrix<double> shell_nodes;
  zjucad::matrix::matrix<double> shell_normal;
  gen_outside_shell(tet_cell, tet_nodes, shell_cell, shell_nodes, shell_normal, __SUBDIVISION_TIME, __EMBED_DEPTH);

  size_t row = tet_nodes.size(2);
  size_t col = shell_nodes.size(2);
  hj::sparse::spm_csc<double> B(row, col);
  tet_embed(tet_nodes, tet_cell, shell_nodes, B);
  matrix<double> B_(row, col);
  for (size_t j = 0; j < col; ++j)
    for (size_t i = 0; i < row; ++i)
      B_(i, j) = B(i, j);

  cluster_machine handle(shell_cell, shell_nodes, __CLUSTER_RADIUS);
  handle.partition(__REGION_COUNT);

  deformer shell_deformer(shell_cell, shell_nodes, shell_nodes, handle.regions_);

  matrix<double> dx(tet_nodes.size(1), tet_nodes.size(2)),
    q(tet_nodes.size(1), tet_nodes.size(2)),
    xq(shell_nodes.size(1), shell_nodes.size(2));

  Timer timer;
  { // set external forces, then simulate 50 steps
    const VVec3d &nodes = tet_mesh->nodes();
    VectorXd gravity(nodes.size()*3);
    gravity.setZero();
    cacu_gravity(tet_mesh, gravity, plane_index, front_collision);
    simulator->setExtForce(gravity);
    record_u.push_back(simulator->getFullDisp());

    for (int i = 0; i < steps; ++i){
      simulator->forward();
      VectorXd &v = simulator->getV();
      VectorXd &u = simulator->getModifyFullDisp();
      // collision_ball();
      //void collision_plane(const VVec3d &nodes, VectorXd &v, VectorXd &u, double kd, int plane_index, double plane_height, bool front)
      collision_plane(tet_mesh->nodes(), v, u, kd, plane_index, plane_height, front_collision);

      if(i%output_steps == 0) {
        cout << "step:" << i << endl;
        VectorXd disp = simulator->getFullDisp();
        // std::copy(disp.data(), disp.data() + disp.size(), dx.begin());
        // q = tet_nodes + dx;
        // xq = q * B_;
        // shell_deformer.deform(shell_nodes, xq);
        // jtf::mesh::cal_point_normal(shell_cell, shell_nodes, shell_normal);
        // std::stringstream ss;
        // ss << output_file << i/output_steps << ".obj";
        // cout << "export obj" << endl;
        // export_obj(ss.str(),shell_cell, shell_nodes, shell_normal);
        record_u.push_back(disp);
      }
    }
  }

  timer.stop("total simulation time is (seconds):");
  { // save as vtk files.
    succ = tet_mesh->writeVTK(output_file.c_str(), record_u);
    assert(succ);
  }
  cout << "[INFO]DONE!\n";
}

void move_obj(Objmesh &obj, Vector3d diff) {
  VectorXd &verts = obj.getModifyVerts();
  for (int i=0; i>verts.size()/3; ++i) {
    verts.segment<3>(i*3) += diff;
  }
}

// a simple example demonstrate the usage of the solid simulator.
int main(int argc, char *argv[]){
  if (argc != 2) {
    cout << "usage: test_drop [ini_file]" << endl;
  } else {
    case_common(argv[1]);
  }
  return 0;
}
<commit_msg>hit ball cushion ok<commit_after>#include <sstream>
#include <Timer.h>
#include <FullStVKSimulator.h>
#include <zjucad/matrix/matrix.h>
#include <common/vtk.h>
#include <jtflib/mesh/util.h>
#include <Objmesh.h>
#include "interpolator/interpolator.h"
#include "shell_deformer/cluster.h"
#include "shell_deformer/deformer.h"
#include "conf_para.h"
#include "objio.h"

using namespace UTILITY;
using namespace SIMULATOR;

void cacu_gravity(const pTetMesh tet_mesh, VectorXd& fext, int axis_index, bool isnegtive=true)
{
  const VVec4i& tets = tet_mesh->tets();
  std::vector<double> rho = tet_mesh->material()._rho;
  int tet_size = tets.size();
  assert(tet_size == rho.size());
  if (tet_size != rho.size()) { cerr << "error" << endl; exit(0); }
  for (int i=0; i<tet_size; ++i) {
    double tmp_g = 25.5*rho[i]*tet_mesh->volume(i);
    if (isnegtive) {
      fext[tets[i][0]*3+axis_index] -= tmp_g;
      fext[tets[i][1]*3+axis_index] -= tmp_g;
      fext[tets[i][2]*3+axis_index] -= tmp_g;
      fext[tets[i][3]*3+axis_index] -= tmp_g;
    } else {
      fext[tets[i][0]*3+axis_index] += tmp_g;
      fext[tets[i][1]*3+axis_index] += tmp_g;
      fext[tets[i][2]*3+axis_index] += tmp_g;
      fext[tets[i][3]*3+axis_index] += tmp_g;
    }
  }
}

/**
 * front true is collision in the front face of that axis
 */
void collision_plane(const VVec3d &nodes, VectorXd &v, VectorXd &u, double kd, int plane_index, double plane_height, bool front)
{
  if (front) {
    for (int i=0; i<nodes.size(); ++i)
      {
        if (nodes[i][plane_index] + u[i*3+plane_index] < plane_height)
          {
            u[i*3+plane_index] = plane_height - nodes[i][plane_index];
            v[i*3+plane_index] = -kd*v[i*3+plane_index];
            // v[i*3+plane_index] = 0;
          }
      }
  }
  else {
    for (int i=0; i<nodes.size(); ++i) {
      if (nodes[i][plane_index] + u[i*3+plane_index] > plane_height)
        {
          u[i*3+plane_index] = plane_height - nodes[i][plane_index];
          v[i*3+plane_index] = -kd*v[i*3+plane_index];
          // v[i*3+plane_index] = 0;
        }
    }
  }
}

void collision_ball(const VVec3d &nodes, VectorXd &v, VectorXd &u, const double kd, Vector3d &center, Vector3d &vball, double r, int surface_index, double surface_height, double limit_intersect,
                    double kstiffness, double time_step)
{
  // step forward
  double intersect = surface_height - center[surface_index] - r;
  vball[surface_index] =  vball[surface_index] - 9.8 * time_step + kstiffness * intersect;
  center += vball * time_step;

  intersect = surface_height - (center[surface_index] - r);
  if (intersect > 0) {
    if (intersect > limit_intersect) {
      vball[surface_index] = 0.0;
      center[surface_index] = surface_height - limit_intersect + r;
    }

    // for (int i=0; i<nodes.size(); ++i) {
    //   Vector3d diff = nodes[i] + u.segment<3>(i*3) - center;
    //   if (diff.norm() < r) {
    //     u.segment<3>(i*3) += (r-diff.norm())*(diff/diff.norm());
    //     v(i*3+surface_index) = vball[surface_index];
    //   }
    // }
  }
}

void case_common(const char *ini_file)
{
  // open init json file
  JsonFilePaser jsonf;
  int steps = 1;
  int output_steps = 1;
  int plane_index = 2;
  bool front_collision = true;
  double plane_height = 0;
  double kd = 0;
  string output_file;

  bool succ = jsonf.open(ini_file);
  assert(succ);

  {// output setting
    succ &= jsonf.read("steps", steps);
    succ &= jsonf.read("output_steps", output_steps);
    succ &= jsonf.read("output_file", output_file);
  }
  assert(succ);

  {// colision setting
    succ &= jsonf.read("plane_index", plane_index);
    succ &= jsonf.read("plane_height", plane_height);
    succ &= jsonf.read("front_collision", front_collision);
    succ &= jsonf.read("kd", kd);
  }
  assert(succ);

  pTetMesh tet_mesh = pTetMesh(new TetMesh());
  { // init tetrahedron mesh.
    string vol_file;
    succ = jsonf.readFilePath("vol_file",vol_file);
    assert(succ);
    succ = tet_mesh->load(vol_file);
    cout << "tet size:" << tet_mesh->tets().size() << endl;
    assert(succ);

    string mtl_file;
    jsonf.readFilePath("elastic_mtl",mtl_file);
    succ = tet_mesh->loadElasticMtl(mtl_file);
    assert(succ);
  }

  pSimulator simulator = pSimulator(new FullStVKSimulator());
  { // init simulator
    succ = simulator->init(ini_file);
    assert(succ);
    simulator->setVolMesh(tet_mesh);
    simulator->precompute();
  }

  string con_file;
  if( jsonf.readFilePath("con_nodes", con_file) )
    { // load and set fixed nodes
      vector<int> nodes;
      succ = UTILITY::loadVec(con_file.c_str(), nodes,UTILITY::TEXT);
      assert(succ);
      cout << "num of fixed nodes: " << nodes.size() << endl;
      simulator->setConNodes(nodes);
      VectorXd uc(nodes.size()*3);
      uc.setZero();
      simulator->setUc(uc);
    }

  // simulation for 200 steps, record displacements
  vector<VectorXd> record_u;
  cout << "nodes size:" << tet_mesh->nodes().size() << endl;
  const VVec3d &nodes = tet_mesh->nodes();
  const VVec4i &tets = tet_mesh->tets();
  zjucad::matrix::matrix<size_t> tet_cell(4, tets.size());
  zjucad::matrix::matrix<double> tet_nodes(3, nodes.size());
  for (int i=0; i<tets.size(); ++i)  {
    tet_cell(0,i) = tets[i][0];
    tet_cell(1,i) = tets[i][1];
    tet_cell(2,i) = tets[i][2];
    tet_cell(3,i) = tets[i][3];
  }
  for (int i=0; i<nodes.size(); ++i) {
    tet_nodes(0,i) = nodes[i][0];
    tet_nodes(1,i) = nodes[i][1];
    tet_nodes(2,i) = nodes[i][2];
  }

  // zjucad::matrix::matrix<size_t> shell_cell;
  // zjucad::matrix::matrix<double> shell_nodes;
  // zjucad::matrix::matrix<double> shell_normal;
  // gen_outside_shell(tet_cell, tet_nodes, shell_cell, shell_nodes, shell_normal, __SUBDIVISION_TIME, __EMBED_DEPTH);

  // size_t row = tet_nodes.size(2);
  // size_t col = shell_nodes.size(2);
  // hj::sparse::spm_csc<double> B(row, col);
  // tet_embed(tet_nodes, tet_cell, shell_nodes, B);
  // matrix<double> B_(row, col);
  // for (size_t j = 0; j < col; ++j)
  //   for (size_t i = 0; i < row; ++i)
  //     B_(i, j) = B(i, j);

  // cluster_machine handle(shell_cell, shell_nodes, __CLUSTER_RADIUS);
  // handle.partition(__REGION_COUNT);

  // deformer shell_deformer(shell_cell, shell_nodes, shell_nodes, handle.regions_);

  // matrix<double> dx(tet_nodes.size(1), tet_nodes.size(2)),
  //   q(tet_nodes.size(1), tet_nodes.size(2)),
  //   xq(shell_nodes.size(1), shell_nodes.size(2));

  Timer timer;
  { // set external forces, then simulate 50 steps
    const VVec3d &nodes = tet_mesh->nodes();
    VectorXd gravity(nodes.size()*3);
    gravity.setZero();
    cacu_gravity(tet_mesh, gravity, plane_index, front_collision);
    simulator->setExtForce(gravity);
    record_u.push_back(simulator->getFullDisp());

    for (int i = 0; i < steps; ++i){
      simulator->forward();
      VectorXd &v = simulator->getV();
      VectorXd &u = simulator->getModifyFullDisp();

      //void collision_plane(const VVec3d &nodes, VectorXd &v, VectorXd &u, double kd, int plane_index, double plane_height, bool front)
      collision_plane(tet_mesh->nodes(), v, u, kd, plane_index, plane_height, front_collision);

      if(i%output_steps == 0) {
        cout << "step:" << i << endl;
        VectorXd disp = simulator->getFullDisp();
        // std::copy(disp.data(), disp.data() + disp.size(), dx.begin());
        // q = tet_nodes + dx;
        // xq = q * B_;
        // shell_deformer.deform(shell_nodes, xq);
        // jtf::mesh::cal_point_normal(shell_cell, shell_nodes, shell_normal);
        // std::stringstream ss;
        // ss << output_file << i/output_steps << ".obj";
        // cout << "export obj" << endl;
        // export_obj(ss.str(),shell_cell, shell_nodes, shell_normal);
        record_u.push_back(disp);
      }
    }
  }

  timer.stop("total simulation time is (seconds):");
  { // save as vtk files.
    succ = tet_mesh->writeVTK(output_file.c_str(), record_u);
    assert(succ);
  }
  cout << "[INFO]DONE!\n";
}

void move_obj(Objmesh &obj, Vector3d diff) {
  VectorXd &verts = obj.getModifyVerts();
  for (int i=0; i>verts.size()/3; ++i) {
    verts.segment<3>(i*3) += diff;
  }
}

// a simple example demonstrate the usage of the solid simulator.
int main(int argc, char *argv[]){
  if (argc != 2) {
    cout << "usage: test_drop [ini_file]" << endl;
  } else {
    case_common(argv[1]);
  }
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Minor code review<commit_after><|endoftext|>