<commit_before>#ifndef SHORTCUT_SMOOTHING_HPP
#define SHORTCUT_SMOOTHING_HPP

#include <functional>
#include "arc_utilities/eigen_helpers.hpp"

namespace shortcut_smoothing
{
    EigenHelpers::VectorVector3d ShortcutSmooth(const EigenHelpers::VectorVector3d& input_vector, const size_t first_ind, const size_t second_ind, const double step_size, const std::function<bool(const Eigen::Vector3d&)>& collision_fn)
    {
        const size_t starting_ind = std::min(first_ind, second_ind);
        const size_t ending_ind = std::max(first_ind, second_ind);

        const Eigen::Vector3d& starting_point = input_vector[starting_ind];
        const Eigen::Vector3d& ending_point = input_vector[ending_ind];
        const Eigen::Vector3d delta = ending_point - starting_point;
        const Eigen::Vector3d delta_unit_vec = delta.normalized();

        const double total_dist = delta.norm();

        if (total_dist <= step_size)
        {
            return input_vector;
        }

        bool collision = false;
        for (double dist = step_size; !collision && dist < total_dist; dist += step_size)
        {
            const Eigen::Vector3d point_to_check = starting_point + dist * delta_unit_vec;
            collision = collision_fn(point_to_check);
        }

        if (!collision)
        {
            const size_t num_original_elements = ending_ind - starting_ind - 1;
            const size_t num_new_elements = (size_t)std::ceil(total_dist / step_size);

            EigenHelpers::VectorVector3d output_vector(input_vector.size() - num_original_elements + num_new_elements - 1);

            // Copy in the first unchanged elements of the vector
            std::copy(input_vector.begin(), input_vector.begin() + starting_ind + 1, output_vector.begin());

            // Assign the replaced elements
            for (size_t new_element_ind = 1; new_element_ind < num_new_elements; ++new_element_ind)
            {
                const double dist = (double)new_element_ind * step_size;
                output_vector[starting_ind + new_element_ind] = starting_point + dist * delta_unit_vec;
            }

            // Copy in the last unchanged elements of the vector
            std::copy(input_vector.begin() + ending_ind, input_vector.end(), output_vector.begin() + starting_ind + num_new_elements);

            return output_vector;

        }
        else
        {
            return input_vector;
        }
    }
}

#endif // SHORTCUT_SMOOTHING_HPP
<commit_msg>Added generic shortcut smoothing and path resampling code<commit_after>#include <functional>
#include <arc_utilities/arc_helpers.hpp>
#include <arc_utilities/eigen_helpers.hpp>

#ifndef SHORTCUT_SMOOTHING_HPP
#define SHORTCUT_SMOOTHING_HPP

namespace shortcut_smoothing
{
    EigenHelpers::VectorVector3d ShortcutSmooth(const EigenHelpers::VectorVector3d& input_vector, const size_t first_ind, const size_t second_ind, const double step_size, const std::function<bool(const Eigen::Vector3d&)>& collision_fn)
    {
        const size_t starting_ind = std::min(first_ind, second_ind);
        const size_t ending_ind = std::max(first_ind, second_ind);

        const Eigen::Vector3d& starting_point = input_vector[starting_ind];
        const Eigen::Vector3d& ending_point = input_vector[ending_ind];
        const Eigen::Vector3d delta = ending_point - starting_point;
        const Eigen::Vector3d delta_unit_vec = delta.normalized();

        const double total_dist = delta.norm();

        if (total_dist <= step_size)
        {
            return input_vector;
        }

        bool collision = false;
        for (double dist = step_size; !collision && dist < total_dist; dist += step_size)
        {
            const Eigen::Vector3d point_to_check = starting_point + dist * delta_unit_vec;
            collision = collision_fn(point_to_check);
        }

        if (!collision)
        {
            const size_t num_original_elements = ending_ind - starting_ind - 1;
            const size_t num_new_elements = (size_t)std::ceil(total_dist / step_size);

            EigenHelpers::VectorVector3d output_vector(input_vector.size() - num_original_elements + num_new_elements - 1);

            // Copy in the first unchanged elements of the vector
            std::copy(input_vector.begin(), input_vector.begin() + starting_ind + 1, output_vector.begin());

            // Assign the replaced elements
            for (size_t new_element_ind = 1; new_element_ind < num_new_elements; ++new_element_ind)
            {
                const double dist = (double)new_element_ind * step_size;
                output_vector[starting_ind + new_element_ind] = starting_point + dist * delta_unit_vec;
            }

            // Copy in the last unchanged elements of the vector
            std::copy(input_vector.begin() + ending_ind, input_vector.end(), output_vector.begin() + starting_ind + num_new_elements);

            return output_vector;

        }
        else
        {
            return input_vector;
        }
    }

    template<typename PRNG, typename Configuration, typename ConfigAlloc=std::allocator<Configuration>>
    std::vector<Configuration, ConfigAlloc> ShortcutSmoothPath(const std::vector<Configuration, ConfigAlloc>& path, const uint32_t max_iterations, const uint32_t max_failed_iterations, const double max_shortcut_fraction, const std::function<bool(const Configuration&, const Configuration&)>& edge_validity_check_fn, PRNG& prng)
    {
        std::vector<Configuration, ConfigAlloc> current_path = path;
        uint32_t num_iterations = 0;
        uint32_t failed_iterations = 0;
        while (num_iterations < max_iterations && failed_iterations < max_failed_iterations && current_path.size() > 2)
        {
            // Attempt a shortcut
            const int64_t base_index = std::uniform_int_distribution<size_t>(0, current_path.size() - 1)(prng);
            // Pick an offset fraction
            const double offset_fraction = std::uniform_real_distribution<double>(-max_shortcut_fraction, max_shortcut_fraction)(prng);
            // Compute the offset index
            const int64_t offset_index = base_index + (int64_t)((double)current_path.size() * offset_fraction); // Could be out of bounds
            const int64_t safe_offset_index = arc_helpers::ClampValue(offset_index, (int64_t)0, (int64_t)(current_path.size() - 1));
            // Get start & end indices
            const size_t start_index = (size_t)std::min(base_index, safe_offset_index);
            const size_t end_index = (size_t)std::max(base_index, safe_offset_index);
            if (end_index <= start_index + 1)
            {
                num_iterations++;
                continue;
            }
            // Check if the edge is valid
            const Configuration& start_config = current_path[start_index];
            const Configuration& end_config = current_path[end_index];
            const bool edge_valid = edge_validity_check_fn(start_config, end_config);
            if (edge_valid)
            {
                // Make the shortened path
                std::vector<Configuration, ConfigAlloc> shortened_path;
                shortened_path.insert(shortened_path.end(), current_path.begin(), current_path.begin() + start_index + 1);
                shortened_path.insert(shortened_path.end(), current_path.begin() + end_index, current_path.end());
                current_path = shortened_path;
                num_iterations++;
            }
            else
            {
                num_iterations++;
                failed_iterations++;
            }
        }
        return current_path;
    }

