<commit_before>//
// Created by david on 2019-03-09.
//

#include <algorithms/class_algorithm_status.h>
#include <config/nmspc_settings.h>
#include <h5pp/h5pp.h>
#include <regex>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
using Scalar = std::complex<double>;

namespace tools::finite::io::h5dset{
    void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> & save_log, const h5pp::File &h5ppFile, const std::vector<std::string> & links){
        if(save_log.empty()){
            try {
                for(auto &link : links) {
                    if(h5ppFile.linkExists(link)) {
                        auto step      = h5ppFile.readAttribute<uint64_t>("step", link);
                        auto iter      = h5ppFile.readAttribute<uint64_t>("iteration", link);
                        save_log[link] = std::make_pair(iter, step);
                    }
                }
            }catch(const std::exception & ex){
                tools::log->warn("Could not bootstrap save_log: {}", ex.what());
            }
        }
    }
}

int tools::finite::io::h5dset::decide_layout(std::string_view prefix_path) {
    return H5D_CHUNKED; // Let everything be chunked a while. When resuming, rewriting into checkpoint/iter_? can lead datasets of different sizes
    std::string str(prefix_path);
    std::regex  rx(R"(checkpoint/iter_[0-9])"); // Declare the regex with a raw string literal
    std::smatch m;
    if(regex_search(str, m, rx)) return H5D_CONTIGUOUS;
    else
        return H5D_CHUNKED;
}

void tools::finite::io::h5dset::save_state(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
                                           const class_state_finite &state, const class_algorithm_status &status) {
    if(storage_level == StorageLevel::NONE) return;
    tools::common::profile::get_default_prof()["t_hdf"]->tic();

    // Checks if the current entry has already been saved
    // If it is empty because we are resuming, check if there is a log entry on file already
    static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;
    bootstrap_save_log(save_log,h5ppFile,{state_prefix + "/schmidt_midchain", state_prefix + "/mps"});

    auto save_point = std::make_pair(status.iter, status.step);

    auto layout = static_cast<H5D_layout_t>(decide_layout(state_prefix));

    std::string dsetName = state_prefix + "/schmidt_midchain";
    if(save_log[dsetName] != save_point) {
        /*! Writes down the center "Lambda" bond matrix (singular values). */
        tools::log->trace("Storing [{: ^6}]: mid bond matrix", enum2str(storage_level));
        h5ppFile.writeDataset(state.midchain_bond(), dsetName, layout);
        h5ppFile.writeAttribute(state.get_truncation_error_midchain(), "truncation_error", dsetName);
        h5ppFile.writeAttribute((state.get_length<long>() - 1) / 2, "position", dsetName);
        h5ppFile.writeAttribute(status.iter, "iteration", dsetName);
        h5ppFile.writeAttribute(status.step, "step", dsetName);
        h5ppFile.writeAttribute(status.chi_lim, "chi_lim", dsetName);
        h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", dsetName);
        save_log[dsetName] = save_point;
    }

    if(storage_level < StorageLevel::NORMAL) {
        tools::common::profile::get_default_prof()["t_hdf"]->toc();
        return;
    }

    std::string mps_prefix = state_prefix + "/mps";
    if(save_log[mps_prefix] != save_point) {
        tools::log->trace("Storing [{: ^6}]: bond matrices", enum2str(storage_level));
        // There should be one more sites+1 number of L's, because there is also a center bond
        // However L_i always belongs M_i. Stick to this rule!
        // This means that some M_i has two bonds, one L_i to the left, and one L_C to the right.
        for(const auto & mps : state.mps_sites) {
            dsetName = fmt::format("{}/L_{}", mps_prefix, mps->get_position<long>());
            if(save_log[dsetName] == save_point) continue;
            h5ppFile.writeDataset(mps->get_L(), dsetName, layout);
            h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
            h5ppFile.writeAttribute(mps->get_L().dimensions(), "dimensions", dsetName);
            h5ppFile.writeAttribute(mps->get_truncation_error(), "truncation_error", dsetName);
            if(mps->isCenter()) {
                dsetName = mps_prefix + "/L_C";
                h5ppFile.writeDataset(mps->get_LC(), dsetName, layout);
                h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
                h5ppFile.writeAttribute(mps->get_LC().dimensions(), "dimensions", dsetName);
                h5ppFile.writeAttribute(mps->get_truncation_error_LC(), "truncation_error", dsetName);
            }
            save_log[dsetName] = save_point;
        }
        h5ppFile.writeAttribute(state.get_length(), "model_size", mps_prefix);
        h5ppFile.writeAttribute(state.get_position<long>(), "position", mps_prefix);
        h5ppFile.writeAttribute(state.get_truncation_errors(), "truncation_errors", mps_prefix);
        h5ppFile.writeAttribute(state.get_labels(), "labels", mps_prefix);
        h5ppFile.writeAttribute(status.iter, "iteration", mps_prefix);
        h5ppFile.writeAttribute(status.step, "step", mps_prefix);
    }

    /*! Writes down the full MPS in "L-G-L-G- LC -G-L-G-L" notation. */
    if(storage_level < StorageLevel::FULL) {
        tools::common::profile::get_default_prof()["t_hdf"]->toc();
        save_log[mps_prefix] = save_point;
        return;
    }

    if(save_log[mps_prefix] != save_point) {
        tools::log->trace("Storing [{: ^6}]: mps tensors", enum2str(storage_level));
        for(const auto & mps : state.mps_sites){
            dsetName = fmt::format("{}/M_{}", mps_prefix, mps->get_position<long>());
            if(save_log[dsetName] == save_point) continue;
            h5ppFile.writeDataset(mps->get_M_bare(), dsetName, layout); // Important to write bare matrices!!
            h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
            h5ppFile.writeAttribute(mps->get_M_bare().dimensions(), "dimensions", dsetName);
            h5ppFile.writeAttribute(mps->get_label(), "label", dsetName);
            h5ppFile.writeAttribute(mps->get_unique_id(), "unique_id", dsetName);
            save_log[dsetName] = save_point;
        }
        save_log[mps_prefix] = save_point;
    }
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}

/*! Write all the MPO's with site info in attributes */
void tools::finite::io::h5dset::save_model(h5pp::File &h5ppFile, const std::string &model_prefix, const StorageLevel &storage_level,
                                           const class_model_finite &model) {
    if(storage_level < StorageLevel::FULL) return;
    // We do not expect the MPO's to change. Therefore if they exist, there is nothing else to do here
    if(h5ppFile.linkExists(model_prefix)) return tools::log->trace("The MPO's have already been written to [{}]", model_prefix);
    tools::log->trace("Storing [{: ^6}]: mpo tensors", enum2str(storage_level));
    tools::common::profile::get_default_prof()["t_hdf"]->tic();
    for(size_t pos = 0; pos < model.get_length(); pos++) { model.get_mpo(pos).save_mpo(h5ppFile, model_prefix); }
    h5ppFile.writeAttribute(settings::model::model_size, "model_size", model_prefix);
    h5ppFile.writeAttribute(enum2str(settings::model::model_type), "model_type", model_prefix);
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}

/*! Write down measurements that can't fit in a table */
void tools::finite::io::h5dset::save_entgm(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
                                           const class_state_finite &state, const class_algorithm_status &status) {
    if(storage_level < StorageLevel::NORMAL) return;
    state.do_all_measurements();
    tools::common::profile::get_default_prof()["t_hdf"]->tic();

    tools::log->trace("Storing [{: ^6}]: bond dimensions", enum2str(storage_level));
    h5ppFile.writeDataset(tools::finite::measure::bond_dimensions(state), state_prefix + "/bond_dimensions");
    h5ppFile.writeAttribute(status.chi_lim, "chi_lim", state_prefix + "/bond_dimensions");
    h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", state_prefix + "/bond_dimensions");

    tools::log->trace("Storing [{: ^6}]: entanglement entropies", enum2str(storage_level));
    h5ppFile.writeDataset(tools::finite::measure::entanglement_entropies(state), state_prefix + "/entanglement_entropies");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 2), state_prefix + "/renyi_2");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 3), state_prefix + "/renyi_3");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 4), state_prefix + "/renyi_4");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 100), state_prefix + "/renyi_100");

    tools::log->trace("Storing [{: ^6}]: truncation errors", enum2str(storage_level));
    h5ppFile.writeDataset(state.get_truncation_errors(), state_prefix + "/truncation_errors");
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
<commit_msg>Introduce SAVEPOINT and CHECKPOINT storage reasons<commit_after>//
// Created by david on 2019-03-09.
//

#include <algorithms/class_algorithm_status.h>
#include <config/nmspc_settings.h>
#include <h5pp/h5pp.h>
#include <regex>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
using Scalar = std::complex<double>;

