<commit_before>#include "graphstorageregistry.h"

#include "edgedb/coverageedb.h"
#include "edgedb/fallbackedgedb.h"
#include "edgedb/linearedgedb.h"
#include "edgedb/prepostorderstorage.h"

using namespace annis;

using PrePostOrderStorageO32L32 = PrePostOrderStorage<uint32_t, int32_t>;
using PrePostOrderStorageO32L8 = PrePostOrderStorage<uint32_t, int8_t>;

using LinearEdgeDBP32 = LinearEdgeDB<uint32_t>;
using LinearEdgeDBP16 = LinearEdgeDB<uint16_t>;
using LinearEdgeDBP8 = LinearEdgeDB<uint8_t>;

const std::string GraphStorageRegistry::linearP32 = "linear";
const std::string GraphStorageRegistry::linearP16 = "linearP16";
const std::string GraphStorageRegistry::linearP8 = "linearP8";
const std::string GraphStorageRegistry::coverage = "coverage";
const std::string GraphStorageRegistry::prepostorderO32L32 = "prepostorder";
const std::string GraphStorageRegistry::prepostorderO32L8 = "prepostorderO32L8";
const std::string GraphStorageRegistry::fallback = "fallback";

GraphStorageRegistry::GraphStorageRegistry()
{
  // set default values
  setImplementation(coverage, ComponentType::COVERAGE);
}

GraphStorageRegistry::~GraphStorageRegistry()
{

}

std::string annis::GraphStorageRegistry::getName(const annis::ReadableGraphStorage *db)
{
  if(dynamic_cast<const CoverageEdgeDB*>(db) != nullptr)
  {
    return coverage;
  }
  else if(dynamic_cast<const LinearEdgeDBP32*>(db) != nullptr)
  {
    return linearP32;
  }
  else if(dynamic_cast<const LinearEdgeDBP16*>(db) != nullptr)
  {
    return linearP16;
  }
  else if(dynamic_cast<const LinearEdgeDBP8*>(db) != nullptr)
  {
    return linearP8;
  }
  else if(dynamic_cast<const PrePostOrderStorageO32L32*>(db) != nullptr)
  {
    return prepostorderO32L32;
  }
  else if(dynamic_cast<const PrePostOrderStorageO32L8*>(db) != nullptr)
  {
    return prepostorderO32L8;
  }
  else if(dynamic_cast<const FallbackEdgeDB*>(db) != nullptr)
  {
    return fallback;
  }
  return "";
}

ReadableGraphStorage *GraphStorageRegistry::createEdgeDB(std::string name, StringStorage& strings, const Component& component)
{
  if(name == coverage)
  {
    return new CoverageEdgeDB(strings, component);
  }
  else if(name == linearP32)
  {
    return new LinearEdgeDBP32(strings, component);
  }
  else if(name == linearP16)
  {
    return new LinearEdgeDBP16(strings, component);
  }
  else if(name == linearP8)
  {
    return new LinearEdgeDBP8(strings, component);
  }
  else if(name == prepostorderO32L32)
  {
    return new PrePostOrderStorageO32L32(strings, component);
  }
  else if(name == prepostorderO32L8)
  {
    return new PrePostOrderStorageO32L8(strings, component);
  }
  else if(name == fallback)
  {
    return new FallbackEdgeDB(strings, component);
  }

  return nullptr;
}

std::string GraphStorageRegistry::getOptimizedImpl(const Component &component, GraphStatistic stats)
{
  std::string result = getImplByRegistry(component);
  if(result.empty())
  {
    result = getImplByHeuristics(component, stats);
  }
  if(result.empty())
  {
    result = fallback;
  }

  return result;
}

ReadableGraphStorage *GraphStorageRegistry::createEdgeDB(StringStorage &strings, const Component &component, GraphStatistic stats)
{
  std::string implName = getOptimizedImpl(component, stats);
  return createEdgeDB(implName, strings, component);
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type)
{
  Component c = {type, "", ""};
  componentToImpl[c] = implName;
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer)
{
  Component c = {type, layer, ""};
  componentToImpl[c] = implName;
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer, std::string name)
{
  Component c = {type, layer, name};
  componentToImpl[c] = implName;
}

std::string GraphStorageRegistry::getImplByRegistry(const Component &component)
{
  std::string result = "";
  // try to find a fully matching entry
  auto it = componentToImpl.find(component);
  if(it != componentToImpl.end())
  {
    result = it->second;
  }
  else
  {
    // try without the name
    Component withoutName = {component.type, component.layer, ""};
    it = componentToImpl.find(withoutName);
    if(it != componentToImpl.end())
    {
      result = it->second;
    }
    else
    {
      // try only the component type
      Component onlyType = {component.type, "", ""};
      it = componentToImpl.find(onlyType);
      if(it != componentToImpl.end())
      {
        result = it->second;
      }
    }
  }

  return result;
}

std::string GraphStorageRegistry::getImplByHeuristics(const Component &component, GraphStatistic stats)
{
  std::string result = fallback;

  if(stats.valid)
  {
    if(stats.rootedTree)
    {
      if(stats.maxFanOut <= 1)
      {
        // a tree where all nodes belong to the same path
        if(stats.maxDepth < std::numeric_limits<uint8_t>::max())
        {
          result = linearP8;
        }
        else if(stats.maxDepth < std::numeric_limits<uint16_t>::max())
        {
          result = linearP16;
        }
        else if(stats.maxDepth < std::numeric_limits<uint32_t>::max())
        {
          result = linearP32;
        }
      }
      else
      {
        // we have a real tree
        result = getPrePostOrderBySize(stats);
      }
    }
    else if(!stats.cyclic)
    {
      // it might be still wise to use pre/post order if the graph is "almost" a tree, thus
      // does not have many exceptions
      if(stats.dfsVisitRatio <= 1.03)
      {
        // there is no more than 3% overhead
        // TODO: how to determine the border?
        result = getPrePostOrderBySize(stats);
      }
    }
  }

  return result;
}
<commit_msg>use fallback if maximal depth is 1<commit_after>#include "graphstorageregistry.h"

#include "edgedb/coverageedb.h"
#include "edgedb/fallbackedgedb.h"
#include "edgedb/linearedgedb.h"
#include "edgedb/prepostorderstorage.h"

using namespace annis;

using PrePostOrderStorageO32L32 = PrePostOrderStorage<uint32_t, int32_t>;
using PrePostOrderStorageO32L8 = PrePostOrderStorage<uint32_t, int8_t>;

using LinearEdgeDBP32 = LinearEdgeDB<uint32_t>;
using LinearEdgeDBP16 = LinearEdgeDB<uint16_t>;
using LinearEdgeDBP8 = LinearEdgeDB<uint8_t>;

const std::string GraphStorageRegistry::linearP32 = "linear";
const std::string GraphStorageRegistry::linearP16 = "linearP16";
const std::string GraphStorageRegistry::linearP8 = "linearP8";
const std::string GraphStorageRegistry::coverage = "coverage";
const std::string GraphStorageRegistry::prepostorderO32L32 = "prepostorder";
const std::string GraphStorageRegistry::prepostorderO32L8 = "prepostorderO32L8";
const std::string GraphStorageRegistry::fallback = "fallback";

GraphStorageRegistry::GraphStorageRegistry()
{
  // set default values
  setImplementation(coverage, ComponentType::COVERAGE);
}

GraphStorageRegistry::~GraphStorageRegistry()
{

}

std::string annis::GraphStorageRegistry::getName(const annis::ReadableGraphStorage *db)
{
  if(dynamic_cast<const CoverageEdgeDB*>(db) != nullptr)
  {
    return coverage;
  }
  else if(dynamic_cast<const LinearEdgeDBP32*>(db) != nullptr)
  {
    return linearP32;
  }
  else if(dynamic_cast<const LinearEdgeDBP16*>(db) != nullptr)
  {
    return linearP16;
  }
  else if(dynamic_cast<const LinearEdgeDBP8*>(db) != nullptr)
  {
    return linearP8;
  }
  else if(dynamic_cast<const PrePostOrderStorageO32L32*>(db) != nullptr)
  {
    return prepostorderO32L32;
  }
  else if(dynamic_cast<const PrePostOrderStorageO32L8*>(db) != nullptr)
  {
    return prepostorderO32L8;
  }
  else if(dynamic_cast<const FallbackEdgeDB*>(db) != nullptr)
  {
    return fallback;
  }
  return "";
}