    template<typename Configuration, typename ConfigAlloc=std::allocator<Configuration>>
    std::vector<Configuration, ConfigAlloc> ResamplePath(const std::vector<Configuration, ConfigAlloc>& path, const double resampled_state_distance, const std::function<double(const Configuration&, const Configuration&)>& state_distance_fn, const std::function<Configuration(const Configuration&, const Configuration&, const double)>& state_interpolation_fn)
    {
        if (path.size() <= 1)
        {
            return path;
        }
        std::vector<Configuration, ConfigAlloc> resampled_path;
        // Add the first state
        resampled_path.push_back(path[0]);
        // Loop through the path, adding interpolated states as needed
        for (size_t idx = 1; idx < path.size(); idx++)
        {
            // Get the states from the original path
            const Configuration& previous_state = path[idx - 1];
            const Configuration& current_state = path[idx];
            // We want to add all the intermediate states to our returned path
            const double distance = state_distance_fn(previous_state, current_state);
            const double raw_num_intervals = distance / resampled_state_distance;
            const uint32_t num_segments = std::max(1u, (uint32_t)std::round(raw_num_intervals));
            // If there's only one segment, we just add the end state of the window
            if (num_segments <= 1u)
            {
                resampled_path.push_back(current_state);
            }
            // If there is more than one segment, interpolate between the start and end (including the end)
            else
            {
                for (uint32_t segment = 1u; segment <= num_segments; segment++)
                {
                    const double interpolation_ratio = (double)segment / (double)num_segments;
                    const Configuration interpolated_state = state_interpolation_fn(previous_state, current_state, interpolation_ratio);
                    resampled_path.push_back(interpolated_state);
                }
            }
        }
        return resampled_path;
    }
}

#endif // SHORTCUT_SMOOTHING_HPP
<|endoftext|>


<commit_before>#include<iostream>
class TicTacToe {
  public:
    TicTacToe():turn('X'), winner('\0') {  }

    // starts the game
    void startGame() {
      std::cout << "Tic Tac Toe" << std::endl;
      while (winner == '\0') {
        drawBoard();
        if (isPlayerWinner())
            break;
        showPlayerTurn();
        showMoveAndSwitchPlayer();
        system("cls");
      }
    }

    // draws the board
    void drawBoard() {
      std::cout << "     1   2   3" << std::endl;
      std::cout << "   +---+---+---+" << std::endl;
      for (int i = 1; i < 4; i++) {
        std::cout << " " << i << " | ";
        std::cout << squares[i - 1][0] << " | ";
        std::cout << squares[i - 1][1] << " | ";
        std::cout << squares[i - 1][2];
        std::cout << " |" << std::endl;
        std::cout << "   +---+---+---+" << std::endl;
      }
    }

    // check for a winner or tie
    bool isPlayerWinner() {
      for (int i = 0; i < 3; i++) {
        if (squares[i][0] == squares[i][1] &&
          squares[i][1] == squares[i][2] &&
          squares[i][0] != ' ') {
          winner = squares[i][0];
        }
      }

      for (int i = 0; i < 3; i++) {
        if (squares[0][i] == squares[1][i] &&
          squares[1][i] == squares[2][i] &&
          squares[0][i] != ' ') {
          winner = squares[0][i];
        }
      }

      if (squares[0][0] == squares[1][1] &&
        squares[1][1] == squares[2][2] &&
        squares[0][0] != ' ') {
        winner = squares[0][0];
      }

      if (squares[0][2] == squares[1][1] &&
        squares[1][1] == squares[2][0] &&
        squares[0][2] != ' ') {
        winner = squares[0][2];
      }

      if (squares[0][0] == squares[0][1] &&
        squares[0][1] == squares[0][2] &&
        squares[0][2] == squares[1][0] &&
        squares[1][0] == squares[1][1] &&
        squares[1][1] == squares[1][2] &&
        squares[1][2] == squares[2][0] &&
        squares[2][0] == squares[2][1] &&
        squares[2][1] == squares[2][2] &&
        squares[0][0] != ' ') {
        winner = 't';
      }

      // if somebody won
      if (winner == 'X' || winner == 'O') {

        // display congratulations message
        std::cout << "Congratulations! Player ";
        if(winner == 'X'){
          std::cout << 1;
        } else {
          std::cout << 2;
        }
        std::cout << " is the winner!" << std::endl;
        return true;
      } else if (winner == 't') {

        // display a message if it`s a tie
        std::cout << "Tie!" << std::endl;
        return true;
      } else {

        // no one has won yet so continue the game
        return false;
      }
    }

    // show the next player to make a move
    void showPlayerTurn() {
      std::cout << "Player ";
      if (turn == 'X') {
      	std::cout << 1;
      } else {
      	std::cout << 2;
      }
      std::cout << "'s turn:" << std::endl;
    }

    // get the row
    void getRow() {
      validRow = false;

      // loop until the player selects a valid row
      while (!validRow) {
        std::cout << "Row: ";
        std::cin >> row;
        if (row == 1 || row == 2 || row == 3) {
          validRow = true;
        } else {
          std::cout << std::endl << "Invalid row!" << std::endl;
        }
      }
    }

    // get the column
    void getCol() {
      validCol = false;

      //Loop until the player selects a valid column
      while (!validCol) {
		    std::cout << "Column: ";
		    std::cin >> col;
		    if (col == 1 || col == 2 || col == 3) {
			    validCol = true;
		    } else {
			    std::cout << std::endl << "Invalid column!" << std::endl;
		    }
	    }
    }

    void switchPlayer() {

      // change the turn to the next player
      if (squares[row - 1][col - 1] == ' ') {
        squares[row - 1][col - 1] = turn;
        validMove = true;
        if (turn == 'X') {
          turn = 'O';
        } else {
          turn = 'X';
        }

        // if the selected square is occupied display a message
        // and loop again
        } else {
          std::cout << "The selected square is occupied!" << std::endl;
          std::cout << "Select again:" << std::endl;
        }
    }

    void showMoveAndSwitchPlayer() {
      validMove = false;
      while (!validMove) {
        getRow();
        getCol();
        switchPlayer();
      }
    }

  private:
    static char squares[3][3];
    char turn, winner;
    int row, col;

    //variables to check if the move is valid
    bool validMove, validRow, validCol;
};

//array of chars represents the game board
char TicTacToe::squares[3][3] = {{' ',' ',' '}, {' ',' ',' '}, {' ',' ',' '}};

int main(int argc, char* agrv[]) {
  TicTacToe ticTacToe;
  ticTacToe.startGame();
  system("pause");
  return 0;
}
<commit_msg>Adjusted whitespace<commit_after>#include<iostream>
class TicTacToe {
  public:
    TicTacToe():turn('X'), winner('\0') {  }

    // starts the game
    void startGame() {
      std::cout << "Tic Tac Toe" << std::endl;
      while (winner == '\0') {
        drawBoard();
        if (isPlayerWinner())
            break;
        showPlayerTurn();
        showMoveAndSwitchPlayer();
        system("cls");
      }
    }

    // draws the board
    void drawBoard() {
      std::cout << "     1   2   3" << std::endl;
      std::cout << "   +---+---+---+" << std::endl;
      for (int i = 1; i < 4; i++) {
        std::cout << " " << i << " | ";
        std::cout << squares[i - 1][0] << " | ";
        std::cout << squares[i - 1][1] << " | ";
        std::cout << squares[i - 1][2];
        std::cout << " |" << std::endl;
        std::cout << "   +---+---+---+" << std::endl;
      }
    }