namespace tools::finite::io::h5dset{
    void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> & save_log, const h5pp::File &h5ppFile, const std::vector<std::string> & links){
        if(save_log.empty()){
            try {
                for(auto &link : links) {
                    if(h5ppFile.linkExists(link)) {
                        auto step      = h5ppFile.readAttribute<uint64_t>("step", link);
                        auto iter      = h5ppFile.readAttribute<uint64_t>("iteration", link);
                        save_log[link] = std::make_pair(iter, step);
                    }
                }
            }catch(const std::exception & ex){
                tools::log->warn("Could not bootstrap save_log: {}", ex.what());
            }
        }
    }
}

int tools::finite::io::h5dset::decide_layout(std::string_view prefix_path) {
    return H5D_CHUNKED; // Let everything be chunked a while. When resuming, rewriting into savepoint/iter_? can lead datasets of different sizes
    std::string str(prefix_path);
    std::regex  rx(R"(savepoint/iter_[0-9])"); // Declare the regex with a raw string literal
    std::smatch m;
    if(regex_search(str, m, rx)) return H5D_CONTIGUOUS;
    else
        return H5D_CHUNKED;
}

void tools::finite::io::h5dset::save_state(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
                                           const class_state_finite &state, const class_algorithm_status &status) {
    if(storage_level == StorageLevel::NONE) return;
    tools::common::profile::get_default_prof()["t_hdf"]->tic();

    // Checks if the current entry has already been saved
    // If it is empty because we are resuming, check if there is a log entry on file already
    static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;
    bootstrap_save_log(save_log,h5ppFile,{state_prefix + "/schmidt_midchain", state_prefix + "/mps"});

    auto save_point = std::make_pair(status.iter, status.step);

    auto layout = static_cast<H5D_layout_t>(decide_layout(state_prefix));

    std::string dsetName = state_prefix + "/schmidt_midchain";
    if(save_log[dsetName] != save_point) {
        /*! Writes down the center "Lambda" bond matrix (singular values). */
        tools::log->trace("Storing [{: ^6}]: mid bond matrix", enum2str(storage_level));
        h5ppFile.writeDataset(state.midchain_bond(), dsetName, layout);
        h5ppFile.writeAttribute(state.get_truncation_error_midchain(), "truncation_error", dsetName);
        h5ppFile.writeAttribute((state.get_length<long>() - 1) / 2, "position", dsetName);
        h5ppFile.writeAttribute(status.iter, "iteration", dsetName);
        h5ppFile.writeAttribute(status.step, "step", dsetName);
        h5ppFile.writeAttribute(status.chi_lim, "chi_lim", dsetName);
        h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", dsetName);
        save_log[dsetName] = save_point;
    }

    if(storage_level < StorageLevel::NORMAL) {
        tools::common::profile::get_default_prof()["t_hdf"]->toc();
        return;
    }

    std::string mps_prefix = state_prefix + "/mps";
    if(save_log[mps_prefix] != save_point) {
        tools::log->trace("Storing [{: ^6}]: bond matrices", enum2str(storage_level));
        // There should be one more sites+1 number of L's, because there is also a center bond
        // However L_i always belongs M_i. Stick to this rule!
        // This means that some M_i has two bonds, one L_i to the left, and one L_C to the right.
        for(const auto & mps : state.mps_sites) {
            dsetName = fmt::format("{}/L_{}", mps_prefix, mps->get_position<long>());
            if(save_log[dsetName] == save_point) continue;
            h5ppFile.writeDataset(mps->get_L(), dsetName, layout);
            h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
            h5ppFile.writeAttribute(mps->get_L().dimensions(), "dimensions", dsetName);
            h5ppFile.writeAttribute(mps->get_truncation_error(), "truncation_error", dsetName);
            if(mps->isCenter()) {
                dsetName = mps_prefix + "/L_C";
                h5ppFile.writeDataset(mps->get_LC(), dsetName, layout);
                h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
                h5ppFile.writeAttribute(mps->get_LC().dimensions(), "dimensions", dsetName);
                h5ppFile.writeAttribute(mps->get_truncation_error_LC(), "truncation_error", dsetName);
            }
            save_log[dsetName] = save_point;
        }
        h5ppFile.writeAttribute(state.get_length(), "model_size", mps_prefix);
        h5ppFile.writeAttribute(state.get_position<long>(), "position", mps_prefix);
        h5ppFile.writeAttribute(state.get_truncation_errors(), "truncation_errors", mps_prefix);
        h5ppFile.writeAttribute(state.get_labels(), "labels", mps_prefix);
        h5ppFile.writeAttribute(status.iter, "iteration", mps_prefix);
        h5ppFile.writeAttribute(status.step, "step", mps_prefix);
    }

    /*! Writes down the full MPS in "L-G-L-G- LC -G-L-G-L" notation. */
    if(storage_level < StorageLevel::FULL) {
        tools::common::profile::get_default_prof()["t_hdf"]->toc();
        save_log[mps_prefix] = save_point;
        return;
    }

    if(save_log[mps_prefix] != save_point) {
        tools::log->trace("Storing [{: ^6}]: mps tensors", enum2str(storage_level));
        for(const auto & mps : state.mps_sites){
            dsetName = fmt::format("{}/M_{}", mps_prefix, mps->get_position<long>());
            if(save_log[dsetName] == save_point) continue;
            h5ppFile.writeDataset(mps->get_M_bare(), dsetName, layout); // Important to write bare matrices!!
            h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
            h5ppFile.writeAttribute(mps->get_M_bare().dimensions(), "dimensions", dsetName);
            h5ppFile.writeAttribute(mps->get_label(), "label", dsetName);
            h5ppFile.writeAttribute(mps->get_unique_id(), "unique_id", dsetName);
            save_log[dsetName] = save_point;
        }
        save_log[mps_prefix] = save_point;
    }
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}

/*! Write all the MPO's with site info in attributes */
void tools::finite::io::h5dset::save_model(h5pp::File &h5ppFile, const std::string &model_prefix, const StorageLevel &storage_level,
                                           const class_model_finite &model) {
    if(storage_level < StorageLevel::FULL) return;
    // We do not expect the MPO's to change. Therefore if they exist, there is nothing else to do here
    if(h5ppFile.linkExists(model_prefix)) return tools::log->trace("The MPO's have already been written to [{}]", model_prefix);
    tools::log->trace("Storing [{: ^6}]: mpo tensors", enum2str(storage_level));
    tools::common::profile::get_default_prof()["t_hdf"]->tic();
    for(size_t pos = 0; pos < model.get_length(); pos++) { model.get_mpo(pos).save_mpo(h5ppFile, model_prefix); }
    h5ppFile.writeAttribute(settings::model::model_size, "model_size", model_prefix);
    h5ppFile.writeAttribute(enum2str(settings::model::model_type), "model_type", model_prefix);
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}

/*! Write down measurements that can't fit in a table */
void tools::finite::io::h5dset::save_entgm(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
                                           const class_state_finite &state, const class_algorithm_status &status) {
    if(storage_level < StorageLevel::NORMAL) return;
    state.do_all_measurements();
    tools::common::profile::get_default_prof()["t_hdf"]->tic();

    tools::log->trace("Storing [{: ^6}]: bond dimensions", enum2str(storage_level));
    h5ppFile.writeDataset(tools::finite::measure::bond_dimensions(state), state_prefix + "/bond_dimensions");
    h5ppFile.writeAttribute(status.chi_lim, "chi_lim", state_prefix + "/bond_dimensions");
    h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", state_prefix + "/bond_dimensions");

    tools::log->trace("Storing [{: ^6}]: entanglement entropies", enum2str(storage_level));
    h5ppFile.writeDataset(tools::finite::measure::entanglement_entropies(state), state_prefix + "/entanglement_entropies");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 2), state_prefix + "/renyi_2");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 3), state_prefix + "/renyi_3");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 4), state_prefix + "/renyi_4");
    h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 100), state_prefix + "/renyi_100");

    tools::log->trace("Storing [{: ^6}]: truncation errors", enum2str(storage_level));
    h5ppFile.writeDataset(state.get_truncation_errors(), state_prefix + "/truncation_errors");
    tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
<|endoftext|>