ReadableGraphStorage *GraphStorageRegistry::createEdgeDB(std::string name, StringStorage& strings, const Component& component)
{
  if(name == coverage)
  {
    return new CoverageEdgeDB(strings, component);
  }
  else if(name == linearP32)
  {
    return new LinearEdgeDBP32(strings, component);
  }
  else if(name == linearP16)
  {
    return new LinearEdgeDBP16(strings, component);
  }
  else if(name == linearP8)
  {
    return new LinearEdgeDBP8(strings, component);
  }
  else if(name == prepostorderO32L32)
  {
    return new PrePostOrderStorageO32L32(strings, component);
  }
  else if(name == prepostorderO32L8)
  {
    return new PrePostOrderStorageO32L8(strings, component);
  }
  else if(name == fallback)
  {
    return new FallbackEdgeDB(strings, component);
  }

  return nullptr;
}

std::string GraphStorageRegistry::getOptimizedImpl(const Component &component, GraphStatistic stats)
{
  std::string result = getImplByRegistry(component);
  if(result.empty())
  {
    result = getImplByHeuristics(component, stats);
  }
  if(result.empty())
  {
    result = fallback;
  }

  return result;
}

ReadableGraphStorage *GraphStorageRegistry::createEdgeDB(StringStorage &strings, const Component &component, GraphStatistic stats)
{
  std::string implName = getOptimizedImpl(component, stats);
  return createEdgeDB(implName, strings, component);
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type)
{
  Component c = {type, "", ""};
  componentToImpl[c] = implName;
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer)
{
  Component c = {type, layer, ""};
  componentToImpl[c] = implName;
}

void GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer, std::string name)
{
  Component c = {type, layer, name};
  componentToImpl[c] = implName;
}

std::string GraphStorageRegistry::getImplByRegistry(const Component &component)
{
  std::string result = "";
  // try to find a fully matching entry
  auto it = componentToImpl.find(component);
  if(it != componentToImpl.end())
  {
    result = it->second;
  }
  else
  {
    // try without the name
    Component withoutName = {component.type, component.layer, ""};
    it = componentToImpl.find(withoutName);
    if(it != componentToImpl.end())
    {
      result = it->second;
    }
    else
    {
      // try only the component type
      Component onlyType = {component.type, "", ""};
      it = componentToImpl.find(onlyType);
      if(it != componentToImpl.end())
      {
        result = it->second;
      }
    }
  }

  return result;
}

std::string GraphStorageRegistry::getImplByHeuristics(const Component &component, GraphStatistic stats)
{
  std::string result = fallback;

  if(stats.valid)
  {
    if(stats.maxDepth <= 1)
    {
      // if we don't have any deep graph structures an adjencency list is always fasted (and has no overhead)
      result = fallback;
    }
    else if(stats.rootedTree)
    {
      if(stats.maxFanOut <= 1)
      {
        // a tree where all nodes belong to the same path
        if(stats.maxDepth < std::numeric_limits<uint8_t>::max())
        {
          result = linearP8;
        }
        else if(stats.maxDepth < std::numeric_limits<uint16_t>::max())
        {
          result = linearP16;
        }
        else if(stats.maxDepth < std::numeric_limits<uint32_t>::max())
        {
          result = linearP32;
        }
      }
      else
      {
        // we have a real tree
        result = getPrePostOrderBySize(stats);
      }
    }
    else if(!stats.cyclic)
    {
      // it might be still wise to use pre/post order if the graph is "almost" a tree, thus
      // does not have many exceptions
      if(stats.dfsVisitRatio <= 1.03)
      {
        // there is no more than 3% overhead
        // TODO: how to determine the border?
        result = getPrePostOrderBySize(stats);
      }
    }
  }

  return result;
}
<|endoftext|>


<commit_before>#pragma once

#include <functional>
#include <memory>
#include <string>
#include <vector>

#include "abstract_operator.hpp"
#include "storage/reference_column.hpp"
#include "types.hpp"

namespace opossum {

template <typename T>
class TableScanImpl;

class TableScan : public AbstractOperator {
 public:
  TableScan(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name, const std::string &op,
            const AllTypeVariant value);
  virtual void execute();
  virtual std::shared_ptr<Table> get_output() const;

 protected:
  virtual const std::string get_name() const;
  virtual uint8_t get_num_in_tables() const;
  virtual uint8_t get_num_out_tables() const;

  const std::unique_ptr<AbstractOperatorImpl> _impl;
};

template <typename T>
class TableScanImpl : public AbstractOperatorImpl {
 public:
  TableScanImpl(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name,
                const std::string &op, const AllTypeVariant value)
      : _filter_value(type_cast<T>(value)),
        _table(in->get_output()),
        _filter_column_id(_table->get_column_id_by_name(filter_column_name)),
        _op(op),
        _output(new Table),
        _pos_list(new PosList) {
    for (size_t column_id = 0; column_id < _table->col_count(); ++column_id) {
      std::shared_ptr<ReferenceColumn> ref;
      if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(column_id))) {
        ref = std::make_shared<ReferenceColumn>(ref_col->get_referenced_table(), column_id, _pos_list);
      } else {
        ref = std::make_shared<ReferenceColumn>(_table, column_id, _pos_list);
      }
      _output->add_column(_table->get_column_name(column_id), _table->get_column_type(column_id), false);
      _output->get_chunk(0).add_column(ref);
      // TODO(Anyone): do we want to distinguish between chunk tables and "reference tables"?
    }
  }

  template <typename Comp>
  void execute_with_operator() {
    Comp comp;
    if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(_filter_column_id))) {
      auto val_table = ref_col->get_referenced_table();
      std::vector<std::vector<T>> values = {};
      for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {
        values.emplace_back(
            std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_filter_column_id))
                ->get_values());
      }
      auto in_pos_list = ref_col->get_pos_list();

      for (size_t pos = 0; pos < in_pos_list->size(); pos++) {
        auto chunk_id = get_chunk_id_from_row_id((*in_pos_list)[pos]);
        auto chunk_offset = get_chunk_offset_from_row_id((*in_pos_list)[pos]);
        if (comp(values[chunk_id][chunk_offset], _filter_value)) {
          _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));
        }
      }
    } else {
      for (ChunkID chunk_id = 0; chunk_id < _table->chunk_count(); ++chunk_id) {
        auto &chunk = _table->get_chunk(chunk_id);
        auto base_column = chunk.get_column(_filter_column_id);
        auto &values = std::dynamic_pointer_cast<ValueColumn<T>>(base_column)->get_values();
        for (ChunkOffset chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) {
          if (comp(values[chunk_offset], _filter_value)) {
            _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));
          }
        }
      }
    }
  }

  void execute() {
    // Definining all possible operators here might appear odd. Chances are, however, that we will not
    // have a similar comparison anywhere else. Index scans, for example, would not use an adaptable binary
    // predicate, but will have to use different methods (lower_range, upper_range, ...) based on the
    // chosen operator. For now, we can save us some dark template magic by using the switch below.
    // DO NOT copy this code, however, without discussing if there is a better way to avoid code duplication.

    if (_op == "=")
      execute_with_operator<std::equal_to<>>();
    else if (_op == "!=")
      execute_with_operator<std::not_equal_to<>>();
    else if (_op == "<")
      execute_with_operator<std::less<>>();
    else if (_op == "<=")
      execute_with_operator<std::less_equal<>>();
    else if (_op == ">")
      execute_with_operator<std::greater<>>();
    else if (_op == ">=")
      execute_with_operator<std::greater_equal<>>();
    else
      throw std::runtime_error(std::string("unknown operator ") + _op);
  }

  virtual std::shared_ptr<Table> get_output() const { return _output; }

  const T _filter_value;
  const std::shared_ptr<Table> _table;
  const size_t _filter_column_id;
  const std::string _op;
  std::shared_ptr<Table> _output;
  std::shared_ptr<PosList> _pos_list;
};
}  // namespace opossum
<commit_msg>ensuring referenced columns during table scan are value columns<commit_after>#pragma once