    // check for a winner or tie
    bool isPlayerWinner() {
      for (int i = 0; i < 3; i++) {
        if (squares[i][0] == squares[i][1] &&
          squares[i][1] == squares[i][2] &&
          squares[i][0] != ' ') {
          winner = squares[i][0];
        }
      }

      for (int i = 0; i < 3; i++) {
        if (squares[0][i] == squares[1][i] &&
          squares[1][i] == squares[2][i] &&
          squares[0][i] != ' ') {
          winner = squares[0][i];
        }
      }

      if (squares[0][0] == squares[1][1] &&
        squares[1][1] == squares[2][2] &&
        squares[0][0] != ' ') {
        winner = squares[0][0];
      }

      if (squares[0][2] == squares[1][1] &&
        squares[1][1] == squares[2][0] &&
        squares[0][2] != ' ') {
        winner = squares[0][2];
      }

      if (squares[0][0] == squares[0][1] &&
        squares[0][1] == squares[0][2] &&
        squares[0][2] == squares[1][0] &&
        squares[1][0] == squares[1][1] &&
        squares[1][1] == squares[1][2] &&
        squares[1][2] == squares[2][0] &&
        squares[2][0] == squares[2][1] &&
        squares[2][1] == squares[2][2] &&
        squares[0][0] != ' ') {
        winner = 't';
      }

      // if somebody won
      if (winner == 'X' || winner == 'O') {

        // display congratulations message
        std::cout << "Congratulations! Player ";
        if(winner == 'X'){
          std::cout << 1;
        } else {
          std::cout << 2;
        }
        std::cout << " is the winner!" << std::endl;
        return true;
      } else if (winner == 't') {

        // display a message if it`s a tie
        std::cout << "Tie!" << std::endl;
        return true;
      } else {

        // no one has won yet so continue the game
        return false;
      }
    }

    // show the next player to make a move
    void showPlayerTurn() {
      std::cout << "Player ";
      if (turn == 'X') {
      	std::cout << 1;
      } else {
      	std::cout << 2;
      }
      std::cout << "'s turn:" << std::endl;
    }

    // get the row
    void getRow() {
      validRow = false;

      // loop until the player selects a valid row
      while (!validRow) {
        std::cout << "Row: ";
        std::cin >> row;
        if (row == 1 || row == 2 || row == 3) {
          validRow = true;
        } else {
          std::cout << std::endl << "Invalid row!" << std::endl;
        }
      }
    }

    // get the column
    void getCol() {
      validCol = false;

      //Loop until the player selects a valid column
      while (!validCol) {
        std::cout << "Column: ";
        std::cin >> col;
        if (col == 1 || col == 2 || col == 3) {
          validCol = true;
        } else {
          std::cout << std::endl << "Invalid column!" << std::endl;
        }
      }
    }

    void switchPlayer() {

      // change the turn to the next player
      if (squares[row - 1][col - 1] == ' ') {
        squares[row - 1][col - 1] = turn;
        validMove = true;
        if (turn == 'X') {
          turn = 'O';
        } else {
          turn = 'X';
        }

        // if the selected square is occupied display a message
        // and loop again
        } else {
          std::cout << "The selected square is occupied!" << std::endl;
          std::cout << "Select again:" << std::endl;
        }
    }

    void showMoveAndSwitchPlayer() {
      validMove = false;
      while (!validMove) {
        getRow();
        getCol();
        switchPlayer();
      }
    }

  private:
    static char squares[3][3];
    char turn, winner;
    int row, col;

    //variables to check if the move is valid
    bool validMove, validRow, validCol;
};

//array of chars represents the game board
char TicTacToe::squares[3][3] = {{' ',' ',' '}, {' ',' ',' '}, {' ',' ',' '}};

int main(int argc, char* agrv[]) {
  TicTacToe ticTacToe;
  ticTacToe.startGame();
  system("pause");
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/runtime_download_manager_delegate.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commdlg.h>
#endif

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/file_chooser_params.h"
#include "content/shell/common/shell_switches.h"
#include "net/base/filename_util.h"
#include "xwalk/runtime/browser/runtime_platform_util.h"

#if defined(OS_LINUX)
#include "base/nix/xdg_util.h"
#endif

using content::BrowserThread;

namespace xwalk {

RuntimeDownloadManagerDelegate::RuntimeDownloadManagerDelegate()
    : download_manager_(NULL),
      suppress_prompting_(false) {
  // Balanced in Shutdown();
  AddRef();
}

RuntimeDownloadManagerDelegate::~RuntimeDownloadManagerDelegate() {
}

void RuntimeDownloadManagerDelegate::SetDownloadManager(
    content::DownloadManager* download_manager) {
  download_manager_ = download_manager;
}

void RuntimeDownloadManagerDelegate::Shutdown() {
  Release();
}

bool RuntimeDownloadManagerDelegate::DetermineDownloadTarget(
    content::DownloadItem* download,
    const content::DownloadTargetCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // This assignment needs to be here because even at the call to
  // SetDownloadManager, the system is not fully initialized.
  if (default_download_path_.empty()) {
#if defined(OS_LINUX)
    default_download_path_ =
        base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads");
#else
    default_download_path_ = download_manager_->GetBrowserContext()->GetPath().
        Append(FILE_PATH_LITERAL("Downloads"));
#endif
  }

  if (!download->GetForcedFilePath().empty()) {
    callback.Run(download->GetForcedFilePath(),
                 content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 download->GetForcedFilePath());
    return true;
  }

  base::FilePath generated_name = net::GenerateFileName(
      download->GetURL(),
      download->GetContentDisposition(),
      std::string(),
      download->GetSuggestedFilename(),
      download->GetMimeType(),
      "download");

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(
          &RuntimeDownloadManagerDelegate::GenerateFilename,
          this, download->GetId(), callback, generated_name,
          default_download_path_));
  return true;
}

bool RuntimeDownloadManagerDelegate::ShouldOpenDownload(
      content::DownloadItem* item,
      const content::DownloadOpenDelayedCallback& callback) {
  return true;
}

void RuntimeDownloadManagerDelegate::GetNextId(
    const content::DownloadIdCallback& callback) {
  static uint32_t next_id = content::DownloadItem::kInvalidId + 1;
  callback.Run(next_id++);
}

void RuntimeDownloadManagerDelegate::GenerateFilename(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& generated_name,
    const base::FilePath& suggested_directory) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  if (!base::CreateDirectory(suggested_directory)) {
    LOG(ERROR) << "Failed to create directory: "
               << suggested_directory.value();
    return;
  }

  base::FilePath suggested_path(suggested_directory.Append(generated_name));
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(
          &RuntimeDownloadManagerDelegate::OnDownloadPathGenerated,
          this, download_id, callback, suggested_path));
}

void RuntimeDownloadManagerDelegate::OnDownloadPathGenerated(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (suppress_prompting_) {
    // Testing exit.
    callback.Run(suggested_path,
                 content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")));
    return;
  }

  ChooseDownloadPath(download_id, callback, suggested_path);
}

void RuntimeDownloadManagerDelegate::ChooseDownloadPath(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::DownloadItem* item = download_manager_->GetDownload(download_id);
  if (!item || (item->GetState() != content::DownloadItem::IN_PROGRESS))
    return;

  base::FilePath result;
#if defined(OS_WIN) && !defined(USE_AURA)
  std::wstring file_part = base::FilePath(suggested_path).BaseName().value();
  wchar_t file_name[MAX_PATH];
  base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name));
  OPENFILENAME save_as;
  ZeroMemory(&save_as, sizeof(save_as));
  save_as.lStructSize = sizeof(OPENFILENAME);
  save_as.hwndOwner = item->GetWebContents()->GetView()->GetNativeView();
  save_as.lpstrFile = file_name;
  save_as.nMaxFile = arraysize(file_name);

  std::wstring directory;
  if (!suggested_path.empty())
    directory = suggested_path.DirName().value();

  save_as.lpstrInitialDir = directory.c_str();
  save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING |
                  OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;

  if (GetSaveFileName(&save_as))
    result = base::FilePath(std::wstring(save_as.lpstrFile));

  callback.Run(result, content::DownloadItem::TARGET_DISPOSITION_PROMPT,
               content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, result);
