<commit_before>/*

This file is part of VROOM.

Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#ifndef _WIN32
#include <unistd.h>
#endif

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "../include/cxxopts/include/cxxopts.hpp"
#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "utils/exception.h"
#include "utils/helpers.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

int main(int argc, char** argv) {
  vroom::io::CLArgs cl_args;
  std::string host_arg;
  std::string port_arg;
  std::string router_arg;
  std::string limit_arg;
  std::string nb_threads_arg;
  std::vector<std::string> heuristic_params_arg;

  // clang-format off
  cxxopts::Options options(
    "vroom",
    "VROOM Copyright (C) 2015-2022, Julien Coupey\n"
    "Version: " + vroom::get_version() + "\n\n"
    "A command-line utility to solve complex vehicle routing problems.\n"
    );

  options
    .set_width(80)
    .set_tab_expansion()
    .add_options("main_group")
    ("h,help", "Print this help message.")
    ("v,version", "Print the version of this software.")
    ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'", cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0"))
    ("c,choose-eta", "Choose ETA for custom routes and report violations.", cxxopts::value<bool>(cl_args.check)->default_value("false"))
    ("g,geometry", "Add detailed route geometry and indicators", cxxopts::value<bool>(cl_args.geometry)->default_value("false"))
    ("i,input-file", "Read input from 'input-file' rather than from stdin", cxxopts::value<std::string>(cl_args.input_file))
    ("l,limit", "Stop solving process after 'limit' seconds", cxxopts::value<std::string>(limit_arg)->default_value(""))
    ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file))
    ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'", cxxopts::value<std::string>(port_arg)->default_value("car:5000"))
    ("r,router", "osrm, libosrm, ors or valhalla", cxxopts::value<std::string>(router_arg)->default_value("osrm"))
    ("t,threads", "Number of threads to use", cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4"))
    ("x,explore", "Exploration level to use (0..5)", cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5"))
    ("input", "optional input positional arg", cxxopts::value<std::string>(cl_args.input));

  try {
    // we don't want to print debug args on --help
    options.add_options("debug_group")
      ("e,heuristic-param", "Heuristic parameter", cxxopts::value<std::vector<std::string>>(heuristic_params_arg));
    // clang-format on

    options.parse_positional({"input"});
    options.positional_help("OPTIONAL INLINE JSON");
    auto parsed_args = options.parse(argc, argv);

    if (parsed_args.count("help")) {
      std::cout << options.help({"main_group"}) << "\n";
      exit(0);
    }

    if (parsed_args.count("version")) {
      std::cout << "vroom " << vroom::get_version() << "\n";
      exit(0);
    }
  } catch (const cxxopts::OptionException& e) {
    auto error_code = vroom::InputException("").error_code;
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()}, false, cl_args.output_file);
    exit(error_code);
  }

  // parse and update some params
  vroom::io::update_host(cl_args.servers, host_arg);
  vroom::io::update_port(cl_args.servers, port_arg);
  if (!limit_arg.empty()) {
    // Internally timeout is in milliseconds.
    cl_args.timeout = 1000 * std::stof(limit_arg);
  }
  cl_args.exploration_level =
    std::min(cl_args.exploration_level, cl_args.max_exploration_level);

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (router_arg == "ors") {
    cl_args.router = vroom::ROUTER::ORS;
  } else if (router_arg == "valhalla") {
    cl_args.router = vroom::ROUTER::VALHALLA;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    auto error_code = vroom::InputException("").error_code;
    std::string message = "Invalid routing engine: " + router_arg + ".";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }

  try {
    // Force heuristic parameters from the command-line, useful for
    // debugging.
    std::transform(heuristic_params_arg.begin(),
                   heuristic_params_arg.end(),
                   std::back_inserter(cl_args.h_params),
                   [](const auto& str_param) {
                     return vroom::utils::str_to_heuristic_param(str_param);
                   });
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({e.error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(e.error_code);
  }

  // Read input problem
  if (cl_args.input.empty()) {
    std::stringstream buffer;
    if (!cl_args.input_file.empty()) {
      std::ifstream ifs(cl_args.input_file);
      buffer << ifs.rdbuf();
    } else {
      buffer << std::cin.rdbuf();
    }
    cl_args.input = buffer.str();
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol = (cl_args.check)
                            ? problem_instance.check(cl_args.nb_threads)
                            : problem_instance.solve(cl_args.exploration_level,
                                                     cl_args.nb_threads,
                                                     cl_args.timeout,
                                                     cl_args.h_params);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({e.error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(e.error_code);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto error_code = vroom::RoutingException("").error_code;
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    auto error_code = vroom::InternalException("").error_code;
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  return 0;
}
<commit_msg>try to remove clang-format<commit_after>/*

This file is part of VROOM.

Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#ifndef _WIN32
#include <unistd.h>
#endif

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "../include/cxxopts/include/cxxopts.hpp"

#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "utils/exception.h"
#include "utils/helpers.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

int main(int argc, char** argv) {
  vroom::io::CLArgs cl_args;
  std::string host_arg;
  std::string port_arg;
  std::string router_arg;
  std::string limit_arg;
  std::string nb_threads_arg;
  std::vector<std::string> heuristic_params_arg;

  cxxopts::Options options(
    "vroom",
    "VROOM Copyright (C) 2015-2022, Julien Coupey\n"
    "Version: " + vroom::get_version() + "\n\n"
    "A command-line utility to solve complex vehicle routing problems.\n"
    );

  options
    .set_width(80)
    .set_tab_expansion()
    .add_options("main_group")
    ("h,help", "Print this help message.")
    ("v,version", "Print the version of this software.")
    ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'",
      cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0"))
    ("c,choose-eta", "Choose ETA for custom routes and report violations.",
      cxxopts::value<bool>(cl_args.check)->default_value("false"))
    ("g,geometry", "Add detailed route geometry and indicators",
      cxxopts::value<bool>(cl_args.geometry)->default_value("false"))
    ("i,input-file", "Read input from 'input-file' rather than from stdin",
      cxxopts::value<std::string>(cl_args.input_file))
    ("l,limit", "Stop solving process after 'limit' seconds",
      cxxopts::value<std::string>(limit_arg)->default_value(""))
    ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file))
    ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'",
      cxxopts::value<std::string>(port_arg)->default_value("car:5000"))
    ("r,router", "osrm, libosrm, ors or valhalla",
      cxxopts::value<std::string>(router_arg)->default_value("osrm"))
    ("t,threads", "Number of threads to use",
      cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4"))
    ("x,explore", "Exploration level to use (0..5)",
      cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5"))
    ("input", "optional input positional arg",
      cxxopts::value<std::string>(cl_args.input));

  try {
    // we don't want to print debug args on --help
    options.add_options("debug_group")
      ("e,heuristic-param", "Heuristic parameter",
      cxxopts::value<std::vector<std::string>>(heuristic_params_arg));

    options.parse_positional({"input"});
    options.positional_help("OPTIONAL INLINE JSON");
    auto parsed_args = options.parse(argc, argv);

    if (parsed_args.count("help")) {
      std::cout << options.help({"main_group"}) << "\n";
      exit(0);
    }

    if (parsed_args.count("version")) {
      std::cout << "vroom " << vroom::get_version() << "\n";
      exit(0);
    }
  } catch (const cxxopts::OptionException& e) {
    auto error_code = vroom::InputException("").error_code;
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()}, false, cl_args.output_file);
    exit(error_code);
  }

  // parse and update some params
  vroom::io::update_host(cl_args.servers, host_arg);
  vroom::io::update_port(cl_args.servers, port_arg);
  if (!limit_arg.empty()) {
    // Internally timeout is in milliseconds.
    cl_args.timeout = 1000 * std::stof(limit_arg);
  }
  cl_args.exploration_level =
    std::min(cl_args.exploration_level, cl_args.max_exploration_level);

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (router_arg == "ors") {
    cl_args.router = vroom::ROUTER::ORS;
  } else if (router_arg == "valhalla") {
    cl_args.router = vroom::ROUTER::VALHALLA;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    auto error_code = vroom::InputException("").error_code;
    std::string message = "Invalid routing engine: " + router_arg + ".";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }

  try {
    // Force heuristic parameters from the command-line, useful for
    // debugging.
    std::transform(heuristic_params_arg.begin(),
                   heuristic_params_arg.end(),
                   std::back_inserter(cl_args.h_params),
                   [](const auto& str_param) {
                     return vroom::utils::str_to_heuristic_param(str_param);
                   });
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({e.error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(e.error_code);
  }

  // Read input problem
  if (cl_args.input.empty()) {
    std::stringstream buffer;
    if (!cl_args.input_file.empty()) {
      std::ifstream ifs(cl_args.input_file);
      buffer << ifs.rdbuf();
    } else {
      buffer << std::cin.rdbuf();
    }
    cl_args.input = buffer.str();
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol = (cl_args.check)
                            ? problem_instance.check(cl_args.nb_threads)
                            : problem_instance.solve(cl_args.exploration_level,
                                                     cl_args.nb_threads,
                                                     cl_args.timeout,
                                                     cl_args.h_params);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({e.error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(e.error_code);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto error_code = vroom::RoutingException("").error_code;
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    auto error_code = vroom::InternalException("").error_code;
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <limits>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <iostream>
#include <fstream>

/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/

#ifdef _WIN32

#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif

#endif

#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = static_cast<char>(tolower(c));
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

int main(int, char *argv[])
{
    CurlGlobalInit curl_global;

#ifdef _WIN32
    std::string nwn_bin("nwmain.exe");
    std::string nwn_root_dir("./");
    std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);
    if (!nwn)
    {
        std::cout << "Current launcher directory not detected as NWN root"\
        " directory.";
        nwn_root_dir = "C:/NeverwinterNights/NWN/";
        std::cout << "\nTrying " << nwn_root_dir << "... ";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);

        if (!nwn)
        {
            std::cout << "not found.\nSearching registry... ";
            SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
                "Location");
            if (reg.good())
            {
                nwn_root_dir = reg.str();
                std::cout << "key found.";
                auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
                if (path_sep != '/' && path_sep != '\\')
                {
                    nwn_root_dir.append("/");
                }
                std::cout << "\nTrying " << nwn_root_dir << "... ";
                nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
                if (!nwn)
                {
                    std::cout << "not found.";
                }
            }
            else
            {
                std::cout << "no key found.";
            }
        }
    }
    if (nwn)
    {
        std::cout << nwn_bin << " found." << std::endl;
    }
    else
    {
        std::cout << "\n\nNWN root directory not found, known"\
            " options exhausted."\
            "\nThe launcher will not be able to download files to the correct"\
            " location or"\
            "\nlaunch Neverwinter Nights, however, the launcher"\
            " may still download files to"\
            "\nthe current directory and you can"\
            " move them manually afterwards. To avoid this"\
            "\nin the future"\
            " either move the launcher to the NWN root directory containing"\
            "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
            " the launcher"\
            "\nexecutable, substituting the correct path, quoted"\
            " if it contains spaces:"\
            "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
            "\n/ and \\ are interchangeable."\
            "\nWould you like to download files anyway (y/n)?" << std::endl;
        if (!confirm())
        {
            std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
            return 0;
        }
    }
#endif

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            if (l.get_update())
            {
                std::cout << "Done. Please extract and run the new launcher." << std::endl;
            }
            return 0;
        }
    }

    try
    {
        l.stat_targets();
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<commit_msg>(Win) Launch nwmain.exe with EfU direct-connect.<commit_after>#include <limits>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <iostream>
#include <fstream>
#include <vector>

/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/

#ifdef _WIN32

#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif

#ifndef EFU_TARGET_H
#include "target.h"
#endif

#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif

#endif

#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = static_cast<char>(tolower(c));
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

int main(int argc, char *argv[])
{
    CurlGlobalInit curl_global;

#ifdef _WIN32
    std::string nwn_bin("nwmain.exe");
    std::string nwn_root_dir("./");
    std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);
    if (!nwn)
    {
        std::cout << "Current launcher directory not detected as NWN root"\
        " directory.";
        nwn_root_dir = "C:/NeverwinterNights/NWN/";
        std::cout << "\nTrying " << nwn_root_dir << "... ";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);

        if (!nwn)
        {
            std::cout << "not found.\nSearching registry... ";
            SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
                "Location");
            if (reg.good())
            {
                nwn_root_dir = reg.str();
                std::cout << "key found.";
                auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
                if (path_sep != '/' && path_sep != '\\')
                {
                    nwn_root_dir.append("/");
                }
                std::cout << "\nTrying " << nwn_root_dir << "... ";
                nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
                if (!nwn)
                {
                    std::cout << "not found.";
                }
            }
            else
            {
                std::cout << "no key found.";
            }
        }
    }
    if (nwn)
    {
        std::cout << nwn_bin << " found." << std::endl;
    }
    else
    {
        std::cout << "\n\nNWN root directory not found, known"\
            " options exhausted."\
            "\nThe launcher will not be able to download files to the correct"\
            " location or"\
            "\nlaunch Neverwinter Nights, however, the launcher"\
            " may still download files to"\
            "\nthe current directory and you can"\
            " move them manually afterwards. To avoid this"\
            "\nin the future"\
            " either move the launcher to the NWN root directory containing"\
            "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
            " the launcher"\
            "\nexecutable, substituting the correct path, quoted"\
            " if it contains spaces:"\
            "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
            "\n/ and \\ are interchangeable."\
            "\nWould you like to download files anyway (y/n)?" << std::endl;
        if (!confirm())
        {
            std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
            return 0;
        }
    }
#endif

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            if (l.get_update())
            {
                std::cout << "Done. Please extract and run the new launcher." << std::endl;
            }
            return 0;
        }
    }

    try
    {
        l.stat_targets();
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

#ifdef _WIN32
    if (nwn)
    {
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ::ZeroMemory(&pi, sizeof(pi));
        ::ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);

        auto nwn_path(nwn_root_dir + nwn_bin);
        auto cmd_line(nwn_path + " +connect nwn.efupw.com:5121");

        const std::vector<const std::string> args(argv + 1, argv + argc);

        for (size_t i = 0; i < args.size(); ++i)
        {
            auto arg(args.at(i));

            if (arg.find("-dmpass") == 0)
            {
                auto cmd(split(arg, '='));
                if (cmd.size() == 2)
                {
                    cmd_line.append(" -dmc +password " + cmd.at(1));
                }
                else
                {
                    std::cout << "-dmpass specified but no value given. Use\n"\
                        "-dmpass=mypassword" <<std::endl;
                }
            }
            else if (arg.find("-nwn") == 0)
            {
                auto cmd(split(arg, '='));
                if (cmd.size() == 2)
                {
//                    cmd_line.append(" -nwn " + cmd.at(1));
                }
                else
                {
                    std::cout << "-nwn specified but no value given. Use\n"\
                        "-nwn=\"path\\to\\NWN\\directory\\" <<std::endl;
                }
            }
            else
            {
                std::cout << "Ignoring unrecognized argument: " << arg
                    << std::endl;
            }
        }

        BOOL success = ::CreateProcess(
            const_cast<char *>(nwn_path.c_str()),
            const_cast<char *>(cmd_line.c_str()),
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            const_cast<char *>(nwn_root_dir.c_str()),           // Starting directory
            &si, &pi);
        if (success)
        {
            ::CloseHandle(pi.hProcess);
            ::CloseHandle(pi.hThread);
        }
        else
        {
            WinErrorString we;
            std::cout << we.str() << std::endl;
        }
    }
#endif

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <queue>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include "argument.h"
#include "parse.h"
#include <cstddef>
#include <stdexcept>

using namespace std;
using namespace boost;

typedef boost::tokenizer<boost::char_separator<char> > mytok;
typedef mytok::iterator tok_it;

int main()
{
	while(1) {
		try {
			// Declare variables
			char *login = getlogin();
			char host[200];
		    if(gethostname(host, 200) == -1) perror("hostname");
			string bash_input;

			// Output user information
			cout << login << "@" << host << "$ ";
			getline(cin, bash_input);

			// Look for comments and remove comments if necessary
			size_t s = bash_input.find("#");
			if (s != string::npos) {
				bash_input.erase(s);
			}

			// Trim left and right whitespace
			string bash_command = trim_copy(bash_input);

         // Now look for exit as only command and quit if necessary
			if (bash_command == "exit") {
				exit(0);
			}

			// Create commands and execute bash line
			Base* start = parse(bash_command);
         if (start != 0) {
				start->execute();
			}
			delete start;
		}
		catch (runtime_error &e) {
			cout << "-rshell: " << e.what() << endl;
		}
	}

	return 0;
}
<commit_msg>added directory to prompt<commit_after>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <queue>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include "argument.h"
#include "parse.h"
#include <cstddef>
#include <stdexcept>

using namespace std;
using namespace boost;

typedef boost::tokenizer<boost::char_separator<char> > mytok;
typedef mytok::iterator tok_it;

int main()
{
	while(1)
	{
		try
		{
			// Declare variables
			char *login = getlogin();
			char host[200];
		    if(gethostname(host, 200) == -1) perror("hostname");
			string bash_input;

			// Output user information
			cout << login << "@" << host << ':' << getenv("PWD") << " $ ";
			getline(cin, bash_input);

			// Look for comments and remove comments if necessary
			size_t s = bash_input.find("#");
			if (s != string::npos)
			{
				bash_input.erase(s);
			}

			// Trim left and right whitespace
			string bash_command = trim_copy(bash_input);

         // Now look for exit as only command and quit if necessary
			if (bash_command == "exit")
			{
				exit(0);
			}

			// Create commands and execute bash line
			Base* start = parse(bash_command);
        	if (start != 0)
        	{
				start->execute();
			}

			delete start;

		}
		catch (runtime_error &e) {
			cout << "-rshell: " << e.what() << endl;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "Kernel.h"
#include "ForegroundApp.h"

#ifdef BUILD_DAEMON
#	include "DaemonApp.h"
#endif /* BUILD_DAEMON */