#include <functional>
#include <memory>
#include <string>
#include <vector>

#include "abstract_operator.hpp"
#include "storage/reference_column.hpp"
#include "types.hpp"

namespace opossum {

template <typename T>
class TableScanImpl;

class TableScan : public AbstractOperator {
 public:
  TableScan(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name, const std::string &op,
            const AllTypeVariant value);
  virtual void execute();
  virtual std::shared_ptr<Table> get_output() const;

 protected:
  virtual const std::string get_name() const;
  virtual uint8_t get_num_in_tables() const;
  virtual uint8_t get_num_out_tables() const;

  const std::unique_ptr<AbstractOperatorImpl> _impl;
};

template <typename T>
class TableScanImpl : public AbstractOperatorImpl {
 public:
  TableScanImpl(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name,
                const std::string &op, const AllTypeVariant value)
      : _filter_value(type_cast<T>(value)),
        _table(in->get_output()),
        _filter_column_id(_table->get_column_id_by_name(filter_column_name)),
        _op(op),
        _output(new Table),
        _pos_list(new PosList) {
    for (size_t column_id = 0; column_id < _table->col_count(); ++column_id) {
      std::shared_ptr<ReferenceColumn> ref;
      if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(column_id))) {
        ref = std::make_shared<ReferenceColumn>(ref_col->get_referenced_table(), column_id, _pos_list);
      } else {
        ref = std::make_shared<ReferenceColumn>(_table, column_id, _pos_list);
      }
      _output->add_column(_table->get_column_name(column_id), _table->get_column_type(column_id), false);
      _output->get_chunk(0).add_column(ref);
      // TODO(Anyone): do we want to distinguish between chunk tables and "reference tables"?
    }
  }

  template <typename Comp>
  void execute_with_operator() {
    Comp comp;
    if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(_filter_column_id))) {
      auto val_table = ref_col->get_referenced_table();
      std::vector<std::vector<T>> values = {};
      for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {
        if (auto val_col =
                std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_filter_column_id))) {
          values.emplace_back(val_col->get_values());
        } else {
          throw std::logic_error("Referenced table must only contain value columns");
        }
      }
      auto in_pos_list = ref_col->get_pos_list();

      for (size_t pos = 0; pos < in_pos_list->size(); pos++) {
        auto chunk_id = get_chunk_id_from_row_id((*in_pos_list)[pos]);
        auto chunk_offset = get_chunk_offset_from_row_id((*in_pos_list)[pos]);
        if (comp(values[chunk_id][chunk_offset], _filter_value)) {
          _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));
        }
      }
    } else {
      for (ChunkID chunk_id = 0; chunk_id < _table->chunk_count(); ++chunk_id) {
        auto &chunk = _table->get_chunk(chunk_id);
        auto base_column = chunk.get_column(_filter_column_id);
        auto &values = std::dynamic_pointer_cast<ValueColumn<T>>(base_column)->get_values();
        for (ChunkOffset chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) {
          if (comp(values[chunk_offset], _filter_value)) {
            _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));
          }
        }
      }
    }
  }

  void execute() {
    // Definining all possible operators here might appear odd. Chances are, however, that we will not
    // have a similar comparison anywhere else. Index scans, for example, would not use an adaptable binary
    // predicate, but will have to use different methods (lower_range, upper_range, ...) based on the
    // chosen operator. For now, we can save us some dark template magic by using the switch below.
    // DO NOT copy this code, however, without discussing if there is a better way to avoid code duplication.

    if (_op == "=")
      execute_with_operator<std::equal_to<>>();
    else if (_op == "!=")
      execute_with_operator<std::not_equal_to<>>();
    else if (_op == "<")
      execute_with_operator<std::less<>>();
    else if (_op == "<=")
      execute_with_operator<std::less_equal<>>();
    else if (_op == ">")
      execute_with_operator<std::greater<>>();
    else if (_op == ">=")
      execute_with_operator<std::greater_equal<>>();
    else
      throw std::runtime_error(std::string("unknown operator ") + _op);
  }

  virtual std::shared_ptr<Table> get_output() const { return _output; }

  const T _filter_value;
  const std::shared_ptr<Table> _table;
  const size_t _filter_column_id;
  const std::string _op;
  std::shared_ptr<Table> _output;
  std::shared_ptr<PosList> _pos_list;
};
}  // namespace opossum
<|endoftext|>


<commit_before>#include "MoveSystem.h"

#include <iostream>

void MoveSystem::update(int currentStep)
{
    const std::vector<int> &uidList = movementNode.uids();
	for(int i = 0; i < uidList.size(); i++)
	{
		MovementNode &n = movementNode.get(uidList.at(i));

		PositionComponent &p = n.position;
		const VelocityComponent &v = n.velocity;
		p.positionX += v.velocityX;
		std::cout << p.positionX << "\n";
	}
}<commit_msg>Change: velocity definition<commit_after>#include "MoveSystem.h"

#include <iostream>

void MoveSystem::update(int currentStep)
{
    const std::vector<int> &uidList = movementNode.uids();
	for(int i = 0; i < uidList.size(); i++)
	{
		MovementNode &n = movementNode.get(uidList.at(i));

		PositionComponent &p = n.position;
		const VelocityComponent &v = n.velocity;
		const PositionTargetComponent &t = n.target;

		p.positionX += v.velocityFB;
	}
}<|endoftext|>


<commit_before>#include "Moves/Move.h"

#include <cassert>

#include "Game/Board.h"
#include "Game/Game_Result.h"
#include "Game/Piece.h"
#include "Utility.h"

Move::Move(char file_start, int rank_start,
           char file_end,   int rank_end) :
               starting_file(file_start),
               starting_rank(rank_start),
               ending_file(file_end),
               ending_rank(rank_end),
               able_to_capture(true),
               is_en_passant_move(false),
               is_castling_move(false)
{
    assert(std::abs(file_change()) < 8);
    assert(std::abs(rank_change()) < 8);
    assert(file_change() != 0 || rank_change() != 0);
}

void Move::side_effects(Board&) const
{
}

bool Move::is_legal(const Board& board) const
{
    assert(Board::inside_board(starting_file, starting_rank));
    assert(Board::inside_board(ending_file, ending_rank));

    // Piece-move compatibility
    auto moving_piece = board.piece_on_square(starting_file, starting_rank);
    assert(moving_piece);
    assert(moving_piece->color() == board.whose_turn());
    assert(moving_piece->can_move(this));

    auto attacked_piece = board.piece_on_square(ending_file, ending_rank);
    if(attacked_piece)
    {
        // Cannot capture piece of same color
        if(moving_piece->color() == attacked_piece->color())
        {
            return false;
        }

        // Enforce non-capturing moves
        if( ! can_capture())
        {
            return false;
        }
    }

    if( ! move_specific_legal(board))
    {
        return false;
    }

    // King should not be in check after move
    return ! board.king_is_in_check_after_move(*this);
}

bool Move::move_specific_legal(const Board&) const
{
    return true;
}

bool Move::can_capture() const
{
    return able_to_capture;
}

char Move::start_file() const
{
    return starting_file;
}

int Move::start_rank() const
{
    return starting_rank;
}

int Move::file_change() const
{
    return ending_file - starting_file;
}

int Move::rank_change() const
{
    return ending_rank - starting_rank;
}

char Move::end_file() const
{
    return ending_file;
}

int Move::end_rank() const
{
    return ending_rank;
}

std::string Move::game_record_item(const Board& board) const
{
    return game_record_move_item(board) + game_record_ending_item(board);
}