#elif defined(OS_LINUX)
  content::WebContents* contents = item->GetWebContents();
  Runtime* runtime = static_cast<Runtime*>(contents->GetDelegate());
  if (!runtime->AddDownloadItem(item, callback, suggested_path)) {
    const base::FilePath empty;
    callback.Run(empty,
        content::DownloadItem::TARGET_DISPOSITION_PROMPT,
        content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
        suggested_path);
  }
#else
  NOTIMPLEMENTED();
#endif
}

void RuntimeDownloadManagerDelegate::SetDownloadBehaviorForTesting(
    const base::FilePath& default_download_path) {
  default_download_path_ = default_download_path;
  suppress_prompting_ = true;
}

}  // namespace xwalk
<commit_msg>Stop using std::wstring in our code.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/runtime_download_manager_delegate.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commdlg.h>
#endif

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/file_chooser_params.h"
#include "content/shell/common/shell_switches.h"
#include "net/base/filename_util.h"
#include "xwalk/runtime/browser/runtime_platform_util.h"

#if defined(OS_LINUX)
#include "base/nix/xdg_util.h"
#endif

#if defined(OS_WIN)
#include "ui/base/win/open_file_name_win.h"
#endif

using content::BrowserThread;

namespace xwalk {

RuntimeDownloadManagerDelegate::RuntimeDownloadManagerDelegate()
    : download_manager_(NULL),
      suppress_prompting_(false) {
  // Balanced in Shutdown();
  AddRef();
}

RuntimeDownloadManagerDelegate::~RuntimeDownloadManagerDelegate() {
}

void RuntimeDownloadManagerDelegate::SetDownloadManager(
    content::DownloadManager* download_manager) {
  download_manager_ = download_manager;
}

void RuntimeDownloadManagerDelegate::Shutdown() {
  Release();
}

bool RuntimeDownloadManagerDelegate::DetermineDownloadTarget(
    content::DownloadItem* download,
    const content::DownloadTargetCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // This assignment needs to be here because even at the call to
  // SetDownloadManager, the system is not fully initialized.
  if (default_download_path_.empty()) {
#if defined(OS_LINUX)
    default_download_path_ =
        base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads");
#else
    default_download_path_ = download_manager_->GetBrowserContext()->GetPath().
        Append(FILE_PATH_LITERAL("Downloads"));
#endif
  }

  if (!download->GetForcedFilePath().empty()) {
    callback.Run(download->GetForcedFilePath(),
                 content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 download->GetForcedFilePath());
    return true;
  }

  base::FilePath generated_name = net::GenerateFileName(
      download->GetURL(),
      download->GetContentDisposition(),
      std::string(),
      download->GetSuggestedFilename(),
      download->GetMimeType(),
      "download");

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(
          &RuntimeDownloadManagerDelegate::GenerateFilename,
          this, download->GetId(), callback, generated_name,
          default_download_path_));
  return true;
}

bool RuntimeDownloadManagerDelegate::ShouldOpenDownload(
      content::DownloadItem* item,
      const content::DownloadOpenDelayedCallback& callback) {
  return true;
}

void RuntimeDownloadManagerDelegate::GetNextId(
    const content::DownloadIdCallback& callback) {
  static uint32_t next_id = content::DownloadItem::kInvalidId + 1;
  callback.Run(next_id++);
}

void RuntimeDownloadManagerDelegate::GenerateFilename(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& generated_name,
    const base::FilePath& suggested_directory) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  if (!base::CreateDirectory(suggested_directory)) {
    LOG(ERROR) << "Failed to create directory: "
               << suggested_directory.value();
    return;
  }

  base::FilePath suggested_path(suggested_directory.Append(generated_name));
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(
          &RuntimeDownloadManagerDelegate::OnDownloadPathGenerated,
          this, download_id, callback, suggested_path));
}

void RuntimeDownloadManagerDelegate::OnDownloadPathGenerated(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (suppress_prompting_) {
    // Testing exit.
    callback.Run(suggested_path,
                 content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")));
    return;
  }

  ChooseDownloadPath(download_id, callback, suggested_path);
}

void RuntimeDownloadManagerDelegate::ChooseDownloadPath(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  content::DownloadItem* item = download_manager_->GetDownload(download_id);
  if (!item || (item->GetState() != content::DownloadItem::IN_PROGRESS))
    return;

  base::FilePath result;
#if defined(OS_WIN) && !defined(USE_AURA)
  ui::win::OpenFileName open_file_name(
      item->GetWebContents()->GetView()->GetNativeView(),
      OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING | OFN_NOCHANGEDIR |
          OFN_PATHMUSTEXIST);
  open_file_name.SetInitialSelection(suggested_path.DirName(),
                                     suggested_path.BaseName());
  if (::GetSaveFileName(open_file_name.GetOPENFILENAME()))
    result = open_file_name.GetSingleResult();
  callback.Run(result, content::DownloadItem::TARGET_DISPOSITION_PROMPT,
               content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, result);
#elif defined(OS_LINUX)
  content::WebContents* contents = item->GetWebContents();
  Runtime* runtime = static_cast<Runtime*>(contents->GetDelegate());
  if (!runtime->AddDownloadItem(item, callback, suggested_path)) {
    const base::FilePath empty;
    callback.Run(empty,
        content::DownloadItem::TARGET_DISPOSITION_PROMPT,
        content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
        suggested_path);
  }
#else
  NOTIMPLEMENTED();
#endif
}

void RuntimeDownloadManagerDelegate::SetDownloadBehaviorForTesting(
    const base::FilePath& default_download_path) {
  default_download_path_ = default_download_path;
  suppress_prompting_ = true;
}

}  // namespace xwalk
<|endoftext|>


<commit_before>#ifndef GAMELIB_PROPCOMPONENT_HPP
#define GAMELIB_PROPCOMPONENT_HPP

#include "PropType.hpp"
#include "gamelib/utils/nametag.hpp"
#include "gamelib/utils/Identifier.hpp"

namespace gamelib
{
    class Component;
    class Entity;
    class PropertyContainer;

    class PropComponent : public PropType<0xe73dee69, Component*>
    {
        public:
            bool loadFromJson(const PropertyHandle& prop, Component** ptr, const Json::Value& node) const final override;
            void writeToJson(const PropertyHandle& prop, Component* const* ptr, Json::Value& node) const final override;
            bool drawGui(const PropertyHandle& prop, const std::string& name, Component** ptr) const final override;

            static Entity* getEntity(const PropertyHandle& prop);
    };

    extern PropComponent propComponent;

    template <typename T, typename U>
    using ComponentPropSetter = NicePropSetterCallback<T*, U>;

    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter,
            unsigned int filter, int max = 0, const char* const* filternames = nullptr);

    template <typename T, typename U,
             typename std::enable_if<has_nametag<T>(), int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        static const char* hints[] = { T::name().c_str() };
        registerProperty(props, name, prop, self, setter, 0, 1, hints);
    }

    template <typename T, typename U,
             typename std::enable_if<!has_nametag<T>() && has_identifier<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, T::id);
    }

    template <typename T, typename U,
             typename std::enable_if<!has_identifier<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, 0);
    }
}