#include "Log.h"
#include "exception.h"
#include "module_loader.h"
#include "path.h"
#include <cstring>
#include <cstdlib>
#include <limits.h>
#include <signal.h>
#include <portable/portable.h>
#include <portable/time.h>
#include "backend/platform.h"
#include "Browser.h"

// for getcwd
#ifdef WIN32
#	include <direct.h>
#	define getcwd _getcwd
#	define PATH_MAX _MAX_PATH
#endif

static Kernel* application = NULL;

static void sighandler(int signum){
	switch ( signum ){
	case SIGINT:
		Log::verbose("IPC: Quit\n");
		application->quit();
		break;
	case SIGHUP:
		Log::verbose("IPC: Reload browser\n");
		application->reload_browser();
		signal(SIGHUP, sighandler);
		break;
	}
}

int main( int argc, const char* argv[] ){
	try {

		// Default arguments
		Kernel::argument_set_t arguments = {
			Kernel::ForegroundMode, // mode
			Log_Info, 				// loglevel
			false,					// fullscreen
			false,					// have_password
			0, 						// queue_id
			800,					// width
			600,					// height
			3.0f,					// transition_time;
			5.0f,					// switch_time;
			NULL,					// connection_string
			NULL,					// transition_string
			NULL,					// file log
			NULL,					// named pipe log
			NULL,					// unix domain socket log

			NULL,                   // Frontend URL.
			NULL,                   // Instance name.
		};

		// Parse the cli arguments, overriding the defaults. Throw an exception
		// if running as a child (e.g. from a front-end).
		if ( !Kernel::parse_arguments(arguments, argc, argv) && !isatty(STDOUT_FILENO) ){
			throw exception("Failed to parse commandline arguments");
		}

		portable_init(stderr);
		moduleloader_init(pluginpath());
		PlatformBackend::register_all();

		Log::initialize();

		/* only log to stdout if no other destination has been set */
		if ( !(arguments.log_file || arguments.log_fifo || arguments.log_domain) ){
			Log::add_destination(new FileDestination(stdout));
		}

		/* setup file log */
		if ( arguments.log_file ){
			Log::add_destination(new FileDestination(arguments.log_file));
		}

		/* setup named pipe log */
		if ( arguments.log_fifo ){
			Log::add_destination(new FIFODestination(arguments.log_fifo));
		}

		/* setup unix domain socket log */
		if ( arguments.log_domain ){
			UDSServer d(arguments.log_domain);
			d.accept(NULL);
		}

#ifdef HAVE_SYSLOG
		Log::add_destination(new SyslogDestination());
#endif /* HAVE_SYSLOG */
		//Log::set_level( (Log::Severity)arguments.loglevel );

		/* Kernel takes ownership of backend and will release memory when finished */
		const char* backend_name = "sdl";
		PlatformBackend* backend = PlatformBackend::factory(backend_name);
		if ( !backend ){
			throw exception("Failed to create a backend named \"%s\"", backend_name);
		}

		switch ( arguments.mode ){
			case Kernel::ForegroundMode:
				application = new ForegroundApp(arguments, backend);
				break;
			case Kernel::DaemonMode:
#ifdef BUILD_DAEMON
				application = new DaemonApp(arguments, backend); break;
#else /* BUILD_DAEMON */
				throw exception("DaemonMode is not supported on this platform.");
#endif /* BUILD_DAEMON */
			case Kernel::ListTransitionMode:
				Kernel::print_transitions();
				throw ExitException();
			default:
				throw exception("No valid mode. This should not happen, please report this to the maintainer. Modeid: %d\n", arguments.mode);
		}

		signal(SIGINT, sighandler);
		signal(SIGHUP, sighandler);

		application->init();
		application->run();
		application->cleanup();

		delete application;
		application = NULL;

		moduleloader_cleanup();
		PlatformBackend::register_cleanup();

		Log::cleanup();

	} catch ( ExitException &e ){
		printf("exit exception\n");
		return e.code();

	} catch ( exception &e ){
		/* Handle unhandled exceptions, if anythin makes it here it is a fatal
		 * error and it is not possible to continue operation. */

		char cwd[PATH_MAX];

		if ( getcwd(cwd, 256) == NULL ){
			fprintf(stderr, "Failed to get cwd\n");
			cwd[0] = '\0';
		}

		fprintf(stderr, " *** slideshow unhandled exception ***\n");
		fprintf(stderr, "\tcwd:     %s\n", cwd);
		fprintf(stderr, "\tSource:  %s:%d\n", e.file(), e.line());
		fprintf(stderr, "\tMessage: %s\n\n", e.what());
		fprintf(stderr, "Troubleshooting:\n");
		fprintf(stderr, " - Make sure that all required dll's are installed.\n");
		fprintf(stderr, " - Make sure that the cwd is correct.\n\n");
		fprintf(stderr, "If the problem persists report the bug at\n"
				"http://sidvind.com:8000/slideshow/newticket\n"
				"and copy the entire output from the console.\n\n");
		fprintf(stderr, "This is a fatal error, the application will now terminate!\n\n");

		fflush(stderr);

		if ( getenv("SLIDESHOW_NO_ABORT") ) {
			return 1;
		} else {
#ifdef WIN32
			__debugbreak();
#elif defined(__GNUC__)
			__builtin_trap();
#else
			abort();
#endif
		}

		/* silence compiler warnings */
		return -1;
	}

	return 0;
}
<commit_msg>update crash message to reflect move to github and add package version.<commit_after>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "Kernel.h"
#include "ForegroundApp.h"