std::string Move::game_record_move_item(const Board& board) const
{
    auto original_piece = board.piece_on_square(starting_file, starting_rank);
    std::string move_record = original_piece->pgn_symbol();

    bool record_file = false;
    bool record_rank = false;
    for(char file_other = 'a'; file_other <= 'h'; ++file_other)
    {
        for(int rank_other = 1; rank_other <= 8; ++rank_other)
        {
            if( ! board.piece_on_square(file_other, rank_other))
            {
                continue;
            }
            if(file_other == starting_file && rank_other == starting_rank)
            {
                continue;
            }
            if(file_other == ending_file && rank_other == ending_rank)
            {
                continue;
            }
            auto new_piece = board.piece_on_square(file_other, rank_other);
            if(original_piece != new_piece)
            {
                continue;
            }

            if(board.is_legal(file_other, rank_other, ending_file, ending_rank))
            {
                if(file_other != starting_file && ! record_file)
                {
                    record_file = true;
                    continue;
                }
                if(rank_other != starting_rank)
                {
                    record_rank = true;
                }
            }
        }
    }

    if(record_file)
    {
        move_record += starting_file;
    }
    if(record_rank)
    {
        move_record += std::to_string(starting_rank);
    }

    if(board.piece_on_square(ending_file, ending_rank))
    {
        move_record += 'x';
    }

    move_record += ending_file + std::to_string(ending_rank);

    return move_record;
}

std::string Move::game_record_ending_item(Board board) const
{
    auto result = board.submit_move(*this);
    std::string appendage;

    if(board.king_is_in_check())
    {
        appendage.push_back('+');
    }

    if(result.game_has_ended())
    {
        appendage += result.game_record_annotation();
    }

    return appendage.substr(String::starts_with(appendage, "+#") ? 1 : 0);
}

std::string Move::coordinate_move() const
{
    return starting_file
           + std::to_string(starting_rank)
           + ending_file
           + std::to_string(ending_rank);
}

bool Move::is_en_passant() const
{
    return is_en_passant_move;
}

bool Move::is_castling() const
{
    return is_castling_move;
}

char Move::promotion_piece_symbol() const
{
    return '\0';
}
<commit_msg>Remove extra call to Board::piece_on_square() from release build<commit_after>#include "Moves/Move.h"

#include <cassert>

#include "Game/Board.h"
#include "Game/Game_Result.h"
#include "Game/Piece.h"
#include "Utility.h"

Move::Move(char file_start, int rank_start,
           char file_end,   int rank_end) :
               starting_file(file_start),
               starting_rank(rank_start),
               ending_file(file_end),
               ending_rank(rank_end),
               able_to_capture(true),
               is_en_passant_move(false),
               is_castling_move(false)
{
    assert(std::abs(file_change()) < 8);
    assert(std::abs(rank_change()) < 8);
    assert(file_change() != 0 || rank_change() != 0);
}

void Move::side_effects(Board&) const
{
}

bool Move::is_legal(const Board& board) const
{
    assert(Board::inside_board(starting_file, starting_rank));
    assert(Board::inside_board(ending_file, ending_rank));

    // Piece-move compatibility
    assert(board.piece_on_square(starting_file, starting_rank));
    assert(board.piece_on_square(starting_file, starting_rank)->color() == board.whose_turn());
    assert(board.piece_on_square(starting_file, starting_rank)->can_move(this));

    auto attacked_piece = board.piece_on_square(ending_file, ending_rank);
    if(attacked_piece)
    {
        // Cannot capture piece of same color
        if(board.whose_turn() == attacked_piece->color())
        {
            return false;
        }

        // Enforce non-capturing moves
        if( ! can_capture())
        {
            return false;
        }
    }

    if( ! move_specific_legal(board))
    {
        return false;
    }

    // King should not be in check after move
    return ! board.king_is_in_check_after_move(*this);
}

bool Move::move_specific_legal(const Board&) const
{
    return true;
}

bool Move::can_capture() const
{
    return able_to_capture;
}

char Move::start_file() const
{
    return starting_file;
}

int Move::start_rank() const
{
    return starting_rank;
}

int Move::file_change() const
{
    return ending_file - starting_file;
}

int Move::rank_change() const
{
    return ending_rank - starting_rank;
}

char Move::end_file() const
{
    return ending_file;
}

int Move::end_rank() const
{
    return ending_rank;
}

std::string Move::game_record_item(const Board& board) const
{
    return game_record_move_item(board) + game_record_ending_item(board);
}

std::string Move::game_record_move_item(const Board& board) const
{
    auto original_piece = board.piece_on_square(starting_file, starting_rank);
    std::string move_record = original_piece->pgn_symbol();

    bool record_file = false;
    bool record_rank = false;
    for(char file_other = 'a'; file_other <= 'h'; ++file_other)
    {
        for(int rank_other = 1; rank_other <= 8; ++rank_other)
        {
            if( ! board.piece_on_square(file_other, rank_other))
            {
                continue;
            }
            if(file_other == starting_file && rank_other == starting_rank)
            {
                continue;
            }
            if(file_other == ending_file && rank_other == ending_rank)
            {
                continue;
            }
            auto new_piece = board.piece_on_square(file_other, rank_other);
            if(original_piece != new_piece)
            {
                continue;
            }

            if(board.is_legal(file_other, rank_other, ending_file, ending_rank))
            {
                if(file_other != starting_file && ! record_file)
                {
                    record_file = true;
                    continue;
                }
                if(rank_other != starting_rank)
                {
                    record_rank = true;
                }
            }
        }
    }

    if(record_file)
    {
        move_record += starting_file;
    }
    if(record_rank)
    {
        move_record += std::to_string(starting_rank);
    }

    if(board.piece_on_square(ending_file, ending_rank))
    {
        move_record += 'x';
    }

    move_record += ending_file + std::to_string(ending_rank);

    return move_record;
}

std::string Move::game_record_ending_item(Board board) const
{
    auto result = board.submit_move(*this);
    std::string appendage;

    if(board.king_is_in_check())
    {
        appendage.push_back('+');
    }

    if(result.game_has_ended())
    {
        appendage += result.game_record_annotation();
    }

    return appendage.substr(String::starts_with(appendage, "+#") ? 1 : 0);
}

std::string Move::coordinate_move() const
{
    return starting_file
           + std::to_string(starting_rank)
           + ending_file
           + std::to_string(ending_rank);
}

bool Move::is_en_passant() const
{
    return is_en_passant_move;
}

bool Move::is_castling() const
{
    return is_castling_move;
}

char Move::promotion_piece_symbol() const
{
    return '\0';
}
<|endoftext|>


<commit_before>/*
 * G00Handler.cpp
 *
 *  Created on: 15 maj 2014
 *      Author: MattLech
 */

#include "GCodeHandler.h"
#include "G00Handler.h"
#include "CurrentState.h"
#include "pins.h"
#include "Config.h"

static G00Handler* instance;

G00Handler * G00Handler::getInstance() {
	if (!instance) {
		instance = new G00Handler();
	};
	return instance;
}
;

G00Handler::G00Handler() {
}

long adjustStepAmount(long steps) {
	if (steps < 0) {
		return steps + 1;
	} else if (steps > 0) {
		return steps - 1;
	} else {
		return 0;
	}
}

long getNumberOfSteps(double destinationNumber, double currentNumber) {
	return destinationNumber - currentNumber;
}