<commit_before>/*
 * W.J. van der Laan 2011-2012
 * The PPCoin Developers 2013
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"

#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"

#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#include <boost/interprocess/ipc/message_queue.hpp>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;

int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & wxMODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
    return 4;
}

bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

void MainFrameRepaint()
{
    if(clientmodel)
        QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
    if(walletmodel)
        QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}

void AddressBookRepaint()
{
    if(walletmodel)
        QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}

void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
        QApplication::instance()->processEvents();
    }
}

void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
std::string _(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows

    // Do this early as we don't want to bother initializing if we are just calling IPC
    for (int i = 1; i < argc; i++)
    {
        if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
        {
            const char *strURI = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                if(mq.try_send(strURI, strlen(strURI), 0))
                    exit(0);
                else
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                break;
            }
        }
    }
#endif

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified directory does not exist\n");
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("PPCoin");
    app.setOrganizationDomain("ppcoin.org");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("PPCoin-Qt-testnet");
    else
        app.setApplicationName("PPCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale ("en_US") from command line or system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang = lang_territory;

    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        BitcoinGUI window;
        guiref = &window;
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                optionsModel.Upgrade(); // Must be done after AppInit2

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                clientmodel = &clientModel;
                WalletModel walletModel(pwalletMain, &optionsModel);
                walletmodel = &walletModel;

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we dont want to lose URIs
                ipcInit();

#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows

                // Check for URI in argv
                for (int i = 1; i < argc; i++)
                {
                    if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
                    {
                        const char *strURI = argv[i];
                        try {
                            boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                            mq.try_send(strURI, strlen(strURI), 0);
                        }
                        catch (boost::interprocess::interprocess_exception &ex) {
                        }
                    }
                }
#endif
                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
                clientmodel = 0;
                walletmodel = 0;
            }
            // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Update bitcoin.cpp<commit_after>/*
 * W.J. van der Laan 2011-2012
 * The PPCoin Developers 2013
 * The Platinum Developers 2013-2014
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"

#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"

#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#include <boost/interprocess/ipc/message_queue.hpp>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;

int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & wxMODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
    return 4;
}

bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

void MainFrameRepaint()
{
    if(clientmodel)
        QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
    if(walletmodel)
        QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}

void AddressBookRepaint()
{
    if(walletmodel)
        QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}

void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
        QApplication::instance()->processEvents();
    }
}

void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
std::string _(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows

    // Do this early as we don't want to bother initializing if we are just calling IPC
    for (int i = 1; i < argc; i++)
    {
        if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
        {
            const char *strURI = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                if(mq.try_send(strURI, strlen(strURI), 0))
                    exit(0);
                else
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                break;
            }
        }
    }
#endif

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified directory does not exist\n");
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("PPCoin");
    app.setOrganizationDomain("ppcoin.org");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("PPCoin-Qt-testnet");
    else
        app.setApplicationName("PPCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale ("en_US") from command line or system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang = lang_territory;

    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        BitcoinGUI window;
        guiref = &window;
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                optionsModel.Upgrade(); // Must be done after AppInit2

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                clientmodel = &clientModel;
                WalletModel walletModel(pwalletMain, &optionsModel);
                walletmodel = &walletModel;

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we dont want to lose URIs
                ipcInit();

#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows

                // Check for URI in argv
                for (int i = 1; i < argc; i++)
                {
                    if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
                    {
                        const char *strURI = argv[i];
                        try {
                            boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                            mq.try_send(strURI, strlen(strURI), 0);
                        }
                        catch (boost::interprocess::interprocess_exception &ex) {
                        }
                    }
                }
#endif
                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
                clientmodel = 0;
                walletmodel = 0;
            }
            // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: PColumn.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2003-12-16 12:26:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif

namespace connectivity
{
    namespace parse
    {
        class OParseColumn;

        typedef sdbcx::OColumn OParseColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;

        class OParseColumn :    public OParseColumn_BASE,
                                public OParseColumn_PROP
        {
            ::rtl::OUString m_aRealName;
            ::rtl::OUString m_aTableName;
            sal_Bool        m_bFunction;
            sal_Bool        m_bDbasePrecisionChanged;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OParseColumn();
        public:
            OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
            OParseColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase);

            virtual void construct();

            void setRealName(const ::rtl::OUString& _rName)  { m_aRealName  = _rName; }
            void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
            void setFunction(sal_Bool _bFunction)            { m_bFunction  = _bFunction; }
            void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }

            ::rtl::OUString getRealName() const { return  m_aRealName; }
            ::rtl::OUString getTableName() const { return  m_aTableName; }
            sal_Bool        getFunction() const { return  m_bFunction; }
            sal_Bool        getDbasePrecisionChanged()  const { return  m_bDbasePrecisionChanged; }
        };

        class OOrderColumn;

        typedef sdbcx::OColumn OOrderColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;

        class OOrderColumn :    public OOrderColumn_BASE,
                                public OOrderColumn_PROP
        {
            sal_Bool        m_bAscending;
            sal_Bool        m_bOrder;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OOrderColumn();
        public:
            OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
            OOrderColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase
                    ,sal_Bool _bAscending);

            virtual void construct();

            virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif //_CONNECTIVITY_PCOLUMN_HXX_

<commit_msg>INTEGRATION: CWS dba16 (1.10.66); FILE MERGED 2004/10/11 11:38:54 oj 1.10.66.1: #i30220# enable having, group by for queries<commit_after>/*************************************************************************
 *
 *  $RCSfile: PColumn.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 08:40:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif

namespace connectivity
{
    namespace parse
    {
        class OParseColumn;

        typedef sdbcx::OColumn OParseColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;

        class OParseColumn :    public OParseColumn_BASE,
                                public OParseColumn_PROP
        {
            ::rtl::OUString m_aRealName;
            ::rtl::OUString m_aTableName;
            sal_Bool        m_bFunction;
            sal_Bool        m_bDbasePrecisionChanged;
            sal_Bool        m_bAggregateFunction;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OParseColumn();
        public:
            OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
            OParseColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase);

            virtual void construct();

            void setRealName(const ::rtl::OUString& _rName)  { m_aRealName  = _rName; }
            void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
            void setFunction(sal_Bool _bFunction)            { m_bFunction  = _bFunction; }
            void setAggregateFunction(sal_Bool _bFunction)   { m_bAggregateFunction = _bFunction; }
            void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }

            ::rtl::OUString getRealName() const { return  m_aRealName; }
            ::rtl::OUString getTableName() const { return  m_aTableName; }
            sal_Bool        getFunction() const { return  m_bFunction; }
            sal_Bool        getDbasePrecisionChanged()  const { return  m_bDbasePrecisionChanged; }
        };

        class OOrderColumn;

        typedef sdbcx::OColumn OOrderColumn_BASE;
        typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;

        class OOrderColumn :    public OOrderColumn_BASE,
                                public OOrderColumn_PROP
        {
            sal_Bool        m_bAscending;
            sal_Bool        m_bOrder;
        protected:
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

            virtual ~OOrderColumn();
        public:
            OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
            OOrderColumn(const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase
                    ,sal_Bool _bAscending);

            virtual void construct();

            virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif //_CONNECTIVITY_PCOLUMN_HXX_

<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName             NFCEctypeModule.cpp
//    @Author               LvSheng.Huang
//    @Date                 2012-12-15
//    @Module               NFCEctypeModule
//
// -------------------------------------------------------------------------

#include "NFCEctypeModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include "NFComm/Define/NFStringInfo.h"

bool NFCEctypeModule::Init()
{
    return true;
}

bool NFCEctypeModule::Shut()
{
    return true;
}

bool NFCEctypeModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCEctypeModule::AfterInit()
{
    m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
    m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
    m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
    m_pSceneProcessModule = dynamic_cast<NFISceneProcessModule*>(pPluginManager->FindModule("NFCSceneProcessModule"));
    m_pAwardModule = dynamic_cast<NFIAwardPackModule*>(pPluginManager->FindModule("NFCAwardPackModule"));
    m_pPackModule = dynamic_cast<NFIPackModule*>(pPluginManager->FindModule("NFCPackModule"));
    m_pPropertyModule = dynamic_cast<NFIPropertyModule*>(pPluginManager->FindModule("NFCPropertyModule"));
    m_pLevelModule = dynamic_cast<NFILevelModule*>(pPluginManager->FindModule("NFCLevelModule"));
    m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule"));
    m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule"));

    assert(NULL != m_pLevelModule);
    assert(NULL != m_pPropertyModule);
    assert(NULL != m_pPackModule);
    assert(NULL != m_pAwardModule);
    assert(NULL != m_pEventProcessModule);
    assert(NULL != m_pElementInfoModule);
    assert(NULL != m_pKernelModule);
    assert(NULL != m_pSceneProcessModule);
    assert(NULL != m_pLogModule);
    assert(NULL != m_pLogicClassModule);

    m_pEventProcessModule->AddClassCallBack("Player", this, &NFCEctypeModule::OnObjectClassEvent);

    return true;
}

bool NFCEctypeModule::CanEntryCloneScene(const NFIDENTID self, const int nContainerID)
{
    std::string strSceneID = boost::lexical_cast<std::string>(nContainerID);
    //ûҵжǷǵһIsFirstCloneScene
    int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
    if (nLevel < m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneLevelLimit"))
    {
		m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self,  "Level limit for scene:" + strSceneID, nLevel, __FUNCTION__, __LINE__);
        return false;
    }

    //ĺֱӿǷ
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (!pRecord.get())
    {
        return false;
    }

    NFCDataList valNormalResult;
    pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
    if (valNormalResult.GetCount() <= 0)
    {
		m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "no this scene in record", nContainerID, __FUNCTION__, __LINE__);
        return false;
    }

    return true;
}

int NFCEctypeModule::OnObjectClassEvent(const NFIDENTID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
    if (strClassName == "Player")
    {
        if (COE_CREATE_BEFORE_EFFECT == eClassEvent)
        {
            int nOnlineCount = m_pKernelModule->GetPropertyInt(self, "OnlineCount");
            if (nOnlineCount <= 0)
            {
                NF_SHARE_PTR<NFILogicClass> pLogicCLass = m_pLogicClassModule->GetElement("Scene");
                if (!pLogicCLass.get())
                {
                   return 0;
                }

                NFList<std::string>& configList = pLogicCLass->GetConfigNameList();
                std::string strSceneConfigID;
                for (bool bRet = configList.First(strSceneConfigID); bRet; bRet = configList.Next(strSceneConfigID))
                {
                    int nFirstScene = m_pElementInfoModule->GetPropertyInt(strSceneConfigID, "IsFirstCloneScene");
                    //һأͨģʽſԣģʽҪͨģʽ
                    if (nFirstScene > 0)
                    {
                        int nSceneId = 0;
                        if(NF_StrTo(strSceneConfigID, nSceneId))
                        {//⼤ĵͼֱӿԽֶһ£EctypeListû
                            AddEctypeActiveState(self, nSceneId);
                        }
                    }
                }
            }
        }
        else if (COE_CREATE_FINISH == eClassEvent)
        {
            m_pKernelModule->AddPropertyCallBack(self, "GroupID", this, &NFCEctypeModule::OnObjectGroupIDEvent);

            //m_pEventProcessModule->AddEventCallBack(self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, this, &NFCEctypeModule::OnEntrySceneEvent);
        }
    }
    return 0;
}

bool NFCEctypeModule::AddEctypeActiveState(const NFIDENTID self, const int nContainerID)
{
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (pRecord.get() && nContainerID > 0)
    {
        NFCDataList valNormalResult;
        pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
        if (valNormalResult.GetCount()  <= 0)
        {
            NFCDataList valValue;
            valValue.AddInt(nContainerID);
            valValue.AddInt(ECS_HAS_OPEN);
            valValue.AddInt(0);

            pRecord->AddRow(-1, valValue);
            m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "EctypeList AddEctypeActiveState", nContainerID);
        }
    }

    return true;
}

int NFCEctypeModule::OnEctypeSettleEvent(const NFIDENTID& self, int nResult, int nStar)
{
    NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
    if (!pObject.get())
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not exit", "", __FUNCTION__, __LINE__);
        return 1;
    }

    int nSceneID = pObject->GetPropertyInt("SceneID");
    if (nSceneID <= 0)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "scene id error", "", __FUNCTION__, __LINE__);
        return 1;
    }

    // ʧ
    if (nResult == 0)
    {
        int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
        const std::string& strAccout = m_pKernelModule->GetPropertyString(self, "Account");

        std::ostringstream stream;
        stream << "[ExitEctype] Account[" << strAccout << "] Level[" << nLevel << "] Scene[" << nSceneID << "] [0]";
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, stream, __FUNCTION__, __LINE__);
        return 1;
    }

    if (!m_pSceneProcessModule->IsCloneScene(nSceneID))
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not int clone scene", "", __FUNCTION__, __LINE__);
        return 1;
    }

    // ͨؼ¼
    // TODO

    // ͨؽ
    AddEctypeAward(self, nSceneID);

    return 0;
}

bool NFCEctypeModule::CompleteEctypeMode(const NFIDENTID self, const int nContainerID, const int nStar)
{
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (NULL == pRecord.get())
    {
        return false;
    }

    //

    return true;
}

int NFCEctypeModule::OnObjectGroupIDEvent(const NFIDENTID& self, const std::string& strPropertyName, const NFIDataList& oldVar, const NFIDataList& newVar, const NFIDataList& argVar)
{

    return 0;
}

int NFCEctypeModule::AddEctypeAward(const NFIDENTID& self, const int nSceneID)
{
    std::string strSceneID = boost::lexical_cast<std::string>(nSceneID);
    int nType = m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneType");

    int nAddMoney = 0;
    int nAddExp = 0;
    NFCDataList xItemList;
    NFCDataList xCountList;

    // 佱
    m_pPackModule->DrawDropAward(self, nAddMoney, nAddExp, xItemList, xCountList);

    // ͨؽ

    // ֪ͨͻ
    NFCDataList xAwardInfoList;
    xAwardInfoList << nAddMoney;
    xAwardInfoList << nAddExp;
    if (xItemList.GetCount() == xCountList.GetCount())
    {
        for (int i = 0; i < xItemList.GetCount(); ++i)
        {
            xAwardInfoList << xItemList.String(i);
            xAwardInfoList << xCountList.Int(i);
        }
    }

    m_pEventProcessModule->DoEvent(self, NFED_ON_NOTICE_ECTYPE_AWARD, xAwardInfoList);

    return 0;
}

bool NFCEctypeModule::AddNewEctype(const NFIDENTID self)
{
    int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");

    //

    return true;
}<commit_msg>end battle function add diamond<commit_after>// -------------------------------------------------------------------------
//    @FileName             NFCEctypeModule.cpp
//    @Author               LvSheng.Huang
//    @Date                 2012-12-15
//    @Module               NFCEctypeModule
//
// -------------------------------------------------------------------------

#include "NFCEctypeModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include "NFComm/Define/NFStringInfo.h"

bool NFCEctypeModule::Init()
{
    return true;
}

bool NFCEctypeModule::Shut()
{
    return true;
}

bool NFCEctypeModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCEctypeModule::AfterInit()
{
    m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
    m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
    m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
    m_pSceneProcessModule = dynamic_cast<NFISceneProcessModule*>(pPluginManager->FindModule("NFCSceneProcessModule"));
    m_pAwardModule = dynamic_cast<NFIAwardPackModule*>(pPluginManager->FindModule("NFCAwardPackModule"));
    m_pPackModule = dynamic_cast<NFIPackModule*>(pPluginManager->FindModule("NFCPackModule"));
    m_pPropertyModule = dynamic_cast<NFIPropertyModule*>(pPluginManager->FindModule("NFCPropertyModule"));
    m_pLevelModule = dynamic_cast<NFILevelModule*>(pPluginManager->FindModule("NFCLevelModule"));
    m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule"));
    m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule"));

    assert(NULL != m_pLevelModule);
    assert(NULL != m_pPropertyModule);
    assert(NULL != m_pPackModule);
    assert(NULL != m_pAwardModule);
    assert(NULL != m_pEventProcessModule);
    assert(NULL != m_pElementInfoModule);
    assert(NULL != m_pKernelModule);
    assert(NULL != m_pSceneProcessModule);
    assert(NULL != m_pLogModule);
    assert(NULL != m_pLogicClassModule);

    m_pEventProcessModule->AddClassCallBack("Player", this, &NFCEctypeModule::OnObjectClassEvent);

    return true;
}

bool NFCEctypeModule::CanEntryCloneScene(const NFIDENTID self, const int nContainerID)
{
    std::string strSceneID = boost::lexical_cast<std::string>(nContainerID);
    //ûҵжǷǵһIsFirstCloneScene
    int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
    if (nLevel < m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneLevelLimit"))
    {
		m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self,  "Level limit for scene:" + strSceneID, nLevel, __FUNCTION__, __LINE__);
        return false;
    }

    //ĺֱӿǷ
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (!pRecord.get())
    {
        return false;
    }

    NFCDataList valNormalResult;
    pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
    if (valNormalResult.GetCount() <= 0)
    {
		m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "no this scene in record", nContainerID, __FUNCTION__, __LINE__);
        return false;
    }

    return true;
}

int NFCEctypeModule::OnObjectClassEvent(const NFIDENTID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
    if (strClassName == "Player")
    {
        if (COE_CREATE_BEFORE_EFFECT == eClassEvent)
        {
            int nOnlineCount = m_pKernelModule->GetPropertyInt(self, "OnlineCount");
            if (nOnlineCount <= 0)
            {
                NF_SHARE_PTR<NFILogicClass> pLogicCLass = m_pLogicClassModule->GetElement("Scene");
                if (!pLogicCLass.get())
                {
                   return 0;
                }

                NFList<std::string>& configList = pLogicCLass->GetConfigNameList();
                std::string strSceneConfigID;
                for (bool bRet = configList.First(strSceneConfigID); bRet; bRet = configList.Next(strSceneConfigID))
                {
                    int nFirstScene = m_pElementInfoModule->GetPropertyInt(strSceneConfigID, "IsFirstCloneScene");
                    //һأͨģʽſԣģʽҪͨģʽ
                    if (nFirstScene > 0)
                    {
                        int nSceneId = 0;
                        if(NF_StrTo(strSceneConfigID, nSceneId))
                        {//⼤ĵͼֱӿԽֶһ£EctypeListû
                            AddEctypeActiveState(self, nSceneId);
                        }
                    }
                }
            }
        }
        else if (COE_CREATE_FINISH == eClassEvent)
        {
            m_pKernelModule->AddPropertyCallBack(self, "GroupID", this, &NFCEctypeModule::OnObjectGroupIDEvent);

            //m_pEventProcessModule->AddEventCallBack(self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, this, &NFCEctypeModule::OnEntrySceneEvent);
        }
    }
    return 0;
}

bool NFCEctypeModule::AddEctypeActiveState(const NFIDENTID self, const int nContainerID)
{
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (pRecord.get() && nContainerID > 0)
    {
        NFCDataList valNormalResult;
        pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
        if (valNormalResult.GetCount()  <= 0)
        {
            NFCDataList valValue;
            valValue.AddInt(nContainerID);
            valValue.AddInt(ECS_HAS_OPEN);
            valValue.AddInt(0);

            pRecord->AddRow(-1, valValue);
            m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "EctypeList AddEctypeActiveState", nContainerID);
        }
    }

    return true;
}

int NFCEctypeModule::OnEctypeSettleEvent(const NFIDENTID& self, int nResult, int nStar)
{
    NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
    if (!pObject.get())
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not exit", "", __FUNCTION__, __LINE__);
        return 1;
    }

    int nSceneID = pObject->GetPropertyInt("SceneID");
    if (nSceneID <= 0)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "scene id error", "", __FUNCTION__, __LINE__);
        return 1;
    }

    // ʧ
    if (nResult == 0)
    {
        int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
        const std::string& strAccout = m_pKernelModule->GetPropertyString(self, "Account");

        std::ostringstream stream;
        stream << "[ExitEctype] Account[" << strAccout << "] Level[" << nLevel << "] Scene[" << nSceneID << "] [0]";
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, stream, __FUNCTION__, __LINE__);
        return 1;
    }

    if (!m_pSceneProcessModule->IsCloneScene(nSceneID))
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not int clone scene", "", __FUNCTION__, __LINE__);
        return 1;
    }

    // ͨؼ¼
    // TODO

    // ͨؽ
    AddEctypeAward(self, nSceneID);

    return 0;
}

bool NFCEctypeModule::CompleteEctypeMode(const NFIDENTID self, const int nContainerID, const int nStar)
{
    NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
    if (NULL == pRecord.get())
    {
        return false;
    }

    //

    return true;
}

int NFCEctypeModule::OnObjectGroupIDEvent(const NFIDENTID& self, const std::string& strPropertyName, const NFIDataList& oldVar, const NFIDataList& newVar, const NFIDataList& argVar)
{

    return 0;
}

int NFCEctypeModule::AddEctypeAward(const NFIDENTID& self, const int nSceneID)
{
    std::string strSceneID = boost::lexical_cast<std::string>(nSceneID);
    int nType = m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneType");

    int nAddMoney = 0;
	int nAddExp = 0;
	int nAddDiamnod = 0;
    NFCDataList xItemList;
    NFCDataList xCountList;

    // 佱
    m_pPackModule->DrawDropAward(self, nAddMoney, nAddExp, xItemList, xCountList);

    // ͨؽ

    // ֪ͨͻ
    NFCDataList xAwardInfoList;
    xAwardInfoList << nAddMoney;
	xAwardInfoList << nAddExp;
	xAwardInfoList << nAddDiamnod;

    if (xItemList.GetCount() == xCountList.GetCount())
    {
        for (int i = 0; i < xItemList.GetCount(); ++i)
        {
            xAwardInfoList << xItemList.String(i);
            xAwardInfoList << xCountList.Int(i);
        }
    }

    m_pEventProcessModule->DoEvent(self, NFED_ON_NOTICE_ECTYPE_AWARD, xAwardInfoList);

    return 0;
}

bool NFCEctypeModule::AddNewEctype(const NFIDENTID self)
{
    int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");

    //

    return true;
}<|endoftext|>


<commit_before>#include "CustomSimulation.h"

#include <Visualization/IRenderer.h>
#include <Simulation/Dynamics/Connection/ConnectorFactory.h>
#include <Simulation/Integration/Implementations/ExplicitEuler.h>
#include <Simulation/Integration/Implementations/ImplicitEuler.h>
#include <Simulation/Integration/Implementations/RungeKutta4.h>
#include <Simulation/Integration/Implementations/RungeKuttaFehlberg45.h>
#include <Visualization/Renderers/LightRenderer.h>
#include <Visualization/Renderers/CoordinateSystemRenderer.h>
#include <Visualization/Renderers/CameraRenderer.h>
#include <Visualization/Renderers/SimulationRunnerRenderer.h>
#include <Visualization/Renderers/TextRenderer.h>
#include <Visualization/Renderers/ConnectorRenderer.h>
#include <Visualization/Renderers/ConnectorVelocityRenderer.h>
#include <Visualization/Renderers/ConnectorForceRenderer.h>
#include <Visualization/Renderers/ParticleRenderer.h>
#include <Visualization/Renderers/BoxRenderer.h>
#include <Visualization/Renderers/SpringRenderer.h>
#include <Visualization/Renderers/TweakBar/TweakBarRenderer.h>
#include <Visualization/UserInterface/DelegateAction.h>
#include <Visualization/UserInterface/RealValue.h>
#include <Visualization/Renderers/PlaneRenderer.h>
#include <Visualization/InputHandler.h>
#include <Simulation/SimulationBuilder.h>
#include <Simulation/Textiles/TextileModel.h>
#include <Simulation/DynamicsAlgorithm.h>
#include <Visualization/Renderers/SphereRenderer.h>
#include <Visualization/Renderers/CollisionRenderer.h>
#include <Visualization/Renderers/OctreeRenderer.h>
#include <Simulation/Geometry/Plane.h>
#include <Simulation/Geometry/BoundingVolumes/BoundingSphere.h>
#include <map>
#include <sstream>
#include <Visualization/Renderers/PolygonRenderer.h>
#include <Visualization/UserInterface/Vector3DValue.h>
#include <Simulation/Geometry/Mesh/Ply/PlyMesh.h>
using namespace IBDS;
using namespace std;

int integratorIndex=0;
vector<SingleStepIntegrator*> integrators;

void CustomSimulation::buildModel(){
	setName("Collision Handling Example");

	CollisionRenderer *  collisionRenderer =new CollisionRenderer(dynamicsAlgorithm.collisionDetector);
	addSimulationObject(collisionRenderer);
	SimulationBuilder b(*this);
	Gravity & g = *(b.setGravity(Vector3D(0,-1,0)));
	g.setGravityMagnitude(0.1);

  addSimulationObject(new DelegateAction("Render Collisions", [collisionRenderer](){collisionRenderer->renderCollisions()=!collisionRenderer->renderCollisions();}));
	addSimulationObject(new RealValue("Collisiontrace Timeout",collisionRenderer->timeout()));
	addSimulationObject(new DelegateAction("Collisiontrace", [collisionRenderer](){
		collisionRenderer->renderCollisionTrace() = !collisionRenderer->renderCollisionTrace();

		}));

	g.setGravityMagnitude(0.1);
	addSimulationObject( new RealValue("Gravity Magnitude",
		[&g](){return g.getGravityMagnitude();},
		[&g](Real val){g.setGravityMagnitude(val);}));

		{
		auto plane = new DynamicGeometry<Plane>(*new Plane(),0,Matrix3x3::Identity());
		plane->coordinates().position() = Vector3D(0,-4,0);
		plane->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),-0.2);
		addSimulationObject(new Vector3DValue("plane ",plane->coordinates().position()));

		addSimulationObject(plane);
		auto renderer = new PlaneRenderer(plane->geometry());
		addSimulationObject(renderer);
		addSimulationObject(new RealValue("plane extent",renderer->extent()));
		addSimulationObject(DynamicCollidable::create(plane->geometry(),plane->body(),0.5,0.01,0.01));
		}

		DynamicBox *body = new DynamicBox(1,1,1,1);
		Real planeAngle = -0.2;
		body->coordinates().position().set(0+5*cos(planeAngle)-0.5*sin(planeAngle),-3.99+5*sin(planeAngle)+0.5*cos(planeAngle),0);
		body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
		addSimulationObject(new BoxRenderer(body->geometry()));
		addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,0.02));

		body = new DynamicBox(1,1,1,1);
		body->coordinates().position().set(0+10*cos(planeAngle)-0.5*sin(planeAngle),-3.99+10*sin(planeAngle)+0.5*cos(planeAngle),0);
		body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
		addSimulationObject(new BoxRenderer(body->geometry()));
		addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,10));

		{
		auto sphere = new DynamicSphere(1,1);
		addSimulationObject(sphere);
		addSimulationObject(new Vector3DValue("sphere",sphere->coordinates().position()));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		sphere->coordinates().position() = Vector3D(1,-2,0);
		addSimulationObject(DynamicCollidable::create(sphere->geometry(),sphere->body(),0.1,100,50));
		}

		{
		auto box = new DynamicBox();
		addSimulationObject(box);
		addSimulationObject(new Vector3DValue("box", box->coordinates().position()));
		addSimulationObject(new BoxRenderer(box->geometry()));
		box->coordinates().position().set(3,2,0);
		addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,* new BoundingSphereFactory()),box->body(),0.3,100,50));
		}

		//{
		//auto pyramid = new DynamicGeometry<Pyramid>(*new Pyramid(),1,Matrix3x3::Identity());
		//addSimulationObject(pyramid);
		//addSimulationObject(new Vector3DValue("pyramid",pyramid->coordinates().position()));
		//addSimulationObject(new PolygonRenderer(pyramid->geometry()));
		//pyramid->coordinates().position().set(3,1,0);
		//addSimulationObject(DynamicCollidable::create(*new Octree(pyramid->geometry(),3,* new BoundingSphereFactory()),pyramid->body(),0.3));
		//}

		{
		DynamicSphere * sphere = 0;
		DynamicCollidable * collidable;

		b.setOffset(Vector3D(10,3,4));
		Real radius = 0.5;

		Particle *particle ;
		particle = b.createParticle("p6",Vector3D(-2,-1,0),1);
		sphere = b.createSphere("s6",Vector3D(-2,-1,0),1,radius);
		b.createBallJoint("j6","s6","p6",Vector3D(-2,-1,0));

		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p5",Vector3D(-2,0,0),0);
		sphere = b.createSphere("s5",Vector3D(-2,-2,0),2,radius);
		b.createBallJoint("j5","s5","p5",Vector3D(-2,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p4",Vector3D(-1,0,0),0);
		sphere = b.createSphere("s4",Vector3D(-1,-2,0),2,radius);
		b.createBallJoint("j4","s4","p4",Vector3D(-1,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p1",Vector3D(0,0,0),0);
		//sphere = b.createSphere("s1",Vector3D(-3,-0.3,0),1,radius);
		sphere = b.createSphere("s1",Vector3D(0,-2,0),2,radius);
		b.createBallJoint("j1","s1","p1",Vector3D(0,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p2",Vector3D(1,0,0),0);
		sphere= b.createSphere("s2",Vector3D(3,0,0),1,radius);
		b.createBallJoint("j2","s2","p2",Vector3D(1,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);
		}

		//{
		//for(int i= 0; i < 2; i++){
		//	Particle * p = new Particle();

		//	Sphere * sphere = new Sphere(0.1);
		//	p->position << sphere->coordinates().position;

		//	Vector3D randVector((rand()%1000)/1000.0,(rand()%1000)/1000.0,(rand()%1000)/1000.0);
		//	p->position() = randVector*5+Vector3D(7,0,0);
		//	p->velocity() = randVector*5 - Vector3D(2.5,2.5,2.5);

		//	DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*p);

		//	addSimulationObject(p);
		//	addSimulationObject(sphere);
		//	addSimulationObject(collidable);
		//	addSimulationObject(new SphereRenderer(*sphere));
		//	}
		//}

    {
      Quaternion orientation;
      orientation.setFromAxisAngle(Vector3D(1,0,0),PI /2);
      int clothDim = 20;
      //TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),200,8,8,clothDim,clothDim);
	  TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),clothDim*clothDim,clothDim/5,clothDim/5,clothDim,clothDim);
      cloth->setElongationSpringConstant(80);
      cloth->setFlexionSpringConstant(80);
      cloth->setShearSpringConstant(80);

      cloth->getNode(0,0)->particle->setMass(0);
      cloth->getNode(clothDim-1,clothDim-1)->particle->setMass(0);
      cloth->getNode(0,clothDim-1)->particle->setMass(0);
      cloth->getNode(clothDim-1,0)->particle->setMass(0);

      addSimulationObject(cloth);
       for_each(cloth->getSimulationObjects().begin(), cloth->getSimulationObjects().end(), [this](ISimulationObject * obj){
        addSimulationObject(obj);
      });

       cloth->foreachNode([this](TextileNode * node){
         Sphere * sphere = new Sphere(0.1);
         DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*node->particle);
         sphere->coordinates().position.mirror(node->particle->position);
         addSimulationObject(sphere);
         //addSimulationObject(new SphereRenderer(*sphere));
         addSimulationObject(collidable);
       });

       DynamicBox * box = new DynamicBox(90);
       box->kinematics().position() = Vector3D(10,2,12);
       addSimulationObject(box);
       addSimulationObject(new PolygonRenderer(box->geometry()));
       addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,*new BoundingSphereFactory()),box->body()));

    }

    {
      /*
      PlyMesh * mesh = new PlyMesh("cube.ply");
      mesh->initialize();
     // mesh->scale(60,60,60);
      addSimulationObject(mesh);
      PolygonRenderer * r = new PolygonRenderer(*mesh);
     r->drawLabels = false;
     r->drawNormals = false;
      addSimulationObject(r);//*/
    }

	}