#ifdef BUILD_DAEMON
#	include "DaemonApp.h"
#endif /* BUILD_DAEMON */

#include "Log.h"
#include "exception.h"
#include "module_loader.h"
#include "path.h"
#include <cstring>
#include <cstdlib>
#include <limits.h>
#include <signal.h>
#include <portable/portable.h>
#include <portable/time.h>
#include "backend/platform.h"
#include "Browser.h"

// for getcwd
#ifdef WIN32
#	include <direct.h>
#	define getcwd _getcwd
#	define PATH_MAX _MAX_PATH
#endif

static Kernel* application = NULL;

static void sighandler(int signum){
	switch ( signum ){
	case SIGINT:
		Log::verbose("IPC: Quit\n");
		application->quit();
		break;
	case SIGHUP:
		Log::verbose("IPC: Reload browser\n");
		application->reload_browser();
		signal(SIGHUP, sighandler);
		break;
	}
}

int main( int argc, const char* argv[] ){
	try {

		// Default arguments
		Kernel::argument_set_t arguments = {
			Kernel::ForegroundMode, // mode
			Log_Info, 				// loglevel
			false,					// fullscreen
			false,					// have_password
			0, 						// queue_id
			800,					// width
			600,					// height
			3.0f,					// transition_time;
			5.0f,					// switch_time;
			NULL,					// connection_string
			NULL,					// transition_string
			NULL,					// file log
			NULL,					// named pipe log
			NULL,					// unix domain socket log

			NULL,                   // Frontend URL.
			NULL,                   // Instance name.
		};

		// Parse the cli arguments, overriding the defaults. Throw an exception
		// if running as a child (e.g. from a front-end).
		if ( !Kernel::parse_arguments(arguments, argc, argv) && !isatty(STDOUT_FILENO) ){
			throw exception("Failed to parse commandline arguments");
		}

		portable_init(stderr);
		moduleloader_init(pluginpath());
		PlatformBackend::register_all();

		Log::initialize();

		/* only log to stdout if no other destination has been set */
		if ( !(arguments.log_file || arguments.log_fifo || arguments.log_domain) ){
			Log::add_destination(new FileDestination(stdout));
		}

		/* setup file log */
		if ( arguments.log_file ){
			Log::add_destination(new FileDestination(arguments.log_file));
		}

		/* setup named pipe log */
		if ( arguments.log_fifo ){
			Log::add_destination(new FIFODestination(arguments.log_fifo));
		}

		/* setup unix domain socket log */
		if ( arguments.log_domain ){
			UDSServer d(arguments.log_domain);
			d.accept(NULL);
		}

#ifdef HAVE_SYSLOG
		Log::add_destination(new SyslogDestination());
#endif /* HAVE_SYSLOG */
		//Log::set_level( (Log::Severity)arguments.loglevel );

		/* Kernel takes ownership of backend and will release memory when finished */
		const char* backend_name = "sdl";
		PlatformBackend* backend = PlatformBackend::factory(backend_name);
		if ( !backend ){
			throw exception("Failed to create a backend named \"%s\"", backend_name);
		}

		switch ( arguments.mode ){
			case Kernel::ForegroundMode:
				application = new ForegroundApp(arguments, backend);
				break;
			case Kernel::DaemonMode:
#ifdef BUILD_DAEMON
				application = new DaemonApp(arguments, backend); break;
#else /* BUILD_DAEMON */
				throw exception("DaemonMode is not supported on this platform.");
#endif /* BUILD_DAEMON */
			case Kernel::ListTransitionMode:
				Kernel::print_transitions();
				throw ExitException();
			default:
				throw exception("No valid mode. This should not happen, please report this to the maintainer. Modeid: %d\n", arguments.mode);
		}

		signal(SIGINT, sighandler);
		signal(SIGHUP, sighandler);

		application->init();
		application->run();
		application->cleanup();

		delete application;
		application = NULL;

		moduleloader_cleanup();
		PlatformBackend::register_cleanup();

		Log::cleanup();

	} catch ( ExitException &e ){
		printf("exit exception\n");
		return e.code();

	} catch ( exception &e ){
		/* Handle unhandled exceptions, if anythin makes it here it is a fatal
		 * error and it is not possible to continue operation. */

		char cwd[PATH_MAX];

		if ( getcwd(cwd, 256) == NULL ){
			fprintf(stderr, "Failed to get cwd\n");
			cwd[0] = '\0';
		}

		fprintf(stderr, " *** "PACKAGE" unhandled exception ***\n");
		fprintf(stderr, "\tversion: "PACKAGE"-"VERSION"\n");
		fprintf(stderr, "\tcwd:     %s\n", cwd);
		fprintf(stderr, "\tSource:  %s:%d\n", e.file(), e.line());
		fprintf(stderr, "\tMessage: %s\n\n", e.what());
		fprintf(stderr, "Troubleshooting:\n");
		fprintf(stderr, " - Make sure that all required shared libraries are installed.\n");
		fprintf(stderr, " - Make sure that the cwd is correct.\n\n");
		fprintf(stderr, "If the problem persists report the bug at\n"
				"https://github.com/ext/slideshow/issues/new\n"
				"and copy the entire output from the console.\n\n");
		fprintf(stderr, "This is a fatal error, the application will now terminate!\n\n");

		fflush(stderr);

		if ( getenv("SLIDESHOW_NO_ABORT") ) {
			return 1;
		} else {
#ifdef WIN32
			__debugbreak();
#elif defined(__GNUC__)
			__builtin_trap();
#else
			abort();
#endif
		}

		/* silence compiler warnings */
		return -1;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "input/filter.h"
#include "input/format.h"
#include "encoder/encoder.h"
#include "sjoin/sjoin.h"
#include "virtualizer/virtualizer.h"
#include <ctime>
#include <stdio.h>

int process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {
    FILE *fl;
    FILE *fr;
    FILE *fc;
    FILE *bl;
    FILE *br;
    const char * fl_filename = "FL.aac";
    const char * fr_filename = "FR.aac";
    const char * fc_filename = "FC.aac";
    const char * bl_filename = "BL.aac";
    const char * br_filename = "BR.aac";

    AVPacket packet, packet0;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;
    complete_sofa sofa_;

    AVPacket packet_out;
    int got_output;

    Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,
            fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);

    SJoin  *sjoin  = new SJoin(encoder);

    fl = fopen(fl_filename, "wb");
    fr = fopen(fr_filename, "wb");
    fc = fopen(fc_filename, "wb");
    bl = fopen(bl_filename, "wb");
    br = fopen(br_filename, "wb");
    if(!fl || !fr || !fc || !bl || !br) {
        std::cout << "Error opening file" << std::endl;
    }

    int ret = 0;

    /* Read all of the packets */
    packet0.data = NULL;
    packet.data = NULL;
    while(1) {

        if(!packet0.data) {
            ret = av_read_frame(fmt->format_ctx, &packet);
            if(ret < 0) break;
            packet0 = packet;
        }

        if(packet.stream_index == fmt->audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);

            if(ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }

            packet.size -= ret;
            packet.data += ret;

            if(got_frame) {

                /* push audio from decoded frame through filter graph */
                if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                    break;
                }

                while(ret >= 0) {
                    // This is where you will work with each processed frame.

                    int i = 0;

                    for (auto it = filter->abuffersink_ctx_map.begin();
                            it != filter->abuffersink_ctx_map.end(); it++) {

                        ret = av_buffersink_get_frame(it->second, filt_frame);
                        if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;

                        int sample_count = filt_frame->nb_samples;
                        int sample_rate = filt_frame->sample_rate;

                        if (c2v_.count(it->first) == 0) {
                            float x;
                            float y;
                            float z;
                            Filter::get_coords(it->first, &x, &y, &z);

                            if (sofa_.hrtf == NULL) {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                                sofa_ = virt->get_hrtf();
                            }
                            else {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                            }
                        }

                        float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        float ** float_results = c2v_[it->first]->process(samples, sample_count);

                        uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        delete[] float_results[0];
                        delete[] float_results[1];
                        delete[] float_results;
                        delete[] samples;

                        AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,
                                result_l);

                        // apparently, new_frame just points to our data, it doesn't make a copy
                        //free(result_l);
                        //free(result_r);

                        // This will move once virtualizaiton works
                        av_init_packet(&packet_out);
                        packet_out.data = NULL;
                        packet_out.size = 0;

                        ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);
                        if(ret < 0) exit(1);

                        if(it->first == Filter::FL && got_output) fwrite(packet_out.data, 1, packet_out.size, fl);
                        else if(it->first == Filter::FR && got_output) fwrite(packet_out.data, 1, packet_out.size, fr);
                        else if(it->first == Filter::FC && got_output) fwrite(packet_out.data, 1, packet_out.size, fc);
                        else if(it->first == Filter::BL && got_output) fwrite(packet_out.data, 1, packet_out.size, bl);
                        else if(it->first == Filter::BR && got_output) fwrite(packet_out.data, 1, packet_out.size, br);

                        av_free_packet(&packet_out);

                        //std::cout << "FR";
                        av_frame_unref(filt_frame);
                        //av_frame_unref(r_frame);
                        i++;
                    }
                    av_frame_unref(filt_frame);
                }
            }
            if(packet.size <= 0) av_free_packet(&packet0);
        } else {
            av_free_packet(&packet0);
        }
    }

    //for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second;

    fclose(fl);
    fclose(fc);
    fclose(fr);
    fclose(bl);
    fclose(br);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);
    delete filter;
    delete fmt;
}