int GCodeHandler::execute(Command* command) {
	long xStepsNeeded = getNumberOfSteps(command->getX(),
			CurrentState::getInstance()->getX());
	long yStepsNeeded = getNumberOfSteps(command->getY(),
			CurrentState::getInstance()->getY());
	long zStepsNeeded = getNumberOfSteps(command->getZ(),
			CurrentState::getInstance()->getZ());
	if(LOGGING) {
		Serial.print("Steps X:");
		Serial.print(xStepsNeeded);
		Serial.print(", Steps Y:");
		Serial.print(yStepsNeeded);
		Serial.print(", Steps Z:");
		Serial.println(zStepsNeeded);
	}
	if (xStepsNeeded > 0) {
		digitalWrite(X_DIR_PIN, LOW);
	} else {
		digitalWrite(X_DIR_PIN, HIGH);
	}
	if (yStepsNeeded > 0) {
		digitalWrite(Y_DIR_PIN, LOW);
	} else {
		digitalWrite(Y_DIR_PIN, HIGH);
	}
	if (zStepsNeeded > 0) {
		digitalWrite(Z_DIR_PIN, LOW);
	} else {
		digitalWrite(Z_DIR_PIN, HIGH);
	}

	CurrentState::getInstance()->setX(
			CurrentState::getInstance()->getX() + xStepsNeeded);
	CurrentState::getInstance()->setY(
			CurrentState::getInstance()->getY() + yStepsNeeded);
	CurrentState::getInstance()->setZ(
			CurrentState::getInstance()->getZ() + zStepsNeeded);

	digitalWrite(X_ENABLE_PIN, LOW);
	digitalWrite(Y_ENABLE_PIN, LOW);
	digitalWrite(Z_ENABLE_PIN, LOW);

	while (xStepsNeeded != 0 || yStepsNeeded != 0 || zStepsNeeded != 0) {
		if (xStepsNeeded != 0) {
			digitalWrite(X_STEP_PIN, HIGH);
		}
		if (yStepsNeeded != 0) {
			digitalWrite(Y_STEP_PIN, HIGH);
		}
		if (zStepsNeeded != 0) {
			digitalWrite(Z_STEP_PIN, HIGH);
		}
		delay(5);
		if (xStepsNeeded != 0) {
			digitalWrite(X_STEP_PIN, LOW);
			xStepsNeeded = adjustStepAmount(xStepsNeeded);
		}
		if (yStepsNeeded != 0) {
			digitalWrite(Y_STEP_PIN, LOW);
			yStepsNeeded = adjustStepAmount(yStepsNeeded);
		}
		if (zStepsNeeded != 0) {
			digitalWrite(Z_STEP_PIN, LOW);
			zStepsNeeded = adjustStepAmount(zStepsNeeded);
		}

	}
	if(LOGGING) {
		CurrentState::getInstance()->print();
	}
	return 0;
}
<commit_msg>Inverted the direction of all axis<commit_after>/*
 * G00Handler.cpp
 *
 *  Created on: 15 maj 2014
 *      Author: MattLech
 */

#include "GCodeHandler.h"
#include "G00Handler.h"
#include "CurrentState.h"
#include "pins.h"
#include "Config.h"

static G00Handler* instance;

G00Handler * G00Handler::getInstance() {
	if (!instance) {
		instance = new G00Handler();
	};
	return instance;
}
;

G00Handler::G00Handler() {
}

long adjustStepAmount(long steps) {
	if (steps < 0) {
		return steps + 1;
	} else if (steps > 0) {
		return steps - 1;
	} else {
		return 0;
	}
}

long getNumberOfSteps(double destinationNumber, double currentNumber) {
	return destinationNumber - currentNumber;
}