#include "PropertyContainer.hpp"

namespace gamelib
{
    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter, unsigned int filter, int max, const char* const* filternames)
    {
        static_assert(std::is_base_of<Component, T>(), "Not a component");
        static_assert(std::is_base_of<Component, U>(), "Callback data must be the calling component or the component to search in");
        props.registerProperty(name, prop, setter, &self, &propComponent, filter, max, filternames);
    }
}

#endif
<commit_msg>Fix calling wrong function<commit_after>#ifndef GAMELIB_PROPCOMPONENT_HPP
#define GAMELIB_PROPCOMPONENT_HPP

#include "PropType.hpp"
#include "gamelib/utils/nametag.hpp"
#include "gamelib/utils/Identifier.hpp"

namespace gamelib
{
    class Component;
    class Entity;
    class PropertyContainer;

    class PropComponent : public PropType<0xe73dee69, Component*>
    {
        public:
            bool loadFromJson(const PropertyHandle& prop, Component** ptr, const Json::Value& node) const final override;
            void writeToJson(const PropertyHandle& prop, Component* const* ptr, Json::Value& node) const final override;
            bool drawGui(const PropertyHandle& prop, const std::string& name, Component** ptr) const final override;

            static Entity* getEntity(const PropertyHandle& prop);
    };

    extern PropComponent propComponent;

    template <typename T, typename U>
    using ComponentPropSetter = NicePropSetterCallback<T*, U>;

    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter,
            unsigned int filter, int max = 0, const char* const* filternames = nullptr);

    template <typename T, typename U,
             typename std::enable_if<has_nametag<T>(), int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        static const char* hints[] = { T::name().c_str() };
        registerProperty(props, name, prop, self, setter, 0, 1, hints);
    }

    template <typename T, typename U,
             typename std::enable_if<!has_nametag<T>() && has_identifier<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, T::id);
    }

    template <typename T, typename U,
             typename std::enable_if<!has_identifier<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, 0);
    }
}

#include "PropertyContainer.hpp"

namespace gamelib
{
    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter, unsigned int filter, int max, const char* const* filternames)
    {
        static_assert(std::is_base_of<Component, T>(), "Not a component");
        static_assert(std::is_base_of<Component, U>(), "Callback data must be the calling component or the component to search in");
        if (setter)
            props.registerProperty(name, prop, setter, &self, &propComponent, filter, max, filternames);
        else
            props.registerProperty(name, prop, &propComponent, filter, max, filternames, &self);
    }
}

#endif
<|endoftext|>


<commit_before>#include "BtWorld.hpp"
#include "BtShape.hpp"
#include "BtRigidBody.hpp"
#include "BtCharacter.hpp"
#include "../Exception.hpp"

BEGIN_INANITY_PHYSICS

BtWorld::BtWorld() :
	collisionConfiguration(0), collisionDispatcher(0), broadphase(0),
	solver(0), dynamicsWorld(0)
{
	try
	{
		collisionConfiguration = new btDefaultCollisionConfiguration();
		collisionDispatcher = new btCollisionDispatcher(collisionConfiguration);
		broadphase = new btDbvtBroadphase();
		solver = new btSequentialImpulseConstraintSolver();
		dynamicsWorld = new btDiscreteDynamicsWorld(collisionDispatcher, broadphase, solver, collisionConfiguration);

		broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());

		dynamicsWorld->setGravity(btVector3(0, 0, -9.8));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet world", exception);
	}
}

BtWorld::~BtWorld()
{
	if(dynamicsWorld)
		delete dynamicsWorld;
	if(solver)
		delete solver;
	if(broadphase)
		delete broadphase;
	if(collisionDispatcher)
		delete collisionDispatcher;
	if(collisionConfiguration)
		delete collisionConfiguration;
}

btDynamicsWorld* BtWorld::GetInternalDynamicsWorld() const
{
	return dynamicsWorld;
}