int main(int argc, char *argv[]) {
    std::string videoFile = std::string(argv[1]);
    std::string sofaFile = std::string(argv[2]);

    clock_t begin = clock();
    Format *format = new Format(videoFile);
    Filter *filter = new Filter(format);
    clock_t end = clock();

    std::cout << "Filter initialization: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;

    begin = clock();
    process_filter_graph(format, filter, sofaFile);
    end = clock();

    std::cout << "Processing Time: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;
    return 0;
}
<commit_msg>Revert src/main.cpp back to Conor's version.<commit_after>#include <iostream>
#include "input/filter.h"
#include "input/format.h"
#include "encoder/encoder.h"
#include "sjoin/sjoin.h"
#include "virtualizer/virtualizer.h"
#include <ctime>
#include <stdio.h>

int process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {
    FILE *f;
    const char *filename = "FL.aac";

    AVPacket packet, packet0;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;
    complete_sofa sofa_;

    AVPacket packet_out;
    int got_output;

    Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,
            fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);

    SJoin  *sjoin  = new SJoin(encoder);

    f = fopen(filename, "wb");
    if(!f) {
        std::cout << "Error opening file" << std::endl;
    }

    int ret = 0;

    /* Read all of the packets */
    packet0.data = NULL;
    packet.data = NULL;
    while(1) {

        if(!packet0.data) {
            ret = av_read_frame(fmt->format_ctx, &packet);
            if(ret < 0) break;
            packet0 = packet;
        }

        if(packet.stream_index == fmt->audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);

            if(ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }

            packet.size -= ret;
            packet.data += ret;

            if(got_frame) {

                /* push audio from decoded frame through filter graph */
                if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                    break;
                }

                while(ret >= 0) {
                    // This is where you will work with each processed frame.

                    int i;

                    i = 0;
                    for (auto it = filter->abuffersink_ctx_map.begin();
                            it != filter->abuffersink_ctx_map.end(); it++) {

                        ret = av_buffersink_get_frame(it->second, filt_frame);
                        if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;

                        int sample_count = filt_frame->nb_samples;
                        int sample_rate = filt_frame->sample_rate;

                        if (c2v_.count(it->first) == 0) {
                            float x;
                            float y;
                            float z;
                            Filter::get_coords(it->first, &x, &y, &z);

                            if (sofa_.hrtf == NULL) {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                                sofa_ = virt->get_hrtf();
                            }
                            else {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                            }
                        }

                        float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        float ** float_results = c2v_[it->first]->process(samples, sample_count);

                        uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        delete[] float_results[0];
                        delete[] float_results[1];
                        delete[] float_results;
                        delete[] samples;

                        AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,
                                result_l);

                       if(it->first == 0) {
                           //std::cout << l_frame->nb_samples << std::endl;
                           //std::cout << l_frame->format << std::endl;
                           // This will move once virtualizaiton works
                        av_init_packet(&packet_out);
                        packet_out.data = NULL;
                        packet_out.size = 0;

                        ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);
                        if(ret < 0) exit(1);
                        if(got_output) {
                          fwrite(packet_out.data, 1, packet_out.size, f);
                          av_free_packet(&packet_out);
                        }
                       }

                        //AVFrame *r_frame = encoder->fill_new_frame(result_r, 2);

                        /*
                        if(av_buffersrc_add_frame_flags(sjoin->right_abuffers_ctx[i], r_frame, 0) < 0) {
                            av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                            break;
                        }
                        */
                        // TODO: do something with the result

                        //std::cout << "FR";
                        av_frame_unref(filt_frame);
                        //av_frame_unref(r_frame);
                        i++;
                    }
                    av_frame_unref(filt_frame);
                }
            }
            if(packet.size <= 0) av_free_packet(&packet0);
        } else {
            av_free_packet(&packet0);
        }
    }
    fclose(f);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);
    delete filter;
    delete fmt;
}