int GCodeHandler::execute(Command* command) {
	long xStepsNeeded = getNumberOfSteps(command->getX(),
			CurrentState::getInstance()->getX());
	long yStepsNeeded = getNumberOfSteps(command->getY(),
			CurrentState::getInstance()->getY());
	long zStepsNeeded = getNumberOfSteps(command->getZ(),
			CurrentState::getInstance()->getZ());
	if(LOGGING) {
		Serial.print("Steps X:");
		Serial.print(xStepsNeeded);
		Serial.print(", Steps Y:");
		Serial.print(yStepsNeeded);
		Serial.print(", Steps Z:");
		Serial.println(zStepsNeeded);
	}
	if (xStepsNeeded > 0) {
		digitalWrite(X_DIR_PIN, HIGH);
	} else {
		digitalWrite(X_DIR_PIN, LOW);
	}
	if (yStepsNeeded > 0) {
		digitalWrite(Y_DIR_PIN, HIGH);
	} else {
		digitalWrite(Y_DIR_PIN, LOW);
	}
	if (zStepsNeeded > 0) {
		digitalWrite(Z_DIR_PIN, HIGH);
	} else {
		digitalWrite(Z_DIR_PIN, LOW);
	}

	CurrentState::getInstance()->setX(
			CurrentState::getInstance()->getX() + xStepsNeeded);
	CurrentState::getInstance()->setY(
			CurrentState::getInstance()->getY() + yStepsNeeded);
	CurrentState::getInstance()->setZ(
			CurrentState::getInstance()->getZ() + zStepsNeeded);

	digitalWrite(X_ENABLE_PIN, LOW);
	digitalWrite(Y_ENABLE_PIN, LOW);
	digitalWrite(Z_ENABLE_PIN, LOW);

	while (xStepsNeeded != 0 || yStepsNeeded != 0 || zStepsNeeded != 0) {
		if (xStepsNeeded != 0) {
			digitalWrite(X_STEP_PIN, HIGH);
		}
		if (yStepsNeeded != 0) {
			digitalWrite(Y_STEP_PIN, HIGH);
		}
		if (zStepsNeeded != 0) {
			digitalWrite(Z_STEP_PIN, HIGH);
		}
		delay(5);
		if (xStepsNeeded != 0) {
			digitalWrite(X_STEP_PIN, LOW);
			xStepsNeeded = adjustStepAmount(xStepsNeeded);
		}
		if (yStepsNeeded != 0) {
			digitalWrite(Y_STEP_PIN, LOW);
			yStepsNeeded = adjustStepAmount(yStepsNeeded);
		}
		if (zStepsNeeded != 0) {
			digitalWrite(Z_STEP_PIN, LOW);
			zStepsNeeded = adjustStepAmount(zStepsNeeded);
		}

	}
	if(LOGGING) {
		CurrentState::getInstance()->print();
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "dualnumberarray.h"
#include <iostream>
#include <masa.h>

typedef double RawScalar;

template <std::size_t NDIM, typename Scalar>
void evaluate_q (const NumberArray<NDIM, Scalar>& xyz);

using namespace MASA;

int main(void)
{
  int err = 0;

  const unsigned int NDIM = 2;

  const RawScalar xvecinit[] = {1., 0.};
  const RawScalar yvecinit[] = {0., 1.};

  const NumberArray<NDIM, RawScalar> xvec(xvecinit);
  const NumberArray<NDIM, RawScalar> yvec(yvecinit);

  typedef DualNumber<RawScalar, NumberArray<NDIM, RawScalar> > FirstDerivType;
  typedef DualNumber<FirstDerivType, NumberArray<NDIM, FirstDerivType> > SecondDerivType;

  typedef SecondDerivType ADType;
  // typedef FirstDerivType ADType;

  // initialize the problem in MASA
  err += masa_init("euler-maple","euler_2d");

  // call the sanity check routine
  // (tests that all variables have been initialized)
  err += masa_sanity_check();
  err += masa_printid<double>();

  // set up array
  NumberArray<NDIM, ADType> xy;
  xy[0] = ADType(1., xvec);
  xy[1] = ADType(1., yvec);

  // evaluate source terms
  evaluate_q(xy);

}

// Note: ADScalar needs to be a FirstDerivType or better since we have
// first derivatives here.  Adding diffusion will require a
// SecondDerivType or better

template <std::size_t NDIM, typename ADScalar>
void evaluate_q (const NumberArray<NDIM, ADScalar>& xyz)
{
  typedef typename RawType<ADScalar>::value_type Scalar;

  const Scalar PI = std::acos(Scalar(-1));

  const Scalar k = 1.38;
  const Scalar u_0 = 200.23;
  const Scalar u_x = 1.1;
  const Scalar u_y = 1.08;
  const Scalar v_0 = 1.2;
  const Scalar v_x = 1.6;
  const Scalar v_y = .47;
  const Scalar rho_0 = 100.02;
  const Scalar rho_x = 2.22;
  const Scalar rho_y = 0.8;
  const Scalar p_0 = 150.2;
  const Scalar p_x = .91;
  const Scalar p_y = .623;
  const Scalar a_px = .165;
  const Scalar a_py = .612;
  const Scalar a_rhox = 1.0;
  const Scalar a_rhoy = 1.0;
  const Scalar a_ux = .1987;
  const Scalar a_uy = 1.189;
  const Scalar a_vx = 1.91;
  const Scalar a_vy = 1.0;
  const Scalar Gamma = 1.01;
  const Scalar mu = .918;
  const Scalar L = 3.02;

  const ADScalar& x = xyz[0];
  const ADScalar& y = xyz[1];

  // Treat velocity as a vector
  NumberArray<NDIM, ADScalar> U;

  // Arbitrary manufactured solution
  U[0] = u_0 + u_x * std::sin(a_ux * PI * x / L) + u_y * std::cos(a_uy * PI * y / L);
  U[1] = v_0 + v_x * std::cos(a_vx * PI * x / L) + v_y * std::sin(a_vy * PI * y / L);
  ADScalar RHO = rho_0 + rho_x * std::sin(a_rhox * PI * x / L) + rho_y * std::cos(a_rhoy * PI * y / L);
  ADScalar P = p_0 + p_x * std::cos(a_px * PI * x / L) + p_y * std::sin(a_py * PI * y / L);

  // Perfect gas energies
  ADScalar E = 1./(Gamma-1.)*P/RHO;
  ADScalar ET = E + .5 * U.dot(U);

  // Euler equation residuals
  Scalar Q_rho = raw_value(divergence(U));
  NumberArray<NDIM, Scalar> Q_rho_u = raw_value(divergence(RHO*U.outerproduct(U)) + P.derivatives());
  Scalar Q_rho_e = raw_value(divergence((RHO*ET+P)*U));

//  std::cout << f;
}
<commit_msg>[masa]: adding roys notes to code<commit_after>#include "dualnumberarray.h"
#include <iostream>
#include <masa.h>

typedef double RawScalar;

template <std::size_t NDIM, typename Scalar>
void evaluate_q (const NumberArray<NDIM, Scalar>& xyz);

using namespace MASA;

int main(void)
{
  int err = 0;

  const unsigned int NDIM = 2;

  const RawScalar xvecinit[] = {1., 0.};
  const RawScalar yvecinit[] = {0., 1.};

  const NumberArray<NDIM, RawScalar> xvec(xvecinit);
  const NumberArray<NDIM, RawScalar> yvec(yvecinit);

  typedef DualNumber<RawScalar, NumberArray<NDIM, RawScalar> > FirstDerivType;
  typedef DualNumber<FirstDerivType, NumberArray<NDIM, FirstDerivType> > SecondDerivType;

  typedef SecondDerivType ADType;
  // typedef FirstDerivType ADType;

  // initialize the problem in MASA
  err += masa_init("euler-maple","euler_2d");

  // call the sanity check routine
  // (tests that all variables have been initialized)
  err += masa_sanity_check();
  err += masa_printid<double>();

  // we first set up the DualNumber::derivatives() terms.
  // When main() says "xy[0] = ADType(1., xvec);", that's saying "x = 1, and
  // the gradient of f(x,y)=x is the constant vector xvec={1,0}"
  // Likewise "xy[1] = ADType(1., yvec);" means "y = 1, and the gradient of f(x,y)=y
  // is the constant vector yvec={0,1}"
  NumberArray<NDIM, ADType> xy;
  xy[0] = ADType(1., xvec);
  xy[1] = ADType(1., yvec);

  // the input argument xyz is another NumberArray
  // a vector just like Q_rho_u, a spatial location rather
  // than a vector-valued forcing function.
  double h = 1.0/N;
  for (int i=0; i != N+1; ++i)
    {
      xy[0] = ADType(i*h,xvec);
      for (int j=0; j != N+1; ++j)
	{
	  xy[1] = ADType(j*h,yvec);
	  do_my_test(xy);
	}
    }

  // evaluate source terms
  evaluate_q(xy);

}

// Note: ADScalar needs to be a FirstDerivType or better since we have
// first derivatives here.  Adding diffusion will require a
// SecondDerivType or better

template <std::size_t NDIM, typename ADScalar>
void evaluate_q (const NumberArray<NDIM, ADScalar>& xyz)
{
  typedef typename RawType<ADScalar>::value_type Scalar;

  const Scalar PI = std::acos(Scalar(-1));

  const Scalar k = 1.38;
  const Scalar u_0 = 200.23;
  const Scalar u_x = 1.1;
  const Scalar u_y = 1.08;
  const Scalar v_0 = 1.2;
  const Scalar v_x = 1.6;
  const Scalar v_y = .47;
  const Scalar rho_0 = 100.02;
  const Scalar rho_x = 2.22;
  const Scalar rho_y = 0.8;
  const Scalar p_0 = 150.2;
  const Scalar p_x = .91;
  const Scalar p_y = .623;
  const Scalar a_px = .165;
  const Scalar a_py = .612;
  const Scalar a_rhox = 1.0;
  const Scalar a_rhoy = 1.0;
  const Scalar a_ux = .1987;
  const Scalar a_uy = 1.189;
  const Scalar a_vx = 1.91;
  const Scalar a_vy = 1.0;
  const Scalar Gamma = 1.01;
  const Scalar mu = .918;
  const Scalar L = 3.02;

  const ADScalar& x = xyz[0];
  const ADScalar& y = xyz[1];

  // Treat velocity as a vector
  NumberArray<NDIM, ADScalar> U;

  // Arbitrary manufactured solution
  U[0] = u_0 + u_x * std::sin(a_ux * PI * x / L) + u_y * std::cos(a_uy * PI * y / L);
  U[1] = v_0 + v_x * std::cos(a_vx * PI * x / L) + v_y * std::sin(a_vy * PI * y / L);
  ADScalar RHO = rho_0 + rho_x * std::sin(a_rhox * PI * x / L) + rho_y * std::cos(a_rhoy * PI * y / L);
  ADScalar P = p_0 + p_x * std::cos(a_px * PI * x / L) + p_y * std::sin(a_py * PI * y / L);

  // Perfect gas energies
  ADScalar E = 1./(Gamma-1.)*P/RHO;
  ADScalar ET = E + .5 * U.dot(U);

  // Euler equation residuals
  Scalar Q_rho = raw_value(divergence(U));
  NumberArray<NDIM, Scalar> Q_rho_u = raw_value(divergence(RHO*U.outerproduct(U)) + P.derivatives());
  Scalar Q_rho_e = raw_value(divergence((RHO*ET+P)*U));

//  std::cout << f;
}
<|endoftext|>


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

#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {
  ASSERT_TRUE(StartTestServer());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("incognito")
      .AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result));
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("content_scripts")
      .AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result));
  EXPECT_TRUE(result);
}

// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
  ASSERT_TRUE(RunExtensionTestIncognito(
      "incognito/dont_create_profile")) << message_;
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}

// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
// Hangs flakily on mac, linux, win: http://crbug.com/53991
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  // Wait for both extensions to be ready before telling them to proceed.
  ExtensionTestMessageListener listener("waiting", true);
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  ExtensionTestMessageListener listener_incognito("waiting", true);
  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
  listener.Reply("go");
  listener_incognito.Reply("go");

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Mark ExtensionApiTest.Incognito as FLAKY.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {
  ASSERT_TRUE(StartTestServer());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("incognito")
      .AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result));
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("content_scripts")
      .AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result));
  EXPECT_TRUE(result);
}

// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
  ASSERT_TRUE(RunExtensionTestIncognito(
      "incognito/dont_create_profile")) << message_;
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}

// Tests that the APIs in an incognito-enabled extension work properly.
// Flaky - see crbug.com/77951.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
// Hangs flakily on mac, linux, win: http://crbug.com/53991
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  // Wait for both extensions to be ready before telling them to proceed.
  ExtensionTestMessageListener listener("waiting", true);
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  ExtensionTestMessageListener listener_incognito("waiting", true);
  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
  listener.Reply("go");
  listener_incognito.Reply("go");

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>


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

#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

// Disabled, http://crbug.com/91058.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebSocket) {
  FilePath websocket_root_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));

  ui_test_utils::TestWebSocketServer server;
  ASSERT_TRUE(server.Start(websocket_root_dir));
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<commit_msg>Re-enable ExtensionApiTest.WebSocket.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {
  FilePath websocket_root_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));

  ui_test_utils::TestWebSocketServer server;
  ASSERT_TRUE(server.Start(websocket_root_dir));
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkEventMapper.h"
#include "mitkPositionEvent.h"
#include "mitkGlobalInteraction.h"
#include "mitkDisplayPositionEvent.h"
#include "mitkWeakPointerProperty.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkSliceNavigationController.h"
#include "mitkStatusBar.h"
#include "mitkInteractionConst.h"
#include <vtkTransform.h>