void CustomSimulation::onSimulationObjectAdded(ISimulationObject * simulationObject){
	Connector * connector = dynamic_cast<Connector*>(simulationObject);
	if(connector){
		addSimulationObject(new ConnectorRenderer(*connector));
		}

	Particle * particle = dynamic_cast<Particle*>(simulationObject);
	if(particle){
		addSimulationObject(new ParticleRenderer(*particle));
		}
	}

void CustomSimulation::buildAlgorithms(){
	integrators.push_back(new ExplicitEuler(0.01));
	integrators.push_back(new ImplicitEuler(0.02));
	integrators.push_back(new RungeKutta4(0.01));

	addSimulationObject(&dynamicsAlgorithm);

	integrator = integrators.at(0);

	integrator->setSystemFunction(dynamicsAlgorithm);

	setIntegrator(*integrator);

	addSimulationObject(new DelegateAction("toggle collision detection",[this](){
		dynamicsAlgorithm.detectCollisions = ! dynamicsAlgorithm.detectCollisions;
		dynamicsAlgorithm.collisionDetector.resetCollisions();
		}));

	addSimulationObject(new DelegateAction("toggle multibody",[this](){
		dynamicsAlgorithm.doMultiBody = ! dynamicsAlgorithm.doMultiBody;
		}));

	addSimulationObject(new RealValue("time", [this](){return getTime();}, [](Real r){}));

	addSimulationObject(new IntValue("Integrator 0-2 (0=ee, 1=ie,2=rk4)",
		[this](){
			return integratorIndex;
		},
			[this](int val){
				integratorIndex = val % 3;
				integrator= integrators.at(integratorIndex);
				integrator->setSystemFunction(dynamicsAlgorithm);
				setIntegrator(*integrator);

			}));

		addSimulationObject( new RealValue("Integrator Step Size",
			[this](){return integrator->getStepSize();},
			[this](Real value){integrator->setStepSize(value);}));

		addSimulationObject(new LightRenderer());
		addSimulationObject(new CoordinateSystemRenderer());// renders coordinate system at world origin

		auto cam = new CameraRenderer();
		cam->position() =Vector3D(8,0,30);
		cam->orientation().setFromAxisAngle(Vector3D(0,1,0),PI/2);
		addSimulationObject(cam);

		addSimulationObject(new Vector3DValue("camera position", cam->position()));

	}