int main(int argc, char *argv[]) {
    std::string videoFile = std::string(argv[1]);
    std::string sofaFile = std::string(argv[2]);

    clock_t begin = clock();
    Format *format = new Format(videoFile);
    Filter *filter = new Filter(format);
    clock_t end = clock();

    std::cout << "Filter initialization: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;

    begin = clock();
    process_filter_graph(format, filter, sofaFile);
    end = clock();

    std::cout << "Processing Time: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>

#include <thread>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include "engine/terrain.hpp"
#include "engine/unit.hpp"
#include "engine/engine.hpp"

#include "gui/cursor.hpp"
#include "gui/guihandler.hpp"
#include "gui/splashscreen.hpp"
#include "gui/imagemanager.hpp"
#include "gui/texturemanager.hpp"

#include "config/tilesetprocessor.hpp"

int main(int argc, char const *argv[])
{
	// Create and show splash
	//qrw::SplashScreen* splash = new qrw::SplashScreen("./res/img/splash.png");
	//std::thread splashthread(&qrw::SplashScreen::show, splash);

	// Preload image resources.
	qrw::ImageManager* imgmgr = qrw::ImageManager::getInstance();
	imgmgr->loadImage("p1swordman", "./res/img/units/p1swordman.png");
	imgmgr->loadImage("p1archer", "./res/img/units/p1archer.png");
	imgmgr->loadImage("p1spearman", "./res/img/units/p1spearman.png");
	imgmgr->loadImage("p2swordman", "./res/img/units/p2swordman.png");
	imgmgr->loadImage("p2archer", "./res/img/units/p2archer.png");
	imgmgr->loadImage("p2spearman", "./res/img/units/p2spearman.png");
	imgmgr->loadImage("plainsquare", "./res/img/plainsquare.png");
	// Preload texture resources.
	qrw::TextureManager* texturemanager = qrw::TextureManager::getInstance();
	qrw::TilesetProcessor tilesetprocessor;
	tilesetprocessor.loadTileset("./res/defaulttileset.xml");

	texturemanager->loadTexture("nextbutton", "./res/img/gui/nextbutton.png");
	texturemanager->loadTexture("nextbutton_hover", "./res/img/gui/nextbutton_hover.png");
	texturemanager->loadTexture("nextbutton_active", "./res/img/gui/nextbutton_active.png");
	texturemanager->loadTexture("health", "./res/img/gui/health.png");
	texturemanager->loadTexture("attack", "./res/img/gui/attack.png");
	texturemanager->loadTexture("defense", "./res/img/gui/defense.png");
	texturemanager->loadTexture("movement", "./res/img/gui/movement.png");
	texturemanager->loadTexture("startbutton", "./res/img/gui/startbutton.png");

	//splash->setCloseable(true);
	//splashthread.join();
	//delete splash;

	sf::Vector2f windowsize(800, 600);
	qrw::Engine engine;
	engine.init(10, 4);

// Setup random board for test dings
qrw::Board* board = engine.getBoard();
qrw::Terrain* terrain1 = new qrw::Terrain(qrw::ET_WOOD, 1, 2);
board->getSquare(0, 0)->setTerrain(terrain1);
qrw::Terrain* terrain2 = new qrw::Terrain(qrw::ET_HILL, 3, -1);
board->getSquare(1, 2)->setTerrain(terrain2);
qrw::Terrain* terrain3 = new qrw::Terrain(qrw::ET_WALL, 2, 2);
board->getSquare(5, 1)->setTerrain(terrain3);

	sf::RenderWindow renderwindow(sf::VideoMode(windowsize.x, windowsize.y), "Quad-Ruled War", sf::Style::Default);
	qrw::GuiHandler guihandler(&engine, &renderwindow);
	sf::View camera(sf::FloatRect(0.0f, 0.0f, windowsize.x, windowsize.y));
	renderwindow.setView(camera);

	sf::RectangleShape rect(sf::Vector2f(10.0f, 10.0f));
	rect.setFillColor(sf::Color::Green);

	sf::Clock clock;
	float elapsedtime;

	while(!guihandler.getQuit())
	{
		elapsedtime = clock.restart().asSeconds();
		// Event handling
		sf::Event event;
		while(renderwindow.pollEvent(event))
			guihandler.HandleEvent(event);

		// Rendering
		renderwindow.clear(sf::Color::Black);
		renderwindow.draw(rect);

		guihandler.Update(elapsedtime);
		guihandler.display(renderwindow);

		renderwindow.display();
	}

	return 0;
}
<commit_msg>Now using Settings to initialize game in main.cpp.<commit_after>#include <stdio.h>

#include <thread>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include "engine/terrain.hpp"
#include "engine/unit.hpp"
#include "engine/engine.hpp"

#include "gui/cursor.hpp"
#include "gui/guihandler.hpp"
#include "gui/splashscreen.hpp"
#include "gui/imagemanager.hpp"
#include "gui/texturemanager.hpp"

#include "config/tilesetprocessor.hpp"
#include "config/settings.hpp"

int main(int argc, char const *argv[])
{
	qrw::Settings* settings = qrw::Settings::getInstance();
	settings->loadFromFile("res/conf/settings.xml");

	// Create and show splash
	//qrw::SplashScreen* splash = new qrw::SplashScreen("./res/img/splash.png");
	//std::thread splashthread(&qrw::SplashScreen::show, splash);

	// Preload image resources.
	qrw::ImageManager* imgmgr = qrw::ImageManager::getInstance();
	imgmgr->loadImage("p1swordman", "./res/img/units/p1swordman.png");
	imgmgr->loadImage("p1archer", "./res/img/units/p1archer.png");
	imgmgr->loadImage("p1spearman", "./res/img/units/p1spearman.png");
	imgmgr->loadImage("p2swordman", "./res/img/units/p2swordman.png");
	imgmgr->loadImage("p2archer", "./res/img/units/p2archer.png");
	imgmgr->loadImage("p2spearman", "./res/img/units/p2spearman.png");
	imgmgr->loadImage("plainsquare", "./res/img/plainsquare.png");
	// Preload texture resources.
	qrw::TextureManager* texturemanager = qrw::TextureManager::getInstance();
	qrw::TilesetProcessor tilesetprocessor;
	tilesetprocessor.loadTileset(settings->getTilesetPath());

	texturemanager->loadTexture("nextbutton", "./res/img/gui/nextbutton.png");
	texturemanager->loadTexture("nextbutton_hover", "./res/img/gui/nextbutton_hover.png");
	texturemanager->loadTexture("nextbutton_active", "./res/img/gui/nextbutton_active.png");
	texturemanager->loadTexture("health", "./res/img/gui/health.png");
	texturemanager->loadTexture("attack", "./res/img/gui/attack.png");
	texturemanager->loadTexture("defense", "./res/img/gui/defense.png");
	texturemanager->loadTexture("movement", "./res/img/gui/movement.png");
	texturemanager->loadTexture("startbutton", "./res/img/gui/startbutton.png");

	//splash->setCloseable(true);
	//splashthread.join();
	//delete splash;

	qrw::Engine engine;
	engine.init(10, 4);

// Setup random board for test dings
qrw::Board* board = engine.getBoard();
qrw::Terrain* terrain1 = new qrw::Terrain(qrw::ET_WOOD, 1, 2);
board->getSquare(0, 0)->setTerrain(terrain1);
qrw::Terrain* terrain2 = new qrw::Terrain(qrw::ET_HILL, 3, -1);
board->getSquare(1, 2)->setTerrain(terrain2);
qrw::Terrain* terrain3 = new qrw::Terrain(qrw::ET_WALL, 2, 2);
board->getSquare(5, 1)->setTerrain(terrain3);

	sf::RenderWindow renderwindow(
		sf::VideoMode(settings->getResolutionX(), settings->getResolutionY()),
		"Quad-Ruled War",
		sf::Style::Default
	);

	qrw::GuiHandler guihandler(&engine, &renderwindow);
	sf::View camera(sf::FloatRect(0.0f, 0.0f, settings->getResolutionX(), settings->getResolutionY()));
	renderwindow.setView(camera);

	sf::RectangleShape rect(sf::Vector2f(10.0f, 10.0f));
	rect.setFillColor(sf::Color::Green);

	sf::Clock clock;
	float elapsedtime;

	while(!guihandler.getQuit())
	{
		elapsedtime = clock.restart().asSeconds();
		// Event handling
		sf::Event event;
		while(renderwindow.pollEvent(event))
			guihandler.HandleEvent(event);

		// Rendering
		renderwindow.clear(sf::Color::Black);
		renderwindow.draw(rect);

		guihandler.Update(elapsedtime);
		guihandler.display(renderwindow);

		renderwindow.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include "PhysSystem.h"
#include <sstream>
#include <iomanip>

//50 125 218
//50 50 50

sf::Vector2f ConvertVector(Vector2f vec)
{
  return sf::Vector2f(vec.x, vec.y);
}

void RenderBox(std::vector<sf::Vertex>& vertices, Coords2f coords, Vector2f size, sf::Color color)
{
  Vector2f localPoints[4];
  localPoints[0] = Vector2f(-size.x, -size.y);
  localPoints[1] = Vector2f(size.x, -size.y);
  localPoints[2] = Vector2f(size.x, size.y);
  localPoints[3] = Vector2f(-size.x, size.y);

  for (int vertexNumber = 0; vertexNumber < 4; vertexNumber++)
  {
    sf::Vertex v;
    v.color = color;
    v.position = ConvertVector(coords.GetPointGlobalPos(localPoints[vertexNumber]));
    vertices.push_back(v);
  }
}

float random(float min, float max)
{
  return min + (max - min) * (float(rand()) / float(RAND_MAX));
}

const struct { PhysSystem::SolveMode mode; const char* name; } kModes[] =
{
    { PhysSystem::Solve_Baseline, "Baseline" },
    { PhysSystem::Solve_AoS, "AoS" },
    { PhysSystem::Solve_SoA_Scalar, "SoA Scalar" },
    { PhysSystem::Solve_SoA_SSE2, "SoA SSE2" },

  #ifdef __AVX2__
    { PhysSystem::Solve_SoA_AVX2, "SoA AVX2" },
  #endif

    { PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar" },
    { PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2" },

  #ifdef __AVX2__
    { PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2" },
  #endif
};

int main(int argc, char** argv)
{
  int windowWidth = 1024, windowHeight = 768;

  PhysSystem physSystem;
  RigidBody *groundBody = physSystem.AddBody(Coords2f(Vector2f(windowWidth * 0.5f, windowHeight * 0.95f), 0.0f), Vector2f(windowWidth * 10.45f, 10.0f));
  groundBody->invInertia = 0.0f;
  groundBody->invMass = 0.0f;

  int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1;

  const float gravity = 200.0f;
  const float integrationTime = 2e-2f;

  float physicsTime = 0.0f;

  RigidBody *draggedBody = physSystem.AddBody(
    Coords2f(Vector2f(windowWidth * 0.1f, windowHeight * 0.7f), 0.0f), Vector2f(30.0f, 30.0f));

  for (int bodyIndex = 0; bodyIndex < 1000; bodyIndex++)
  {
    RigidBody *testBody = physSystem.AddBody(
      Coords2f(Vector2f(windowWidth * 0.5f, windowHeight * 0.6f) + Vector2f(random(-250.0f, 250.0f), random(-650.0f, 250.0f)), 0.0f), Vector2f(15.0f, 15.0f));
    //testBody->invInertia = 0;
    testBody->velocity = Vector2f(10.0f, 0.0f);
  }

  if (argc > 1 && strcmp(argv[1], "profile") == 0)
  {
    for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode)
    {
      PhysSystem testSystem;

      for (int i = 0; i < physSystem.GetBodiesCount(); ++i)
      {
        RigidBody* body = physSystem.GetBody(i);

        RigidBody* testBody = testSystem.AddBody(body->coords, body->geom.size);
        testBody->velocity = body->velocity;
      }

      double solveTime = 0;

      for (int i = 0; i < 10; ++i)
      {
        testSystem.Update(1.f / 60.f, kModes[mode].mode);

        solveTime += testSystem.solveTime;
      }

      printf("%s: %.2f ms\n", kModes[mode].name, solveTime * 1000.f);
    }

    return 0;
  }

  sf::Font font;
  font.loadFromFile("DroidSansMono.ttf");

  sf::RenderWindow *window = new sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), "This is awesome!");

  sf::Clock clock;

  float prevUpdateTime = 0.0f;

  bool paused = 0;

  std::vector<sf::Vertex> vertices;

  while (window->isOpen())
  {
    sf::Event event;
    while (window->pollEvent(event))
    {
      if (event.type == sf::Event::Closed)
        window->close();
      else if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::M)
        currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0]));
    }
    Vector2f mousePos = Vector2f(sf::Mouse::getPosition(*window).x, sf::Mouse::getPosition(*window).y);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
    {
      paused = 0;
    }
    window->clear(sf::Color(50, 50, 50, 255));
    vertices.clear();
    if (clock.getElapsedTime().asSeconds() > prevUpdateTime + integrationTime)
    {
      sf::Clock physicsClock;
      prevUpdateTime += integrationTime;
      if (!paused)
      {

        for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
        {
          physSystem.GetBody(bodyIndex)->acceleration = Vector2f(0.0f, 0.0f);
          physSystem.GetBody(bodyIndex)->angularAcceleration = 0.0f;
        }
        for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
        {
          RigidBody *body = physSystem.GetBody(bodyIndex);
          if (body->invMass > 0.0f)
          {
            physSystem.GetBody(bodyIndex)->acceleration += Vector2f(0.0f, gravity);
          }
        }
        RigidBody *draggedBody = physSystem.GetBody(1);
        Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f;
        draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0;

        physSystem.Update(integrationTime, kModes[currentMode].mode);
        physicsTime = physicsClock.getElapsedTime().asSeconds();
      }
    }

    for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
    {
      RigidBody *body = physSystem.GetBody(bodyIndex);
      Coords2f bodyCoords = body->coords;
      Vector2f size = body->geom.size;

      float colorMult = float(bodyIndex) / float(physSystem.GetBodiesCount()) * 0.5f + 0.5f;
      sf::Color color = sf::Color(char(50 * colorMult), char(125 * colorMult), char(218 * colorMult));

      if (bodyIndex == 1) //dragged body
      {
        color = sf::Color(242, 236, 164, 255);
      }

      RenderBox(vertices, bodyCoords, size, color);
    }

    bool pickingCollision = 0;
    /*if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
      pickingCollision = true;
    }*/
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::C))
    for (size_t manifoldIndex = 0; manifoldIndex < physSystem.GetCollider()->manifolds.size(); ++manifoldIndex)
    {
      Manifold& man = physSystem.GetCollider()->manifolds[manifoldIndex];

      for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++)
      {
        Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f);

        coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1;

        float redMult = 1.0f;
        if (man.collisions[collisionNumber].isNewlyCreated)
          redMult = 0.5f;

        sf::Color color1(100, char(100 * redMult), char(100 * redMult), 100);
        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), color1);

        coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2;
        sf::Color color2(150, char(150 * redMult), char(150 * redMult), 100);
        //if (pickingCollision && (coords.pos - mousePos).SquareLen() < 5.0f * 5.0f)
        //{
        //  color2 = sf::Color(255, 0, 0, 255);
        //}
        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), color2);
      }
    }

    if (vertices.size() > 0)
      window->draw(&vertices[0], vertices.size(), sf::Quads);

    std::stringstream debugTextStream;
    debugTextStream << "Bodies count: " << physSystem.GetBodiesCount() << " contacts count: " << physSystem.GetJointsCount();
    sf::Text text(debugTextStream.str().c_str(), font, 20);
    text.setPosition(sf::Vector2f(10.0f, 30.0f));
    window->draw(text);

    std::stringstream debugTextStream2;
    debugTextStream2 << std::fixed;
    debugTextStream2.precision(2);
    debugTextStream2 <<
      "Mode: " << kModes[currentMode].name << "; " <<
      "Physics time: " << std::setw(5) << physicsTime * 1000.0f <<
      "ms (c: " << std::setw(5) << physSystem.collisionTime * 1000.0f <<
      "ms, m: " << std::setw(5) << physSystem.mergeTime * 1000.0f <<
      "ms, s: " << std::setw(5) << physSystem.solveTime * 1000.0f << "ms)";
    sf::Text text2(debugTextStream2.str().c_str(), font, 20);
    text2.setPosition(sf::Vector2f(10.0f, 50.0f));
    window->draw(text2);

    window->display();
  }
}<commit_msg>Add string.h include<commit_after>#include <SFML/Graphics.hpp>
#include "PhysSystem.h"
#include <sstream>
#include <iomanip>
#include <string.h>