//##ModelId=3E3D2F120050
mitk::BaseRenderer::BaseRenderer() :
  m_MapperID(defaultMapper), m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_CameraController(NULL), m_Focused(false),
  m_WorldGeometry(NULL), m_TimeSlicedWorldGeometry(NULL), m_CurrentWorldGeometry2D(NULL), m_Slice(0), m_TimeStep(0)
{
  m_Size[0] = 0;
  m_Size[1] = 0;

  //adding this BaseRenderer to the List of all BaseRenderer
  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());
  if (globalInteraction != NULL)
	{
    globalInteraction->AddFocusElement(this);
  }

  WeakPointerProperty::Pointer rendererProp = new WeakPointerProperty((itk::Object*)this);

  m_CurrentWorldGeometry2D = mitk::PlaneGeometry::New();

  m_CurrentWorldGeometry2DData = mitk::Geometry2DData::New();
  m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);
  m_CurrentWorldGeometry2DNode = mitk::DataTreeNode::New();
  m_CurrentWorldGeometry2DNode->SetData(m_CurrentWorldGeometry2DData);
  m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_CurrentWorldGeometry2DTransformTime = m_CurrentWorldGeometry2DNode->GetVtkTransform()->GetMTime();

  m_DisplayGeometry = mitk::DisplayGeometry::New();
  m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);
  m_DisplayGeometryData = mitk::Geometry2DData::New();
  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
  m_DisplayGeometryNode = mitk::DataTreeNode::New();
  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);
  m_DisplayGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();
}

//##ModelId=3E3D2F12008C
mitk::BaseRenderer::~BaseRenderer()
{
  m_DataTreeIterator = NULL;
}

//##ModelId=3D6A1791038B
void mitk::BaseRenderer::SetData(const mitk::DataTreeIteratorBase* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    if (iterator != NULL)
      m_DataTreeIterator = iterator;
    else
      m_DataTreeIterator = NULL;
    Modified();
  }
}

//##ModelId=3E330C4D0395
const MapperSlotId mitk::BaseRenderer::defaultMapper = 1;

//##ModelId=3E33162C00D0
void mitk::BaseRenderer::Paint()
{
}

//##ModelId=3E331632031E
void mitk::BaseRenderer::Initialize()
{
}

//##ModelId=3E33163703D9
void mitk::BaseRenderer::Resize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;

  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  //@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E33163A0261
void mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  m_RenderWindow = renderwindow;
}

//##ModelId=3E3799250397
void mitk::BaseRenderer::InitSize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);
  GetDisplayGeometry()->Fit();
}

void mitk::BaseRenderer::SetSlice(unsigned int slice)
{
  if(m_Slice!=slice)
  {
    m_Slice = slice;
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        if(m_Slice >= slicedWorldGeometry->GetSlices())
          m_Slice = slicedWorldGeometry->GetSlices()-1;
        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
        m_CurrentWorldGeometry = slicedWorldGeometry;
      }
    }
    else
      Modified();
  }
}

void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep)
{
  if(m_TimeStep!=timeStep)
  {
    m_TimeStep = timeStep;
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
        m_CurrentWorldGeometry = slicedWorldGeometry;
      }
    }
    else
      Modified();
  }
}

//##ModelId=3E66CC590379
void mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry)
{
  itkDebugMacro("setting WorldGeometry to " << geometry);

  if(m_WorldGeometry != geometry)
  {
    m_WorldGeometry = geometry;
    m_TimeSlicedWorldGeometry=dynamic_cast<TimeSlicedGeometry*>(geometry);
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      itkDebugMacro("setting TimeSlicedWorldGeometry to " << m_TimeSlicedWorldGeometry);
      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        if(m_Slice >= slicedWorldGeometry->GetSlices())
          m_Slice = slicedWorldGeometry->GetSlices()-1;
      }
      assert(slicedWorldGeometry!=NULL); //only as long as the todo described in SetWorldGeometry is not done
      SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); // calls Modified()
      m_CurrentWorldGeometry = slicedWorldGeometry;
    }
    else
    {
      Geometry2D* geometry2d=dynamic_cast<Geometry2D*>(geometry);
      SetCurrentWorldGeometry2D(geometry2d);
      m_CurrentWorldGeometry = geometry2d;
      Modified();
    }
  }
  if(m_CurrentWorldGeometry2D.IsNull())
    itkWarningMacro("m_CurrentWorldGeometry2D is NULL");
}

//##ModelId=3E66CC59026B
void mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)
{
  itkDebugMacro("setting DisplayGeometry to " << geometry2d);
  if (m_DisplayGeometry != geometry2d)
  {
    m_DisplayGeometry = geometry2d;
    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
    m_DisplayGeometryUpdateTime.Modified();
    Modified();
  }
}

void mitk::BaseRenderer::SetCurrentWorldGeometry2D(mitk::Geometry2D* geometry2d)
{
  if (m_CurrentWorldGeometry2D != geometry2d)
  {
    m_CurrentWorldGeometry2D = geometry2d;
    m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);
    m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);
    m_CurrentWorldGeometry2DUpdateTime.Modified();
    Modified();
  }
}

void mitk::BaseRenderer::SetGeometry(const itk::EventObject & geometrySendEvent)
{
  const SliceNavigationController::GeometrySendEvent* sendEvent =
    dynamic_cast<const SliceNavigationController::GeometrySendEvent *>(&geometrySendEvent);

  assert(sendEvent !=NULL);
  SetWorldGeometry(sendEvent ->GetTimeSlicedGeometry());
}

void mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject & geometrySliceEvent)
{
  const SliceNavigationController::GeometrySliceEvent* sliceEvent =
    dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent);

  assert(sliceEvent!=NULL);
  SetSlice(sliceEvent->GetPos());
}

void mitk::BaseRenderer::SetGeometryTime(const itk::EventObject & geometryTimeEvent)
{
  const SliceNavigationController::GeometryTimeEvent * timeEvent =
    dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent);

  assert(timeEvent!=NULL);
  SetTimeStep(timeEvent->GetPos());
}

//##ModelId=3E6D5DD30322
void mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)
{
  //set the Focus on the renderer
  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());
  if (globalInteraction != NULL)
  {
    bool success = globalInteraction->SetFocus(this);
    if (! success)
      mitk::StatusBar::DisplayText("Warning! from mitkBaseRenderer.cpp: Couldn't focus this BaseRenderer!");
  }

  if (m_CameraController)
  {
    if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MousePressEvent(me);
  }
  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());

    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
//    std::cout << "press event!" << std::endl;
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

//##ModelId=3E6D5DD30372
void mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
  {
    if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MouseReleaseEvent(me);
  }

  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

//##ModelId=3E6D5DD303C2
void mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
  {
    if((me->GetButtonState()<=512) || (me->GetButtonState()>=516))// provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MouseMoveEvent(me);
  }
  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

void mitk::BaseRenderer::PickWorldPoint(const mitk::Point2D& displayPoint, mitk::Point3D& worldPoint) const
{
  mitk::Point2D worldPoint2D;
  GetDisplayGeometry()->DisplayToMM(displayPoint, worldPoint2D);
  GetDisplayGeometry()->Map(worldPoint2D, worldPoint);
}