<commit_msg>added an example <commit_after>#include "CustomSimulation.h"

#include <Visualization/IRenderer.h>
#include <Simulation/Dynamics/Connection/ConnectorFactory.h>
#include <Simulation/Integration/Implementations/ExplicitEuler.h>
#include <Simulation/Integration/Implementations/ImplicitEuler.h>
#include <Simulation/Integration/Implementations/RungeKutta4.h>
#include <Simulation/Integration/Implementations/RungeKuttaFehlberg45.h>
#include <Visualization/Renderers/LightRenderer.h>
#include <Visualization/Renderers/CoordinateSystemRenderer.h>
#include <Visualization/Renderers/CameraRenderer.h>
#include <Visualization/Renderers/SimulationRunnerRenderer.h>
#include <Visualization/Renderers/TextRenderer.h>
#include <Visualization/Renderers/ConnectorRenderer.h>
#include <Visualization/Renderers/ConnectorVelocityRenderer.h>
#include <Visualization/Renderers/ConnectorForceRenderer.h>
#include <Visualization/Renderers/ParticleRenderer.h>
#include <Visualization/Renderers/BoxRenderer.h>
#include <Visualization/Renderers/SpringRenderer.h>
#include <Visualization/Renderers/TweakBar/TweakBarRenderer.h>
#include <Visualization/UserInterface/DelegateAction.h>
#include <Visualization/UserInterface/RealValue.h>
#include <Visualization/Renderers/PlaneRenderer.h>
#include <Visualization/InputHandler.h>
#include <Simulation/SimulationBuilder.h>
#include <Simulation/Textiles/TextileModel.h>
#include <Simulation/DynamicsAlgorithm.h>
#include <Visualization/Renderers/SphereRenderer.h>
#include <Visualization/Renderers/CollisionRenderer.h>
#include <Visualization/Renderers/OctreeRenderer.h>
#include <Simulation/Geometry/Plane.h>
#include <Simulation/Geometry/BoundingVolumes/BoundingSphere.h>
#include <map>
#include <sstream>
#include <Visualization/Renderers/PolygonRenderer.h>
#include <Visualization/UserInterface/Vector3DValue.h>
#include <Simulation/Geometry/Mesh/Ply/PlyMesh.h>
using namespace IBDS;
using namespace std;