sf::Vector2f ConvertVector(Vector2f vec)
{
  return sf::Vector2f(vec.x, vec.y);
}

void RenderBox(std::vector<sf::Vertex>& vertices, Coords2f coords, Vector2f size, sf::Color color)
{
  Vector2f localPoints[4];
  localPoints[0] = Vector2f(-size.x, -size.y);
  localPoints[1] = Vector2f(size.x, -size.y);
  localPoints[2] = Vector2f(size.x, size.y);
  localPoints[3] = Vector2f(-size.x, size.y);

  for (int vertexNumber = 0; vertexNumber < 4; vertexNumber++)
  {
    sf::Vertex v;
    v.color = color;
    v.position = ConvertVector(coords.GetPointGlobalPos(localPoints[vertexNumber]));
    vertices.push_back(v);
  }
}

float random(float min, float max)
{
  return min + (max - min) * (float(rand()) / float(RAND_MAX));
}

const struct { PhysSystem::SolveMode mode; const char* name; } kModes[] =
{
    { PhysSystem::Solve_Baseline, "Baseline" },
    { PhysSystem::Solve_AoS, "AoS" },
    { PhysSystem::Solve_SoA_Scalar, "SoA Scalar" },
    { PhysSystem::Solve_SoA_SSE2, "SoA SSE2" },

  #ifdef __AVX2__
    { PhysSystem::Solve_SoA_AVX2, "SoA AVX2" },
  #endif

    { PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar" },
    { PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2" },

  #ifdef __AVX2__
    { PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2" },
  #endif
};

int main(int argc, char** argv)
{
  int windowWidth = 1024, windowHeight = 768;

  PhysSystem physSystem;
  RigidBody *groundBody = physSystem.AddBody(Coords2f(Vector2f(windowWidth * 0.5f, windowHeight * 0.95f), 0.0f), Vector2f(windowWidth * 10.45f, 10.0f));
  groundBody->invInertia = 0.0f;
  groundBody->invMass = 0.0f;

  int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1;

  const float gravity = 200.0f;
  const float integrationTime = 2e-2f;

  float physicsTime = 0.0f;

  RigidBody *draggedBody = physSystem.AddBody(
    Coords2f(Vector2f(windowWidth * 0.1f, windowHeight * 0.7f), 0.0f), Vector2f(30.0f, 30.0f));

  for (int bodyIndex = 0; bodyIndex < 1000; bodyIndex++)
  {
    RigidBody *testBody = physSystem.AddBody(
      Coords2f(Vector2f(windowWidth * 0.5f, windowHeight * 0.6f) + Vector2f(random(-250.0f, 250.0f), random(-650.0f, 250.0f)), 0.0f), Vector2f(15.0f, 15.0f));
    //testBody->invInertia = 0;
    testBody->velocity = Vector2f(10.0f, 0.0f);
  }

  if (argc > 1 && strcmp(argv[1], "profile") == 0)
  {
    for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode)
    {
      PhysSystem testSystem;

      for (int i = 0; i < physSystem.GetBodiesCount(); ++i)
      {
        RigidBody* body = physSystem.GetBody(i);

        RigidBody* testBody = testSystem.AddBody(body->coords, body->geom.size);
        testBody->velocity = body->velocity;
      }

      double solveTime = 0;

      for (int i = 0; i < 10; ++i)
      {
        testSystem.Update(1.f / 60.f, kModes[mode].mode);

        solveTime += testSystem.solveTime;
      }

      printf("%s: %.2f ms\n", kModes[mode].name, solveTime * 1000.f);
    }

    return 0;
  }

  sf::Font font;
  font.loadFromFile("DroidSansMono.ttf");

  sf::RenderWindow *window = new sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), "This is awesome!");

  sf::Clock clock;

  float prevUpdateTime = 0.0f;

  bool paused = 0;

  std::vector<sf::Vertex> vertices;

  while (window->isOpen())
  {
    sf::Event event;
    while (window->pollEvent(event))
    {
      if (event.type == sf::Event::Closed)
        window->close();
      else if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::M)
        currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0]));
    }
    Vector2f mousePos = Vector2f(sf::Mouse::getPosition(*window).x, sf::Mouse::getPosition(*window).y);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
    {
      paused = 0;
    }
    window->clear(sf::Color(50, 50, 50, 255));
    vertices.clear();
    if (clock.getElapsedTime().asSeconds() > prevUpdateTime + integrationTime)
    {
      sf::Clock physicsClock;
      prevUpdateTime += integrationTime;
      if (!paused)
      {

        for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
        {
          physSystem.GetBody(bodyIndex)->acceleration = Vector2f(0.0f, 0.0f);
          physSystem.GetBody(bodyIndex)->angularAcceleration = 0.0f;
        }
        for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
        {
          RigidBody *body = physSystem.GetBody(bodyIndex);
          if (body->invMass > 0.0f)
          {
            physSystem.GetBody(bodyIndex)->acceleration += Vector2f(0.0f, gravity);
          }
        }
        RigidBody *draggedBody = physSystem.GetBody(1);
        Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f;
        draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0;

        physSystem.Update(integrationTime, kModes[currentMode].mode);
        physicsTime = physicsClock.getElapsedTime().asSeconds();
      }
    }

    for (size_t bodyIndex = 0; bodyIndex < physSystem.GetBodiesCount(); bodyIndex++)
    {
      RigidBody *body = physSystem.GetBody(bodyIndex);
      Coords2f bodyCoords = body->coords;
      Vector2f size = body->geom.size;

      float colorMult = float(bodyIndex) / float(physSystem.GetBodiesCount()) * 0.5f + 0.5f;
      sf::Color color = sf::Color(char(50 * colorMult), char(125 * colorMult), char(218 * colorMult));

      if (bodyIndex == 1) //dragged body
      {
        color = sf::Color(242, 236, 164, 255);
      }

      RenderBox(vertices, bodyCoords, size, color);
    }

    bool pickingCollision = 0;
    /*if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
      pickingCollision = true;
    }*/
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::C))
    for (size_t manifoldIndex = 0; manifoldIndex < physSystem.GetCollider()->manifolds.size(); ++manifoldIndex)
    {
      Manifold& man = physSystem.GetCollider()->manifolds[manifoldIndex];

      for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++)
      {
        Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f);

        coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1;

        float redMult = 1.0f;
        if (man.collisions[collisionNumber].isNewlyCreated)
          redMult = 0.5f;

        sf::Color color1(100, char(100 * redMult), char(100 * redMult), 100);
        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), color1);

        coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2;
        sf::Color color2(150, char(150 * redMult), char(150 * redMult), 100);
        //if (pickingCollision && (coords.pos - mousePos).SquareLen() < 5.0f * 5.0f)
        //{
        //  color2 = sf::Color(255, 0, 0, 255);
        //}
        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), color2);
      }
    }

    if (vertices.size() > 0)
      window->draw(&vertices[0], vertices.size(), sf::Quads);

    std::stringstream debugTextStream;
    debugTextStream << "Bodies count: " << physSystem.GetBodiesCount() << " contacts count: " << physSystem.GetJointsCount();
    sf::Text text(debugTextStream.str().c_str(), font, 20);
    text.setPosition(sf::Vector2f(10.0f, 30.0f));
    window->draw(text);

    std::stringstream debugTextStream2;
    debugTextStream2 << std::fixed;
    debugTextStream2.precision(2);
    debugTextStream2 <<
      "Mode: " << kModes[currentMode].name << "; " <<
      "Physics time: " << std::setw(5) << physicsTime * 1000.0f <<
      "ms (c: " << std::setw(5) << physSystem.collisionTime * 1000.0f <<
      "ms, m: " << std::setw(5) << physSystem.mergeTime * 1000.0f <<
      "ms, s: " << std::setw(5) << physSystem.solveTime * 1000.0f << "ms)";
    sf::Text text2(debugTextStream2.str().c_str(), font, 20);
    text2.setPosition(sf::Vector2f(10.0f, 50.0f));
    window->draw(text2);

    window->display();
  }
}<|endoftext|>