ptr<Shape> BtWorld::CreateBoxShape(const vec3& halfSize)
{
	try
	{
		btCollisionShape* collisionShape = new btBoxShape(toBt(halfSize));

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<Shape> BtWorld::CreateSphereShape(float radius)
{
	try
	{
		btCollisionShape* collisionShape = new btSphereShape(radius);

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<Shape> BtWorld::CreateCapsuleShape(float radius, float height)
{
	try
	{
		btCollisionShape* collisionShape = new btCapsuleShape(radius, height);

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<RigidBody> BtWorld::CreateRigidBody(ptr<Shape> abstractShape, float mass, const mat4x4& startTransform)
{
	try
	{
		ptr<BtShape> shape = abstractShape.FastCast<BtShape>();
		if(!shape)
			THROW("Non-bullet shape");

		btCollisionShape* collisionShape = shape->GetInternalObject();
		btVector3 localInertia(0, 0, 0);
		if(mass != 0)
			collisionShape->calculateLocalInertia(mass, localInertia);

		ptr<BtRigidBody> rigidBody = NEW(BtRigidBody(this, shape, toBt(startTransform)));
		btRigidBody::btRigidBodyConstructionInfo info(mass, &*rigidBody, shape->GetInternalObject(), localInertia);
		btRigidBody* internalRigidBody = new btRigidBody(info);
		rigidBody->SetInternalObject(internalRigidBody);

		dynamicsWorld->addRigidBody(internalRigidBody);

		return rigidBody;
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet rigid body", exception);
	}
}

ptr<Character> BtWorld::CreateCharacter(ptr<Shape> abstractShape, const mat4x4& startTransform)
{
	try
	{
		ptr<BtShape> shape = abstractShape.FastCast<BtShape>();
		if(!shape)
			THROW("Non-bullet shape");

		btConvexShape* collisionShape = fast_cast<btConvexShape*>(shape->GetInternalObject());

		btPairCachingGhostObject* ghost = new btPairCachingGhostObject();
		ghost->setWorldTransform(toBt(startTransform));
		ghost->setCollisionShape(collisionShape);
		ghost->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
		// 2 - номер оси "вверх" - Z
		btKinematicCharacterController* controller = new btKinematicCharacterController(ghost, collisionShape, 0.5f, 2);

		dynamicsWorld->addCollisionObject(ghost);
		//dynamicsWorld->addCollisionObject(ghost, btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter);
		dynamicsWorld->addAction(controller);

		return NEW(BtCharacter(this, shape, ghost, controller));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet character", exception);
	}
}

void BtWorld::Simulate(float time)
{
	dynamicsWorld->stepSimulation(time, 10);
}

END_INANITY_PHYSICS
<commit_msg>increase bullet computation frequency<commit_after>#include "BtWorld.hpp"
#include "BtShape.hpp"
#include "BtRigidBody.hpp"
#include "BtCharacter.hpp"
#include "../Exception.hpp"

BEGIN_INANITY_PHYSICS

BtWorld::BtWorld() :
	collisionConfiguration(0), collisionDispatcher(0), broadphase(0),
	solver(0), dynamicsWorld(0)
{
	try
	{
		collisionConfiguration = new btDefaultCollisionConfiguration();
		collisionDispatcher = new btCollisionDispatcher(collisionConfiguration);
		broadphase = new btDbvtBroadphase();
		solver = new btSequentialImpulseConstraintSolver();
		dynamicsWorld = new btDiscreteDynamicsWorld(collisionDispatcher, broadphase, solver, collisionConfiguration);

		broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());

		dynamicsWorld->setGravity(btVector3(0, 0, -9.8));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet world", exception);
	}
}

BtWorld::~BtWorld()
{
	if(dynamicsWorld)
		delete dynamicsWorld;
	if(solver)
		delete solver;
	if(broadphase)
		delete broadphase;
	if(collisionDispatcher)
		delete collisionDispatcher;
	if(collisionConfiguration)
		delete collisionConfiguration;
}

btDynamicsWorld* BtWorld::GetInternalDynamicsWorld() const
{
	return dynamicsWorld;
}

ptr<Shape> BtWorld::CreateBoxShape(const vec3& halfSize)
{
	try
	{
		btCollisionShape* collisionShape = new btBoxShape(toBt(halfSize));

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<Shape> BtWorld::CreateSphereShape(float radius)
{
	try
	{
		btCollisionShape* collisionShape = new btSphereShape(radius);

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<Shape> BtWorld::CreateCapsuleShape(float radius, float height)
{
	try
	{
		btCollisionShape* collisionShape = new btCapsuleShape(radius, height);

		return NEW(BtShape(this, collisionShape));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet box shape", exception);
	}
}

ptr<RigidBody> BtWorld::CreateRigidBody(ptr<Shape> abstractShape, float mass, const mat4x4& startTransform)
{
	try
	{
		ptr<BtShape> shape = abstractShape.FastCast<BtShape>();
		if(!shape)
			THROW("Non-bullet shape");

		btCollisionShape* collisionShape = shape->GetInternalObject();
		btVector3 localInertia(0, 0, 0);
		if(mass != 0)
			collisionShape->calculateLocalInertia(mass, localInertia);

		ptr<BtRigidBody> rigidBody = NEW(BtRigidBody(this, shape, toBt(startTransform)));
		btRigidBody::btRigidBodyConstructionInfo info(mass, &*rigidBody, shape->GetInternalObject(), localInertia);
		btRigidBody* internalRigidBody = new btRigidBody(info);
		rigidBody->SetInternalObject(internalRigidBody);

		dynamicsWorld->addRigidBody(internalRigidBody);

		return rigidBody;
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet rigid body", exception);
	}
}

ptr<Character> BtWorld::CreateCharacter(ptr<Shape> abstractShape, const mat4x4& startTransform)
{
	try
	{
		ptr<BtShape> shape = abstractShape.FastCast<BtShape>();
		if(!shape)
			THROW("Non-bullet shape");

		btConvexShape* collisionShape = fast_cast<btConvexShape*>(shape->GetInternalObject());

		btPairCachingGhostObject* ghost = new btPairCachingGhostObject();
		ghost->setWorldTransform(toBt(startTransform));
		ghost->setCollisionShape(collisionShape);
		ghost->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
		// 2 - номер оси "вверх" - Z
		btKinematicCharacterController* controller = new btKinematicCharacterController(ghost, collisionShape, 0.5f, 2);

		dynamicsWorld->addCollisionObject(ghost);
		//dynamicsWorld->addCollisionObject(ghost, btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter);
		dynamicsWorld->addAction(controller);

		return NEW(BtCharacter(this, shape, ghost, controller));
	}
	catch(Exception* exception)
	{
		THROW_SECONDARY("Can't create bullet character", exception);
	}
}

void BtWorld::Simulate(float time)
{
	dynamicsWorld->stepSimulation(time, 100);
}

END_INANITY_PHYSICS
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: targethelper.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2004-01-28 14:38:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_
#include <loadenv/targethelper.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

/*-----------------------------------------------
    05.08.2003 09:12
-----------------------------------------------*/
TargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)
{
    if (
        (!sTarget.getLength()              ) ||
        (sTarget.equals(SPECIALTARGET_SELF))
       )
        return E_SELF;

    if (sTarget.equals(SPECIALTARGET_PARENT))
        return E_PARENT;

    if (sTarget.equals(SPECIALTARGET_TOP))
        return E_TOP;

    if (sTarget.equals(SPECIALTARGET_BLANK))
        return E_BLANK;

    if (sTarget.equals(SPECIALTARGET_DEFAULT))
        return E_DEFAULT;

    if (sTarget.equals(SPECIALTARGET_BEAMER))
        return E_BEAMER;

    if (sTarget.equals(SPECIALTARGET_MENUBAR))
        return E_MENUBAR;

    if (sTarget.equals(SPECIALTARGET_HELPAGENT))
        return E_HELPAGENT;

    if (sTarget.equals(SPECIALTARGET_HELPTASK))
        return E_HELPTASK;

    return E_NOT_SPECIAL;
}

/*-----------------------------------------------
    05.08.2003 09:08
-----------------------------------------------*/
sal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget  ,
                                                ESpecialTarget   eSpecialTarget)
{
    switch(eSpecialTarget)
    {
        case E_SELF :
            return (
                    (!sCheckTarget.getLength()              ) ||
                    (sCheckTarget.equals(SPECIALTARGET_SELF))
                   );

        case E_PARENT :
            return (sCheckTarget.equals(SPECIALTARGET_PARENT));

        case E_TOP :
            return (sCheckTarget.equals(SPECIALTARGET_TOP));

        case E_BLANK :
            return (sCheckTarget.equals(SPECIALTARGET_BLANK));

        case E_DEFAULT :
            return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));

        case E_BEAMER :
            return (sCheckTarget.equals(SPECIALTARGET_BEAMER));

        case E_MENUBAR :
            return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));

        case E_HELPAGENT :
            return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));

        case E_HELPTASK :
            return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));
    }

    return sal_False;
}

/*-----------------------------------------------
    05.08.2003 09:17
-----------------------------------------------*/
sal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)
{
    // some special targets are realy special ones :-)
    // E.g. the are realy used to locate one frame inside the frame tree.
    if (
        (!sName.getLength()                                 ) ||
        (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||
        (TargetHelper::matchSpecialTarget(sName, E_BEAMER)  )
       )
        return sal_True;

    // all other names must be checked more general
    // special targets starts with a "_".
    return (sName.indexOf('_') != 0);
}

} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.350); FILE MERGED 2005/09/05 13:06:42 rt 1.2.350.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: targethelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:38:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_
#include <loadenv/targethelper.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

/*-----------------------------------------------
    05.08.2003 09:12
-----------------------------------------------*/
TargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)
{
    if (
        (!sTarget.getLength()              ) ||
        (sTarget.equals(SPECIALTARGET_SELF))
       )
        return E_SELF;

    if (sTarget.equals(SPECIALTARGET_PARENT))
        return E_PARENT;

    if (sTarget.equals(SPECIALTARGET_TOP))
        return E_TOP;

    if (sTarget.equals(SPECIALTARGET_BLANK))
        return E_BLANK;

    if (sTarget.equals(SPECIALTARGET_DEFAULT))
        return E_DEFAULT;

    if (sTarget.equals(SPECIALTARGET_BEAMER))
        return E_BEAMER;

    if (sTarget.equals(SPECIALTARGET_MENUBAR))
        return E_MENUBAR;

    if (sTarget.equals(SPECIALTARGET_HELPAGENT))
        return E_HELPAGENT;

    if (sTarget.equals(SPECIALTARGET_HELPTASK))
        return E_HELPTASK;

    return E_NOT_SPECIAL;
}