int integratorIndex=0;
vector<SingleStepIntegrator*> integrators;

void CustomSimulation::buildModel(){
	setName("Collision Handling Example");

	CollisionRenderer *  collisionRenderer =new CollisionRenderer(dynamicsAlgorithm.collisionDetector);
	addSimulationObject(collisionRenderer);
	SimulationBuilder b(*this);
	Gravity & g = *(b.setGravity(Vector3D(0,-1,0)));
	g.setGravityMagnitude(0.1);

  addSimulationObject(new DelegateAction("Render Collisions", [collisionRenderer](){collisionRenderer->renderCollisions()=!collisionRenderer->renderCollisions();}));
	addSimulationObject(new RealValue("Collisiontrace Timeout",collisionRenderer->timeout()));
	addSimulationObject(new DelegateAction("Collisiontrace", [collisionRenderer](){
		collisionRenderer->renderCollisionTrace() = !collisionRenderer->renderCollisionTrace();

		}));

	g.setGravityMagnitude(0.1);
	addSimulationObject( new RealValue("Gravity Magnitude",
		[&g](){return g.getGravityMagnitude();},
		[&g](Real val){g.setGravityMagnitude(val);}));

		{
		auto plane = new DynamicGeometry<Plane>(*new Plane(),0,Matrix3x3::Identity());
		plane->coordinates().position() = Vector3D(0,-4,0);
		plane->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),-0.2);
		addSimulationObject(new Vector3DValue("plane ",plane->coordinates().position()));

		addSimulationObject(plane);
		auto renderer = new PlaneRenderer(plane->geometry());
		addSimulationObject(renderer);
		addSimulationObject(new RealValue("plane extent",renderer->extent()));
		addSimulationObject(DynamicCollidable::create(plane->geometry(),plane->body(),0.5,0.01,0.01));
		}

		DynamicBox *body = new DynamicBox(1,1,1,1);
		Real planeAngle = -0.2;
		body->coordinates().position().set(0+5*cos(planeAngle)-0.5*sin(planeAngle),-3.99+5*sin(planeAngle)+0.5*cos(planeAngle),0);
		body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
		addSimulationObject(new BoxRenderer(body->geometry()));
		addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,0.02));

		body = new DynamicBox(1,1,1,1);
		body->coordinates().position().set(0+10*cos(planeAngle)-0.5*sin(planeAngle),-3.99+10*sin(planeAngle)+0.5*cos(planeAngle),0);
		body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
		addSimulationObject(new BoxRenderer(body->geometry()));
		addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,10));

		{
		auto sphere = new DynamicSphere(1,1);
		addSimulationObject(sphere);
		addSimulationObject(new Vector3DValue("sphere",sphere->coordinates().position()));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		sphere->coordinates().position() = Vector3D(1,-2,0);
		addSimulationObject(DynamicCollidable::create(sphere->geometry(),sphere->body(),0.1,100,50));
		}

		{
		auto box = new DynamicBox();
		addSimulationObject(box);
		addSimulationObject(new Vector3DValue("box", box->coordinates().position()));
		addSimulationObject(new BoxRenderer(box->geometry()));
		box->coordinates().position().set(3,2,0);
		addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,* new BoundingSphereFactory()),box->body(),0.3,100,50));
		}

		//{
		//auto pyramid = new DynamicGeometry<Pyramid>(*new Pyramid(),1,Matrix3x3::Identity());
		//addSimulationObject(pyramid);
		//addSimulationObject(new Vector3DValue("pyramid",pyramid->coordinates().position()));
		//addSimulationObject(new PolygonRenderer(pyramid->geometry()));
		//pyramid->coordinates().position().set(3,1,0);
		//addSimulationObject(DynamicCollidable::create(*new Octree(pyramid->geometry(),3,* new BoundingSphereFactory()),pyramid->body(),0.3));
		//}

		{
		DynamicSphere * sphere = 0;
		DynamicCollidable * collidable;

		b.setOffset(Vector3D(10,3,4));
		Real radius = 0.5;

		Particle *particle ;
		particle = b.createParticle("p6",Vector3D(-2,-1,0),1);
		sphere = b.createSphere("s6",Vector3D(-2,-1,0),1,radius);
		b.createBallJoint("j6","s6","p6",Vector3D(-2,-1,0));

		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p5",Vector3D(-2,0,0),0);
		sphere = b.createSphere("s5",Vector3D(-2,-2,0),2,radius);
		b.createBallJoint("j5","s5","p5",Vector3D(-2,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p4",Vector3D(-1,0,0),0);
		sphere = b.createSphere("s4",Vector3D(-1,-2,0),2,radius);
		b.createBallJoint("j4","s4","p4",Vector3D(-1,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p1",Vector3D(0,0,0),0);
		//sphere = b.createSphere("s1",Vector3D(-3,-0.3,0),1,radius);
		sphere = b.createSphere("s1",Vector3D(0,-2,0),2,radius);
		b.createBallJoint("j1","s1","p1",Vector3D(0,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);

		particle = b.createParticle("p2",Vector3D(1,0,0),0);
		sphere= b.createSphere("s2",Vector3D(3,0,0),1,radius);
		b.createBallJoint("j2","s2","p2",Vector3D(1,0,0));
		addSimulationObject(new SphereRenderer(sphere->geometry()));
		collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
		addSimulationObject(collidable);
		}

		//{
		//for(int i= 0; i < 2; i++){
		//	Particle * p = new Particle();

		//	Sphere * sphere = new Sphere(0.1);
		//	p->position << sphere->coordinates().position;

		//	Vector3D randVector((rand()%1000)/1000.0,(rand()%1000)/1000.0,(rand()%1000)/1000.0);
		//	p->position() = randVector*5+Vector3D(7,0,0);
		//	p->velocity() = randVector*5 - Vector3D(2.5,2.5,2.5);

		//	DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*p);

		//	addSimulationObject(p);
		//	addSimulationObject(sphere);
		//	addSimulationObject(collidable);
		//	addSimulationObject(new SphereRenderer(*sphere));
		//	}
		//}

    {
      Quaternion orientation;
      orientation.setFromAxisAngle(Vector3D(1,0,0),PI /2);
      int clothDim = 20;
      //TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),200,8,8,clothDim,clothDim);
	  TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),clothDim*clothDim,clothDim/5,clothDim/5,clothDim,clothDim);
      cloth->setElongationSpringConstant(80);
      cloth->setFlexionSpringConstant(80);
      cloth->setShearSpringConstant(80);

      cloth->getNode(0,0)->particle->setMass(0);
      cloth->getNode(clothDim-1,clothDim-1)->particle->setMass(0);
      cloth->getNode(0,clothDim-1)->particle->setMass(0);
      cloth->getNode(clothDim-1,0)->particle->setMass(0);

      addSimulationObject(cloth);
       for_each(cloth->getSimulationObjects().begin(), cloth->getSimulationObjects().end(), [this](ISimulationObject * obj){
        addSimulationObject(obj);
      });

       cloth->foreachNode([this](TextileNode * node){
         Sphere * sphere = new Sphere(0.1);
         DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*node->particle);
         sphere->coordinates().position.mirror(node->particle->position);
         addSimulationObject(sphere);
         //addSimulationObject(new SphereRenderer(*sphere));
         addSimulationObject(collidable);
       });

       DynamicBox * box = new DynamicBox(90);
       box->kinematics().position() = Vector3D(10,2,12);
       addSimulationObject(box);
       addSimulationObject(new PolygonRenderer(box->geometry()));
       addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,*new BoundingSphereFactory()),box->body()));
       addSimulationObject(new DelegateAction("box mass",[box](){
         if(box->body().getMass()){
           box->body().setMass(0);
         }else{
           box->body().setMass(1);
         }
       }));
    }

    {
      DynamicGeometry<Rectangle> * rectangle;
      PolygonRenderer * renderer;
      Real spacing=3;
      DynamicCollidable * collidable;
      Vector3D offset(0,0,-3);
      Vector3D left(-1,0,0);
      Vector3D right(1,0,0);
      Real angle = PI/6;
      Vector3D axis(0,0,1);
      Vector2D rectangleDim(3,2);
      Quaternion q;
      Vector3D pos;
      q.setFromAxisAngle(Vector3D(1,0,0),PI/2);
      for(int i=0; i< 4; i++){
        rectangle =   new DynamicGeometry<Rectangle>(
          *new Rectangle(rectangleDim),
          0,
          Matrix3x3::Zero());
        renderer = new PolygonRenderer(rectangle->geometry());
        collidable = DynamicCollidable::create(*new Octree(rectangle->geometry(),4,*new BoundingSphereFactory()),rectangle->body(),0.1);

         pos = offset + Vector3D(0,spacing * i,0);
        Quaternion ori;
        if(i%2){
          pos = pos + right;
          ori.setFromAxisAngle(axis,angle);
        }else{
          pos = pos + left;
          ori.setFromAxisAngle(axis,-angle);
        }

        rectangle->coordinates().position() = pos;
        rectangle->coordinates().orientation() =ori*q;

        addSimulationObject(rectangle);
        addSimulationObject(renderer);
        addSimulationObject(collidable);
      }

      DynamicSphere * sphere = new DynamicSphere(0.1,0.6);
      addSimulationObject(sphere);
      addSimulationObject(new SphereRenderer(sphere->geometry()));
      addSimulationObject(DynamicCollidable::create(sphere->geometry(), sphere->body(),0.4,10,6));
      sphere->coordinates().position() = pos+Vector3D(0,1,0);

    }

    {
      /*
      PlyMesh * mesh = new PlyMesh("cube.ply");
      mesh->initialize();
     // mesh->scale(60,60,60);
      addSimulationObject(mesh);
      PolygonRenderer * r = new PolygonRenderer(*mesh);
     r->drawLabels = false;
     r->drawNormals = false;
      addSimulationObject(r);//*/
    }

	}