void mitk::BaseRenderer::WheelEvent(mitk::WheelEvent *we)
{
  //mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());
  //mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3E6D5DD4002A
void mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)
{
  if (m_CameraController)
    m_CameraController->KeyPressEvent(ke);
  mitk::Event event(this, ke->type(), BS_NoButton, BS_NoButton, ke->key());
  mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3EF1627503C4
void mitk::BaseRenderer::MakeCurrent()
{
}
<commit_msg>FIX: bug #25: BaseRenderer::Resize has to tell m_CameraController the new size<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkEventMapper.h"
#include "mitkPositionEvent.h"
#include "mitkGlobalInteraction.h"
#include "mitkDisplayPositionEvent.h"
#include "mitkWeakPointerProperty.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkSliceNavigationController.h"
#include "mitkStatusBar.h"
#include "mitkInteractionConst.h"
#include <vtkTransform.h>

//##ModelId=3E3D2F120050
mitk::BaseRenderer::BaseRenderer() :
  m_MapperID(defaultMapper), m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_CameraController(NULL), m_Focused(false),
  m_WorldGeometry(NULL), m_TimeSlicedWorldGeometry(NULL), m_CurrentWorldGeometry2D(NULL), m_Slice(0), m_TimeStep(0)
{
  m_Size[0] = 0;
  m_Size[1] = 0;

  //adding this BaseRenderer to the List of all BaseRenderer
  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());
  if (globalInteraction != NULL)
	{
    globalInteraction->AddFocusElement(this);
  }

  WeakPointerProperty::Pointer rendererProp = new WeakPointerProperty((itk::Object*)this);

  m_CurrentWorldGeometry2D = mitk::PlaneGeometry::New();

  m_CurrentWorldGeometry2DData = mitk::Geometry2DData::New();
  m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);
  m_CurrentWorldGeometry2DNode = mitk::DataTreeNode::New();
  m_CurrentWorldGeometry2DNode->SetData(m_CurrentWorldGeometry2DData);
  m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_CurrentWorldGeometry2DTransformTime = m_CurrentWorldGeometry2DNode->GetVtkTransform()->GetMTime();

  m_DisplayGeometry = mitk::DisplayGeometry::New();
  m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);
  m_DisplayGeometryData = mitk::Geometry2DData::New();
  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
  m_DisplayGeometryNode = mitk::DataTreeNode::New();
  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);
  m_DisplayGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();
}

//##ModelId=3E3D2F12008C
mitk::BaseRenderer::~BaseRenderer()
{
  m_DataTreeIterator = NULL;
}

//##ModelId=3D6A1791038B
void mitk::BaseRenderer::SetData(const mitk::DataTreeIteratorBase* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    if (iterator != NULL)
      m_DataTreeIterator = iterator;
    else
      m_DataTreeIterator = NULL;
    Modified();
  }
}

//##ModelId=3E330C4D0395
const MapperSlotId mitk::BaseRenderer::defaultMapper = 1;

//##ModelId=3E33162C00D0
void mitk::BaseRenderer::Paint()
{
}

//##ModelId=3E331632031E
void mitk::BaseRenderer::Initialize()
{
}

//##ModelId=3E33163703D9
void mitk::BaseRenderer::Resize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;

  if(m_CameraController)
    m_CameraController->Resize(w, h);

  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  //@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E33163A0261
void mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  m_RenderWindow = renderwindow;
}

//##ModelId=3E3799250397
void mitk::BaseRenderer::InitSize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);
  GetDisplayGeometry()->Fit();
}

void mitk::BaseRenderer::SetSlice(unsigned int slice)
{
  if(m_Slice!=slice)
  {
    m_Slice = slice;
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        if(m_Slice >= slicedWorldGeometry->GetSlices())
          m_Slice = slicedWorldGeometry->GetSlices()-1;
        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
        m_CurrentWorldGeometry = slicedWorldGeometry;
      }
    }
    else
      Modified();
  }
}

void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep)
{
  if(m_TimeStep!=timeStep)
  {
    m_TimeStep = timeStep;
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));
        m_CurrentWorldGeometry = slicedWorldGeometry;
      }
    }
    else
      Modified();
  }
}

//##ModelId=3E66CC590379
void mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry)
{
  itkDebugMacro("setting WorldGeometry to " << geometry);

  if(m_WorldGeometry != geometry)
  {
    m_WorldGeometry = geometry;
    m_TimeSlicedWorldGeometry=dynamic_cast<TimeSlicedGeometry*>(geometry);
    if(m_TimeSlicedWorldGeometry.IsNotNull())
    {
      itkDebugMacro("setting TimeSlicedWorldGeometry to " << m_TimeSlicedWorldGeometry);
      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())
        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;
      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));
      if(slicedWorldGeometry!=NULL)
      {
        if(m_Slice >= slicedWorldGeometry->GetSlices())
          m_Slice = slicedWorldGeometry->GetSlices()-1;
      }
      assert(slicedWorldGeometry!=NULL); //only as long as the todo described in SetWorldGeometry is not done
      SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); // calls Modified()
      m_CurrentWorldGeometry = slicedWorldGeometry;
    }
    else
    {
      Geometry2D* geometry2d=dynamic_cast<Geometry2D*>(geometry);
      SetCurrentWorldGeometry2D(geometry2d);
      m_CurrentWorldGeometry = geometry2d;
      Modified();
    }
  }
  if(m_CurrentWorldGeometry2D.IsNull())
    itkWarningMacro("m_CurrentWorldGeometry2D is NULL");
}

//##ModelId=3E66CC59026B
void mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)
{
  itkDebugMacro("setting DisplayGeometry to " << geometry2d);
  if (m_DisplayGeometry != geometry2d)
  {
    m_DisplayGeometry = geometry2d;
    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
    m_DisplayGeometryUpdateTime.Modified();
    Modified();
  }
}

void mitk::BaseRenderer::SetCurrentWorldGeometry2D(mitk::Geometry2D* geometry2d)
{
  if (m_CurrentWorldGeometry2D != geometry2d)
  {
    m_CurrentWorldGeometry2D = geometry2d;
    m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);
    m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);
    m_CurrentWorldGeometry2DUpdateTime.Modified();
    Modified();
  }
}

void mitk::BaseRenderer::SetGeometry(const itk::EventObject & geometrySendEvent)
{
  const SliceNavigationController::GeometrySendEvent* sendEvent =
    dynamic_cast<const SliceNavigationController::GeometrySendEvent *>(&geometrySendEvent);

  assert(sendEvent !=NULL);
  SetWorldGeometry(sendEvent ->GetTimeSlicedGeometry());
}

void mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject & geometrySliceEvent)
{
  const SliceNavigationController::GeometrySliceEvent* sliceEvent =
    dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent);

  assert(sliceEvent!=NULL);
  SetSlice(sliceEvent->GetPos());
}

void mitk::BaseRenderer::SetGeometryTime(const itk::EventObject & geometryTimeEvent)
{
  const SliceNavigationController::GeometryTimeEvent * timeEvent =
    dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent);

  assert(timeEvent!=NULL);
  SetTimeStep(timeEvent->GetPos());
}

//##ModelId=3E6D5DD30322
void mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)
{
  //set the Focus on the renderer
  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());
  if (globalInteraction != NULL)
  {
    bool success = globalInteraction->SetFocus(this);
    if (! success)
      mitk::StatusBar::DisplayText("Warning! from mitkBaseRenderer.cpp: Couldn't focus this BaseRenderer!");
  }

  if (m_CameraController)
  {
    if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MousePressEvent(me);
  }
  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());

    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
//    std::cout << "press event!" << std::endl;
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

//##ModelId=3E6D5DD30372
void mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
  {
    if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MouseReleaseEvent(me);
  }

  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

//##ModelId=3E6D5DD303C2
void mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
  {
    if((me->GetButtonState()<=512) || (me->GetButtonState()>=516))// provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine
      m_CameraController->MouseMoveEvent(me);
  }
  if(m_MapperID==1)
  {
    Point2D p(me->GetDisplayPosition());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->GetDisplayPosition());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    me->SetDisplayPosition(p);
    mitk::EventMapper::MapEvent(me);
  }
}

void mitk::BaseRenderer::PickWorldPoint(const mitk::Point2D& displayPoint, mitk::Point3D& worldPoint) const
{
  mitk::Point2D worldPoint2D;
  GetDisplayGeometry()->DisplayToMM(displayPoint, worldPoint2D);
  GetDisplayGeometry()->Map(worldPoint2D, worldPoint);
}

void mitk::BaseRenderer::WheelEvent(mitk::WheelEvent *we)
{
  //mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());
  //mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3E6D5DD4002A
void mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)
{
  if (m_CameraController)
    m_CameraController->KeyPressEvent(ke);
  mitk::Event event(this, ke->type(), BS_NoButton, BS_NoButton, ke->key());
  mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3EF1627503C4
void mitk::BaseRenderer::MakeCurrent()
{
}
<|endoftext|>