/*-----------------------------------------------
    05.08.2003 09:08
-----------------------------------------------*/
sal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget  ,
                                                ESpecialTarget   eSpecialTarget)
{
    switch(eSpecialTarget)
    {
        case E_SELF :
            return (
                    (!sCheckTarget.getLength()              ) ||
                    (sCheckTarget.equals(SPECIALTARGET_SELF))
                   );

        case E_PARENT :
            return (sCheckTarget.equals(SPECIALTARGET_PARENT));

        case E_TOP :
            return (sCheckTarget.equals(SPECIALTARGET_TOP));

        case E_BLANK :
            return (sCheckTarget.equals(SPECIALTARGET_BLANK));

        case E_DEFAULT :
            return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));

        case E_BEAMER :
            return (sCheckTarget.equals(SPECIALTARGET_BEAMER));

        case E_MENUBAR :
            return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));

        case E_HELPAGENT :
            return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));

        case E_HELPTASK :
            return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));
    }

    return sal_False;
}

/*-----------------------------------------------
    05.08.2003 09:17
-----------------------------------------------*/
sal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)
{
    // some special targets are realy special ones :-)
    // E.g. the are realy used to locate one frame inside the frame tree.
    if (
        (!sName.getLength()                                 ) ||
        (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||
        (TargetHelper::matchSpecialTarget(sName, E_BEAMER)  )
       )
        return sal_True;

    // all other names must be checked more general
    // special targets starts with a "_".
    return (sName.indexOf('_') != 0);
}

} // namespace framework
<|endoftext|>


<commit_before><commit_msg>Sketcher: Show partial redundant messages when sketch is fully constraint<commit_after><|endoftext|>


<commit_before><commit_msg>VectorOps : explicitly define vecMul and VecDiv for MSVC<commit_after><|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// test the pacTire for 3 distinct slip cases, then compare force/moment output
// v. slip (kappa, alpha) to Adams/Car testrig output
// 1) pure longitudinal slip (V_yc = tan(alpha) = 0)
// 2) pure lateral slip, (kappa ~= 0)
// 3) combined slip
//
// we will run our vehicle with default rigid tires, but calculate the output
// for the pacjeka tire in the background
//
// =============================================================================

#include <vector>

#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

#include "subsys/tire/ChPacejkaTire.h"
#include "subsys/terrain/FlatTerrain.h"

#include "ChronoT_config.h"

using namespace chrono;

const std::string out_dir = "../PACTEST";
const std::string pov_dir = out_dir + "/POVRAY";

// ============== PacTire settings go here
const int num_pts = 801;                  // # of data points in the slip ranges
const double step_size = 0.01;            // seconds, arbitrary unless calculating transient slip
const double alpha_lim = CH_C_PI_4/3.0;   // slip angle in range [-lim,lim] or [0,lim]
const double kappa_lim = 1;               // slip rate in range [-lim,lim] or [0,lim]
const double F_z = 8000;                  // vertical force, [N]
const double time_end = (num_pts - 1)*step_size;

// for the transient model
const bool use_transient_slip = true;    // use kinematic or transient contact slips?

const std::string pacParamFile = utils::GetModelDataFile("hmmwv/pactest.tir");

std::string outData_filename_long = "test_pacTire_pureLongSlip.csv";
std::string outData_filename_lat = "test_pacTire_pureLatSlip.csv";
std::string outData_filename_combined = "test_pacTire_combinedSlip.csv";