void CustomSimulation::onSimulationObjectAdded(ISimulationObject * simulationObject){
	Connector * connector = dynamic_cast<Connector*>(simulationObject);
	if(connector){
		addSimulationObject(new ConnectorRenderer(*connector));
		}

	Particle * particle = dynamic_cast<Particle*>(simulationObject);
	if(particle){
		addSimulationObject(new ParticleRenderer(*particle));
		}
	}

void CustomSimulation::buildAlgorithms(){
	integrators.push_back(new ExplicitEuler(0.01));
	integrators.push_back(new ImplicitEuler(0.02));
	integrators.push_back(new RungeKutta4(0.01));

	addSimulationObject(&dynamicsAlgorithm);

	integrator = integrators.at(0);

	integrator->setSystemFunction(dynamicsAlgorithm);

	setIntegrator(*integrator);

	addSimulationObject(new DelegateAction("toggle collision detection",[this](){
		dynamicsAlgorithm.detectCollisions = ! dynamicsAlgorithm.detectCollisions;
		dynamicsAlgorithm.collisionDetector.resetCollisions();
		}));

	addSimulationObject(new DelegateAction("toggle multibody",[this](){
		dynamicsAlgorithm.doMultiBody = ! dynamicsAlgorithm.doMultiBody;
		}));

	addSimulationObject(new RealValue("time", [this](){return getTime();}, [](Real r){}));

	addSimulationObject(new IntValue("Integrator 0-2 (0=ee, 1=ie,2=rk4)",
		[this](){
			return integratorIndex;
		},
			[this](int val){
				integratorIndex = val % 3;
				integrator= integrators.at(integratorIndex);
				integrator->setSystemFunction(dynamicsAlgorithm);
				setIntegrator(*integrator);

			}));

		addSimulationObject( new RealValue("Integrator Step Size",
			[this](){return integrator->getStepSize();},
			[this](Real value){integrator->setStepSize(value);}));

		addSimulationObject(new LightRenderer());
		addSimulationObject(new CoordinateSystemRenderer());// renders coordinate system at world origin

		auto cam = new CameraRenderer();
		cam->position() =Vector3D(8,0,30);
		cam->orientation().setFromAxisAngle(Vector3D(0,1,0),PI/2);
		addSimulationObject(cam);

		addSimulationObject(new Vector3DValue("camera position", cam->position()));

	}