<commit_before>#include "consts.h"
#include "utils.h"
#include "circuits/circuit.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include "matrix/newtonraphson.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
#include <math.h>

using namespace std;

/* The program starts here */
int main(int argc, char **argv){
    printIntro();

    int rc=0;
    ifstream netlistFile;
    Circuit circuit;

    // Reads netlist file
    string netlistFileName;
    rc = openNetlistFile(argc, argv, netlistFileName, netlistFile);
    if (rc == EXIT_FAILURE)
        exitPolitely(EXIT_FAILURE);
    // Prepares solutions file
    string outputFileName;
    outputFileName = netlistFileName.substr(0, netlistFileName.find(".")).append("_mnapoly.tab");
    ofstream solutionsFile(outputFileName.c_str(), ofstream::out);

    // Parses netlist file (constructs Circuit)
    cout << "Reading netlist:" << endl;
    circuit = Circuit(netlistFile);
    netlistFile.close();

    // Write solutions file header
    circuit.writeSolutionsHeader(solutionsFile);

    #ifdef DEBUG
    cout << "Internal variables:" << endl;
    circuit.printVariables();

    cout << "Summary:" << endl;
    circuit.printSummary();
    #endif

    // Bias Analysis
    double t=0;
    double solution[MAX_NODES+1];
    copySolution(circuit.getNumVariables(), ZERO_SOLUTION, solution);
    runNewtonRaphson(circuit, solution, t);
    circuit.appendSolutionToFile(solutionsFile, solution);

    // Transient Analysis
    double step = circuit.getStep();
    int numInternalSteps = circuit.getNumInternalSteps();
    double realStep = step/(double)numInternalSteps;
    double finalTime = circuit.getFinalTime();
    double lastSolution[MAX_NODES+1];
    do {
        t += step;
        copySolution(circuit.getNumVariables(),
                     solution,
                     lastSolution);
        t += realStep;
        runNewtonRaphson(circuit, solution, t, lastSolution);
        if (fmod(t, realStep) < TOLG)
            circuit.appendSolutionToFile(solutionsFile, solution, t);
    } while (t<finalTime);

    //Closing The File
    cout << endl << "Created: " << outputFileName << endl;
    solutionsFile.close();

    exitPolitely(EXIT_SUCCESS);
}
<commit_msg>Fixes bad commit cherrypicking for internal step<commit_after>#include "consts.h"
#include "utils.h"
#include "circuits/circuit.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include "matrix/newtonraphson.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
#include <math.h>

using namespace std;