int main(int argc, char* argv[])
{
  SetChronoDataPath(CHRONO_DATA_DIR);

  // flat rigid terrain, height = 0 for all (x,y)
  FlatTerrain flat_terrain(0);

  // Create the Pac tires, try to open param file and load empirical constants
  ChPacejkaTire tire_long("LONGITUDINAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
  ChPacejkaTire tire_lat("LATERAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
  ChPacejkaTire tire_combined("COMBINED", pacParamFile, flat_terrain, F_z, use_transient_slip);

  // record pacTire output for each of the 3 slip cases
  ChTireForces long_forces(1);
  ChTireForces lat_forces(1);
  ChTireForces combined_forces(1);

  // update body state based on varying input variables to pacTire:
  // alpha, kappa and gamma
  ChWheelState long_state;
  ChWheelState lat_state;
  ChWheelState combined_state;

  // keep track of the input variable values
  std::vector<double> latSlip_range;
  std::vector<double> longSlip_range;
  latSlip_range.resize(num_pts);
  longSlip_range.resize(num_pts);

  double time = 0.0;

  // get the bounds of the slip angles from the input *.tire file
  double k_min, k_max, a_min, a_max;
  k_min = -kappa_lim;
  k_max = kappa_lim;
  a_min = -alpha_lim;
  a_max = alpha_lim;

  // at IC, go straight ahead at zero slip
  double kappa_t = k_min;
  double alpha_t = 0;
  double tanalpha_t = tan(alpha_t);
  double gamma_t = 0.1 * alpha_t;

  // unless we're only using steady-state EQs, then just sweep min to max
  if (!use_transient_slip)
  {
    alpha_t = a_min;
    tanalpha_t = tan(alpha_t);
    gamma_t = 0.1 * alpha_t;
  }
  else {
    outData_filename_long = "test_pacTire_pureLongSlip_transient.csv";
    outData_filename_lat = "test_pacTire_pureLatSlip_transient.csv";
    outData_filename_combined = "test_pacTire_combinedSlip_transient.csv";
  }

  // calculate the increments for each slip case (assuming constant per step)
  double kappa_incr = (k_max - k_min) / double(num_pts);
  double alpha_incr = (a_max - a_min) / double(num_pts);

  // horizontal velocity (x,y components) is constant throughout all runs
  double vel_xy = tire_long.get_longvl();

  // time step is arbitrary, steps determined by slip array length
  for (size_t step = 0; step < num_pts; step++)
  {
    // tire input slip quantities
    tanalpha_t = tan(alpha_t);

    // DEBUGGING
    gamma_t = 0;   // 0.1 * alpha_t;

    latSlip_range[step] = tanalpha_t;
    longSlip_range[step] = kappa_t;

    // **** longitudinal states
    long_state = tire_long.getState_from_KAG(kappa_t, 0, 0, vel_xy);

    // **** lateral states
    lat_state = tire_lat.getState_from_KAG(0, alpha_t, gamma_t, vel_xy);

    // ****  combined states
    combined_state = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);

    // check states calculated for this step
    // ChWheelState kag_long = tire_long.getState_from_KAG(kappa_t, 0, gamma_t, vel_xy);
    // ChWheelState kag_lat = tire_lat.getState_from_KAG(0, alpha_t, gamma_t, vel_xy;
    // ChWheelState kag_combined = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);

    // DEBUGGING
    if (step == 250)
      int arg = 2;

    // update all 3 types of tires, with current wheel state data
    tire_long.Update(time, long_state);
    tire_lat.Update(time, lat_state);
    tire_combined.Update(time, combined_state);

    // advance the slip displacements, calculate reactions
    tire_long.Advance(step_size);
    tire_lat.Advance(step_size);
    tire_combined.Advance(step_size);

    // see what the calculated reactions are
    long_forces[0] = tire_long.GetTireForce();
    lat_forces[0] = tire_lat.GetTireForce();
    combined_forces[0] = tire_combined.GetTireForce();

    // output any data at the end of the step
    tire_long.WriteOutData(time, outData_filename_long);
    tire_lat.WriteOutData(time, outData_filename_lat);
    tire_combined.WriteOutData(time, outData_filename_combined);

    // std::cout << "step: " << step << ", kappa = " << kappa_t << ", alpha = " << alpha_t << ", tan(alpha) = " << tanalpha_t << std::endl;

    // increment time, update long. & lat. slips for the next time step
    time += step_size;
    // constant increments. sine waves would be better
    if (use_transient_slip)
    {
      // do a powered lane change
      // Careful !!!!
      // need to properly mimic Adams/Car kappa, alpha vs. time
      // kappa is linear
      kappa_t += kappa_incr;
      // lateral angle is a sine wave
      alpha_t = abs(a_max) * sin(2.0 * chrono::CH_C_PI * time / time_end);
    }
    else {
      kappa_t += kappa_incr;
      alpha_t += alpha_incr;
    }

  }

  // clean up anything

  return 0;
}
<commit_msg>Add Initialize() function call after initializing the ChPacejkaTire objects.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// test the pacTire for 3 distinct slip cases, then compare force/moment output
// v. slip (kappa, alpha) to Adams/Car testrig output
// 1) pure longitudinal slip (V_yc = tan(alpha) = 0)
// 2) pure lateral slip, (kappa ~= 0)
// 3) combined slip
//
// we will run our vehicle with default rigid tires, but calculate the output
// for the pacjeka tire in the background
//
// =============================================================================

#include <vector>

#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

#include "subsys/tire/ChPacejkaTire.h"
#include "subsys/terrain/FlatTerrain.h"

#include "ChronoT_config.h"

using namespace chrono;

const std::string out_dir = "../PACTEST";
const std::string pov_dir = out_dir + "/POVRAY";

// ============== PacTire settings go here
const int num_pts = 801;                  // # of data points in the slip ranges
const double step_size = 0.01;            // seconds, arbitrary unless calculating transient slip
const double alpha_lim = CH_C_PI_4/3.0;   // slip angle in range [-lim,lim] or [0,lim]
const double kappa_lim = 1;               // slip rate in range [-lim,lim] or [0,lim]
const double F_z = 8000;                  // vertical force, [N]
const double time_end = (num_pts - 1)*step_size;

// for the transient model
const bool use_transient_slip = true;    // use kinematic or transient contact slips?

const std::string pacParamFile = utils::GetModelDataFile("hmmwv/pactest.tir");

std::string outData_filename_long = "test_pacTire_pureLongSlip.csv";
std::string outData_filename_lat = "test_pacTire_pureLatSlip.csv";
std::string outData_filename_combined = "test_pacTire_combinedSlip.csv";

int main(int argc, char* argv[])
{
  SetChronoDataPath(CHRONO_DATA_DIR);

  // flat rigid terrain, height = 0 for all (x,y)
  FlatTerrain flat_terrain(0);

  // Create the Pac tires, try to open param file and load empirical constants
  ChPacejkaTire tire_long("LONGITUDINAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
  ChPacejkaTire tire_lat("LATERAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
  ChPacejkaTire tire_combined("COMBINED", pacParamFile, flat_terrain, F_z, use_transient_slip);

  tire_long.Initialize(LEFT);
  tire_lat.Initialize(LEFT);
  tire_combined.Initialize(LEFT);

  // record pacTire output for each of the 3 slip cases
  ChTireForces long_forces(1);
  ChTireForces lat_forces(1);
  ChTireForces combined_forces(1);

  // update body state based on varying input variables to pacTire:
  // alpha, kappa and gamma
  ChWheelState long_state;
  ChWheelState lat_state;
  ChWheelState combined_state;

  // keep track of the input variable values
  std::vector<double> latSlip_range;
  std::vector<double> longSlip_range;
  latSlip_range.resize(num_pts);
  longSlip_range.resize(num_pts);

  double time = 0.0;

  // get the bounds of the slip angles from the input *.tire file
  double k_min, k_max, a_min, a_max;
  k_min = -kappa_lim;
  k_max = kappa_lim;
  a_min = -alpha_lim;
  a_max = alpha_lim;

  // at IC, go straight ahead at zero slip
  double kappa_t = k_min;
  double alpha_t = 0;
  double tanalpha_t = tan(alpha_t);
  double gamma_t = 0.1 * alpha_t;

  // unless we're only using steady-state EQs, then just sweep min to max
  if (!use_transient_slip)
  {
    alpha_t = a_min;
    tanalpha_t = tan(alpha_t);
    gamma_t = 0.1 * alpha_t;
  }
  else {
    outData_filename_long = "test_pacTire_pureLongSlip_transient.csv";
    outData_filename_lat = "test_pacTire_pureLatSlip_transient.csv";
    outData_filename_combined = "test_pacTire_combinedSlip_transient.csv";
  }

  // calculate the increments for each slip case (assuming constant per step)
  double kappa_incr = (k_max - k_min) / double(num_pts);
  double alpha_incr = (a_max - a_min) / double(num_pts);

  // horizontal velocity (x,y components) is constant throughout all runs
  double vel_xy = tire_long.get_longvl();

  // time step is arbitrary, steps determined by slip array length
  for (size_t step = 0; step < num_pts; step++)
  {
    // tire input slip quantities
    tanalpha_t = tan(alpha_t);

    // DEBUGGING
    gamma_t = 0;   // 0.1 * alpha_t;

    latSlip_range[step] = tanalpha_t;
    longSlip_range[step] = kappa_t;

    // **** longitudinal states
    long_state = tire_long.getState_from_KAG(kappa_t, 0, 0, vel_xy);

    // **** lateral states
    lat_state = tire_lat.getState_from_KAG(0, alpha_t, gamma_t, vel_xy);

    // ****  combined states
    combined_state = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);

    // check states calculated for this step
    // ChWheelState kag_long = tire_long.getState_from_KAG(kappa_t, 0, gamma_t, vel_xy);
    // ChWheelState kag_lat = tire_lat.getState_from_KAG(0, alpha_t, gamma_t, vel_xy;
    // ChWheelState kag_combined = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);

    // DEBUGGING
    if (step == 250)
      int arg = 2;

    // update all 3 types of tires, with current wheel state data
    tire_long.Update(time, long_state);
    tire_lat.Update(time, lat_state);
    tire_combined.Update(time, combined_state);

    // advance the slip displacements, calculate reactions
    tire_long.Advance(step_size);
    tire_lat.Advance(step_size);
    tire_combined.Advance(step_size);

    // see what the calculated reactions are
    long_forces[0] = tire_long.GetTireForce();
    lat_forces[0] = tire_lat.GetTireForce();
    combined_forces[0] = tire_combined.GetTireForce();

    // output any data at the end of the step
    tire_long.WriteOutData(time, outData_filename_long);
    tire_lat.WriteOutData(time, outData_filename_lat);
    tire_combined.WriteOutData(time, outData_filename_combined);

    // std::cout << "step: " << step << ", kappa = " << kappa_t << ", alpha = " << alpha_t << ", tan(alpha) = " << tanalpha_t << std::endl;

    // increment time, update long. & lat. slips for the next time step
    time += step_size;
    // constant increments. sine waves would be better
    if (use_transient_slip)
    {
      // do a powered lane change
      // Careful !!!!
      // need to properly mimic Adams/Car kappa, alpha vs. time
      // kappa is linear
      kappa_t += kappa_incr;
      // lateral angle is a sine wave
      alpha_t = abs(a_max) * sin(2.0 * chrono::CH_C_PI * time / time_end);
    }
    else {
      kappa_t += kappa_incr;
      alpha_t += alpha_incr;
    }

  }

  // clean up anything

  return 0;
}
<|endoftext|>