<|endoftext|>


<commit_before>#ifndef JOEDB_PORTABLE
#include "joedb/concurrency/Local_Connection.h"
#include "joedb/journal/File.h"
#include "joedb/concurrency/Interpreted_Client.h"
#include "joedb/journal/Memory_File.h"

#include "gtest/gtest.h"

using namespace joedb;

static const char * const file_name = "local_connection.joedb";

/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, bad_journal)
/////////////////////////////////////////////////////////////////////////////
{
 std::remove(file_name);
 Local_Connection<File> connection(file_name);

 {
  Memory_File client_file;
  EXPECT_ANY_THROW
  (
   Interpreted_Client client(connection, client_file)
  );
 }

 Interpreted_Client client(connection, connection.get_file());
}

/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, simple_operation)
/////////////////////////////////////////////////////////////////////////////
{
 std::remove(file_name);

 Local_Connection<File> connection1(file_name);
 Local_Connection<File> connection2(file_name);

 Interpreted_Client client1(connection1, connection1.get_file());
 Interpreted_Client client2(connection2, connection2.get_file());

 client1.transaction
 (
  [](Readable &readable, Writable &writable)
  {
   writable.create_table("person");
  }
 );

 EXPECT_EQ(0, int(client2.get_database().get_tables().size()));
 client2.pull();
 EXPECT_EQ(1, int(client2.get_database().get_tables().size()));

 client2.transaction
 (
  [](Readable &readable, Writable &writable)
  {
   writable.create_table("city");
  }
 );

 EXPECT_EQ(1, int(client1.get_database().get_tables().size()));
 client1.pull();
 EXPECT_EQ(2, int(client1.get_database().get_tables().size()));
}
#endif
<commit_msg>unit test for Local_Connection size_check.<commit_after>#include <joedb/Writable.h>
#include <joedb/journal/Generic_File.h>
#include <joedb/journal/Writable_Journal.h>
#ifndef JOEDB_PORTABLE
#include "joedb/concurrency/Local_Connection.h"
#include "joedb/journal/File.h"
#include "joedb/concurrency/Interpreted_Client.h"
#include "joedb/journal/Memory_File.h"

#include "gtest/gtest.h"

using namespace joedb;

static const char * const file_name = "local_connection.joedb";

/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, bad_journal)
/////////////////////////////////////////////////////////////////////////////
{
 std::remove(file_name);
 Local_Connection<File> connection(file_name);

 {
  Memory_File client_file;
  EXPECT_ANY_THROW
  (
   Interpreted_Client client(connection, client_file)
  );
 }

 Interpreted_Client client(connection, connection.get_file());
}

/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, simple_operation)
/////////////////////////////////////////////////////////////////////////////
{
 std::remove(file_name);

 Local_Connection<File> connection1(file_name);
 Local_Connection<File> connection2(file_name);

 Interpreted_Client client1(connection1, connection1.get_file());
 Interpreted_Client client2(connection2, connection2.get_file());

 client1.transaction
 (
  [](Readable &readable, Writable &writable)
  {
   writable.create_table("person");
  }
 );

 EXPECT_EQ(0, int(client2.get_database().get_tables().size()));
 client2.pull();
 EXPECT_EQ(1, int(client2.get_database().get_tables().size()));

 client2.transaction
 (
  [](Readable &readable, Writable &writable)
  {
   writable.create_table("city");
  }
 );

 EXPECT_EQ(1, int(client1.get_database().get_tables().size()));
 client1.pull();
 EXPECT_EQ(2, int(client1.get_database().get_tables().size()));
}

/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, size_check)
/////////////////////////////////////////////////////////////////////////////
{
 std::remove(file_name);

 {
  joedb::File file(file_name, joedb::Open_Mode::create_new);
  joedb::Writable_Journal journal(file);
  journal.timestamp(0);
  journal.flush();
 }

 try
 {
  Local_Connection<File> connection(file_name);
  FAIL() << "Expected an exception\n";
 }
 catch(...)
 {
 }
}
#endif
<|endoftext|>