/* The program starts here */
int main(int argc, char **argv){
    printIntro();

    int rc=0;
    ifstream netlistFile;
    Circuit circuit;

    // Reads netlist file
    string netlistFileName;
    rc = openNetlistFile(argc, argv, netlistFileName, netlistFile);
    if (rc == EXIT_FAILURE)
        exitPolitely(EXIT_FAILURE);
    // Prepares solutions file
    string outputFileName;
    outputFileName = netlistFileName.substr(0, netlistFileName.find(".")).append("_mnapoly.tab");
    ofstream solutionsFile(outputFileName.c_str(), ofstream::out);

    // Parses netlist file (constructs Circuit)
    cout << "Reading netlist:" << endl;
    circuit = Circuit(netlistFile);
    netlistFile.close();

    // Write solutions file header
    circuit.writeSolutionsHeader(solutionsFile);

    #ifdef DEBUG
    cout << "Internal variables:" << endl;
    circuit.printVariables();

    cout << "Summary:" << endl;
    circuit.printSummary();
    #endif

    // Bias Analysis
    double t=0;
    double solution[MAX_NODES+1];
    copySolution(circuit.getNumVariables(), ZERO_SOLUTION, solution);
    runNewtonRaphson(circuit, solution, t);
    circuit.appendSolutionToFile(solutionsFile, solution);

    // Transient Analysis
    double step = circuit.getStep();
    int numInternalSteps = circuit.getNumInternalSteps();
    double realStep = step/(double)numInternalSteps;
    double finalTime = circuit.getFinalTime();
    double lastSolution[MAX_NODES+1];
    do {
        t += realStep;
        copySolution(circuit.getNumVariables(),
                     solution,
                     lastSolution);
        runNewtonRaphson(circuit, solution, t, lastSolution);
        if (fmod(t, realStep) < TOLG)
            circuit.appendSolutionToFile(solutionsFile, solution, t);
    } while (t<finalTime);

    //Closing The File
    cout << endl << "Created: " << outputFileName << endl;
    solutionsFile.close();

    exitPolitely(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include "../include/PSATsolver.hpp"

using namespace std;
using namespace arma;

int main(int argc, char** argv)
{
    bool v = false;

    if (argc < 2)
    {
        std::cout << "I need a input file " << "\n";
        return -1;
    }

    //if (argc == 3 && argv[2][1] == 'v' && argv[2][0] == '-')
      //  v = true;

    int** m;
    int**& M = m;
    vector<double> pi;
    double time;
    int n;

    for(int i = 0; i < argc; i++)
    {
        n = PSATsolver::solve(M, pi, &time, argv[i], v);
        cout << time << "\n";
    }

    return 1;
}
<commit_msg>just a test<commit_after>#include "../include/PSATsolver.hpp"

using namespace std;
using namespace arma;

int main(int argc, char** argv)
{
    bool v = false;

    if (argc < 2)
    {
        std::cout << "I need a input file " << "\n";
        return -1;
    }

    //if (argc == 3 && argv[2][1] == 'v' && argv[2][0] == '-')
      //  v = true;

    int** m;
    int**& M = m;
    vector<double> pi;
    double time;
    int n;

    for(int i = 1; i < argc; i++)
    {
        n = PSATsolver::solve(M, pi, &time, argv[i], v);
        cout << time << "\n";
    }

    return 1;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ios>

#include "hext/parser.h"
#include "hext/matcher.h"
#include "hext/program-options.h"

int main(int argc, const char ** argv)
{
  std::ios_base::sync_with_stdio(false);

  hext::program_options po(argc, argv);

  if( !po.validate_or_print_error(std::cerr) )
    return EXIT_FAILURE;

  if( argc < 2 || po.contains("help") )
  {
    po.print(argv[0], std::cout);
    return EXIT_SUCCESS;
  }

  try
  {
    auto rules = hext::parser::parse_file(po.get("hext-file"));

    if( po.contains("print") )
    {
      for(const auto& r : rules)
        r.print();
      return EXIT_SUCCESS;
    }

    if( po.contains("lint") )
      return EXIT_SUCCESS;

    hext::matcher m(po.get("html-file"));

    for(const auto& r : rules)
    {
      std::fstream g(
        "auto.graph.dot",
        std::fstream::out|std::fstream::trunc
      );
      std::fstream gf(
        "auto.graph.filtered.dot",
        std::fstream::out|std::fstream::trunc
      );

      std::unique_ptr<hext::match_tree> mt = m.match(r);
      assert(mt != nullptr);

      if( po.contains("mt-graph") )
      {
        mt->print_dot(g); // debug
        mt->filter();
        mt->print_dot(gf); // debug
        mt->print_dot();
      }
      else if( po.contains("unfiltered-mt-graph") )
      {
        mt->print_dot();
      }
      else
      {
        mt->filter();
        mt->print_json();
      }
    }
  }
  catch( std::ios_base::failure& e )
  {
    std::cerr << e.what() << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<commit_msg>only open graph files if we want to write data<commit_after>#include <cassert>
#include <cstdlib>
#include <iostream>
#include <ios>

#include "hext/parser.h"
#include "hext/matcher.h"
#include "hext/program-options.h"

int main(int argc, const char ** argv)
{
  std::ios_base::sync_with_stdio(false);

  hext::program_options po(argc, argv);

  if( !po.validate_or_print_error(std::cerr) )
    return EXIT_FAILURE;

  if( argc < 2 || po.contains("help") )
  {
    po.print(argv[0], std::cout);
    return EXIT_SUCCESS;
  }

  try
  {
    auto rules = hext::parser::parse_file(po.get("hext-file"));

    if( po.contains("print") )
    {
      for(const auto& r : rules)
        r.print();
      return EXIT_SUCCESS;
    }

    if( po.contains("lint") )
      return EXIT_SUCCESS;

    hext::matcher m(po.get("html-file"));

    for(const auto& r : rules)
    {
      std::unique_ptr<hext::match_tree> mt = m.match(r);
      assert(mt != nullptr);

      if( po.contains("mt-graph") )
      {
        std::fstream g(
          "auto.graph.dot",
          std::fstream::out|std::fstream::trunc
        );
        std::fstream gf(
          "auto.graph.filtered.dot",
          std::fstream::out|std::fstream::trunc
        );

        mt->print_dot(g); // debug
        mt->filter();
        mt->print_dot(gf); // debug
        mt->print_dot();
      }
      else if( po.contains("unfiltered-mt-graph") )
      {
        mt->print_dot();
      }
      else
      {
        mt->filter();
        mt->print_json();
      }
    }
  }
  catch( std::ios_base::failure& e )
  {
    std::cerr << e.what() << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "consts.h"
#include "utils.h"
#include "phantom.h"
#include "crashdump.h"

#include <QApplication>
#include <QSslSocket>
#include <QWebSettings>

#include <stdio.h>

static int inner_main(int argc, char** argv)
{
    QApplication app(argc, argv);

    app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
    app.setApplicationName("PhantomJS");
    app.setOrganizationName("Ofi Labs");
    app.setOrganizationDomain("www.ofilabs.com");
    app.setApplicationVersion(PHANTOMJS_VERSION_STRING);

    // Registering an alternative Message Handler
    qInstallMessageHandler(Utils::messageHandler);

#if defined(Q_OS_LINUX)
    if (QSslSocket::supportsSsl()) {
        // Don't perform on-demand loading of root certificates on Linux
        QSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates());
    }
#endif

    // Get the Phantom singleton
    Phantom* phantom = Phantom::instance();

    // Start script execution
    if (phantom->execute()) {
        app.exec();
    }

    // End script execution: delete the phantom singleton and set
    // execution return value
    int retVal = phantom->returnValue();
    delete phantom;

#ifndef QT_NO_DEBUG
    // Clear all cached data before exiting, so it is not detected as
    // leaked.
    QWebSettings::clearMemoryCaches();
#endif

    return retVal;
}

int main(int argc, char** argv)
{
    try {
        init_crash_handler();
        return inner_main(argc, argv);

        // These last-ditch exception handlers write to the C stderr
        // because who knows what kind of state Qt is in.  And they avoid
        // using fprintf because _that_ might be in bad shape too.
        // (I would drop all the way down to write() but then I'd have to
        // write the code again for Windows.)
        //
        // print_crash_message includes a call to fflush(stderr).
    } catch (std::bad_alloc) {
        fputs("Memory exhausted.\n", stderr);
        fflush(stderr);
        return 1;

    } catch (std::exception& e) {
        fputs("Uncaught C++ exception: ", stderr);
        fputs(e.what(), stderr);
        putc('\n', stderr);
        print_crash_message();
        return 1;

    } catch (...) {
        fputs("Uncaught nonstandard exception.\n", stderr);
        print_crash_message();
        return 1;
    }
}
<commit_msg>[Linux] Override the default QPA platform plugin<commit_after>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "consts.h"
#include "utils.h"
#include "phantom.h"
#include "crashdump.h"

#include <QApplication>
#include <QSslSocket>
#include <QWebSettings>

#include <stdio.h>

static int inner_main(int argc, char** argv)
{
#ifdef Q_OS_LINUX
    // override default Qt platform plugin
    qputenv("QT_QPA_PLATFORM", "offscreen");
#endif

    QApplication app(argc, argv);

    app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
    app.setApplicationName("PhantomJS");
    app.setOrganizationName("Ofi Labs");
    app.setOrganizationDomain("www.ofilabs.com");
    app.setApplicationVersion(PHANTOMJS_VERSION_STRING);

    // Registering an alternative Message Handler
    qInstallMessageHandler(Utils::messageHandler);

#if defined(Q_OS_LINUX)
    if (QSslSocket::supportsSsl()) {
        // Don't perform on-demand loading of root certificates on Linux
        QSslSocket::addDefaultCaCertificates(QSslSocket::systemCaCertificates());
    }
#endif

    // Get the Phantom singleton
    Phantom* phantom = Phantom::instance();

    // Start script execution
    if (phantom->execute()) {
        app.exec();
    }

    // End script execution: delete the phantom singleton and set
    // execution return value
    int retVal = phantom->returnValue();
    delete phantom;

#ifndef QT_NO_DEBUG
    // Clear all cached data before exiting, so it is not detected as
    // leaked.
    QWebSettings::clearMemoryCaches();
#endif

    return retVal;
}

int main(int argc, char** argv)
{
    try {
        init_crash_handler();
        return inner_main(argc, argv);

        // These last-ditch exception handlers write to the C stderr
        // because who knows what kind of state Qt is in.  And they avoid
        // using fprintf because _that_ might be in bad shape too.
        // (I would drop all the way down to write() but then I'd have to
        // write the code again for Windows.)
        //
        // print_crash_message includes a call to fflush(stderr).
    } catch (std::bad_alloc) {
        fputs("Memory exhausted.\n", stderr);
        fflush(stderr);
        return 1;

    } catch (std::exception& e) {
        fputs("Uncaught C++ exception: ", stderr);
        fputs(e.what(), stderr);
        putc('\n', stderr);
        print_crash_message();
        return 1;

    } catch (...) {
        fputs("Uncaught nonstandard exception.\n", stderr);
        print_crash_message();
        return 1;
    }
}
<|endoftext|>