<commit_before>#include <rxx.h>

#include <usenet.h>
#include <group.h>

grouplist::grouplist ()
{
  it = group_db->enumerate();
  d = it->nextElement();
};

static rxx listrx ("^(\\d+)(<[^>]+>)([^:]+):");

void
grouplist::next (str *f, unsigned long *i)
{
  ptr<dbrec> data = group_db->lookup (d->key);
  char *c = data->value;
  int len = data->len, cnt = 0;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) )
    cnt++;

  *f = str (d->key->value, d->key->len);
  *i = cnt;
  d = it->nextElement();
}

newsgroup::newsgroup () :
  rec (NULL),
  cur_art (0),
  start (0),
  stop (0),
  c (NULL),
  len (0)
{
}

int
newsgroup::open (str g)
{
  rec = group_db->lookup (New refcounted<dbrec> (g, g.len ()));
  if (rec == NULL)
    return -1;

  warn << "group " << g << " rec len " << rec->len << "\n";

  group_name = g;
  cur_art = 1;

  return 0;
}

int
newsgroup::open (str g, unsigned long *count,
	     unsigned long *first, unsigned long *last)
{
  if (open (g) < 0)
    return -1;

  char *c = rec->value;
  int len = rec->len;
  warn << "xv " << str (c, len) << "\n";
  *count = 0;
  *first = 0;
  *last = 0;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) ) {
    if (*count == 0)
      *first = strtoul (listrx[1], NULL, 10);
    (*count)++;
    *last = strtoul (listrx[1], NULL, 10);
  }

  return 0;
}

static rxx listrxend ("(\\d+)(<[^>]+>)([^:]+):$");

void
newsgroup::addid (str msgid, chordID ID)
{
  assert (rec);
  str old (rec->value, rec->len), updated;
  ptr<dbrec> k = New refcounted<dbrec> (group_name, group_name.len ());

  if (listrxend.search (old))
    updated = strbuf () << old <<
      strtoul (listrxend[1], NULL, 10) + 1 << msgid << ID << ":";
  else
    updated = strbuf () << "1" << msgid << ID << ":";

  rec = New refcounted<dbrec> (updated, updated.len ());

  group_db->insert (k, rec);
}

// now returns the chordid
chordID
newsgroup::getid (unsigned long index)
{
  if (rec == NULL)
    return 0;

  char *c = rec->value;
  int len = rec->len;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) ) {
    if (index == strtoul (listrx[1], NULL, 10))
      return bigint (listrx[3], 16);
    else if (index < strtoul (listrx[1], NULL, 10))
      return 0;
  }

  return 0;
}

static rxx getchordid ("^X-ChordID: (.+)$", "m");
chordID
newsgroup::getid (str msgid)
{
  ptr<dbrec> key, d;

  key = New refcounted<dbrec> (msgid, msgid.len ());
  d = header_db->lookup (key);

  if (d && getchordid.search (str (d->value, d->len)))
    return bigint (getchordid[1], 16);
  else
    return 0;
}

void
newsgroup::xover (unsigned long a, unsigned long b)
{
  start = a;
  stop = b;

  assert (rec);
  c = rec->value;
  len = rec->len;
  while (listrx.search (str (c, len)) &&
	 (strtoul (listrx[1], NULL, 10) < start))
    c += listrx.len (0), len -= listrx.len (0);
}

static rxx oversub ("Subject: (.+)\\r");
static rxx overfrom ("From: (.+)\\r");
static rxx overdate ("Date: (.+)\\r");
static rxx overmsgid ("Message-ID: (.+)\\r");
static rxx overref ("References: (.+)\\r");
static rxx overlines ("X-Lines: (.+)\\r");

str
tabfilter (str f)
{
  unsigned int i;
  strbuf out;

  for (i=0; i<f.len (); i++)
    if (f[i] == '\t')
      out << " ";
    else
      out.tosuio ()->copy (f.cstr() + i, 1); // xxx bleh

  return str (out);
}

// format: "subject\tauthor\tdate\t<msgid>\treferences\tsize\tlines"
strbuf
newsgroup::next (void)
{
  ptr<dbrec> art;
  strbuf resp;
  resp << start << "\t";

  if (more () && len > 0 &&
      listrx.search (str (c, len))) {
    art = header_db->lookup(New refcounted<dbrec> (listrx[2],
						   listrx[2].len ()));

    warn << "mgs " << listrx[2] << "\n";
    warn << "header " << str (art->value, art->len) << "\n";

    if (art == NULL)
      warn << "missing article\n";
    else {
      str msg (art->value, art->len); // xxx
      if (oversub.search (msg) &&
	  overfrom.search (msg) &&
	  overdate.search (msg)) {
	resp << tabfilter (oversub[1]) << "\t"
	     << tabfilter (overfrom[1]) << "\t";
	resp << tabfilter (overdate[1]) << "\t";

	if (overmsgid.search (msg))
	  resp << tabfilter (overmsgid[1]) << "\t";
	else
	  resp << tabfilter (listrx[2]) << "\t";
	if (overref.search (msg))
	  resp << tabfilter (overref[1]);
	resp << "\t" << art->len << "\t";
	if (overlines.search (msg))
	  resp << tabfilter (overlines[1]);
	else
	  resp << "0";
      } else
	warn << "msg parse error\n";
    }

    c += listrx.len (0);
    len -= listrx.len (0);
  }

  start++;
  resp << "\t\r\n";
  return resp;
}
<commit_msg>Less verbose in the safe case.  Avoid a null pointer deref in the process. Clean up the output sent to the remote end in the case of missing articles.<commit_after>#include <rxx.h>

#include <usenet.h>
#include <group.h>

grouplist::grouplist ()
{
  it = group_db->enumerate();
  d = it->nextElement();
};

static rxx listrx ("^(\\d+)(<[^>]+>)([^:]+):");

void
grouplist::next (str *f, unsigned long *i)
{
  ptr<dbrec> data = group_db->lookup (d->key);
  char *c = data->value;
  int len = data->len, cnt = 0;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) )
    cnt++;

  *f = str (d->key->value, d->key->len);
  *i = cnt;
  d = it->nextElement();
}

newsgroup::newsgroup () :
  rec (NULL),
  cur_art (0),
  start (0),
  stop (0),
  c (NULL),
  len (0)
{
}

int
newsgroup::open (str g)
{
  rec = group_db->lookup (New refcounted<dbrec> (g, g.len ()));
  if (rec == NULL)
    return -1;

  warn << "group " << g << " rec len " << rec->len << "\n";

  group_name = g;
  cur_art = 1;

  return 0;
}

int
newsgroup::open (str g, unsigned long *count,
	     unsigned long *first, unsigned long *last)
{
  if (open (g) < 0)
    return -1;

  char *c = rec->value;
  int len = rec->len;
  warn << "xv " << str (c, len) << "\n";
  *count = 0;
  *first = 0;
  *last = 0;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) ) {
    if (*count == 0)
      *first = strtoul (listrx[1], NULL, 10);
    (*count)++;
    *last = strtoul (listrx[1], NULL, 10);
  }

  return 0;
}

static rxx listrxend ("(\\d+)(<[^>]+>)([^:]+):$");

void
newsgroup::addid (str msgid, chordID ID)
{
  assert (rec);
  str old (rec->value, rec->len), updated;
  ptr<dbrec> k = New refcounted<dbrec> (group_name, group_name.len ());

  if (listrxend.search (old))
    updated = strbuf () << old <<
      strtoul (listrxend[1], NULL, 10) + 1 << msgid << ID << ":";
  else
    updated = strbuf () << "1" << msgid << ID << ":";

  rec = New refcounted<dbrec> (updated, updated.len ());

  group_db->insert (k, rec);
}

// now returns the chordid
chordID
newsgroup::getid (unsigned long index)
{
  if (rec == NULL)
    return 0;

  char *c = rec->value;
  int len = rec->len;

  for (; listrx.search (str (c, len))
       ; c += listrx.len (0), len -= listrx.len (0) ) {
    if (index == strtoul (listrx[1], NULL, 10))
      return bigint (listrx[3], 16);
    else if (index < strtoul (listrx[1], NULL, 10))
      return 0;
  }

  return 0;
}

static rxx getchordid ("^X-ChordID: (.+)$", "m");
chordID
newsgroup::getid (str msgid)
{
  ptr<dbrec> key, d;

  key = New refcounted<dbrec> (msgid, msgid.len ());
  d = header_db->lookup (key);

  if (d && getchordid.search (str (d->value, d->len)))
    return bigint (getchordid[1], 16);
  else
    return 0;
}

void
newsgroup::xover (unsigned long a, unsigned long b)
{
  start = a;
  stop = b;

  assert (rec);
  c = rec->value;
  len = rec->len;
  while (listrx.search (str (c, len)) &&
	 (strtoul (listrx[1], NULL, 10) < start))
    c += listrx.len (0), len -= listrx.len (0);
}

static rxx oversub ("Subject: (.+)\\r");
static rxx overfrom ("From: (.+)\\r");
static rxx overdate ("Date: (.+)\\r");
static rxx overmsgid ("Message-ID: (.+)\\r");
static rxx overref ("References: (.+)\\r");
static rxx overlines ("X-Lines: (.+)\\r");

str
tabfilter (str f)
{
  unsigned int i;
  strbuf out;

  for (i=0; i<f.len (); i++)
    if (f[i] == '\t')
      out << " ";
    else
      out.tosuio ()->copy (f.cstr() + i, 1); // xxx bleh

  return str (out);
}

// format: "subject\tauthor\tdate\t<msgid>\treferences\tsize\tlines"
strbuf
newsgroup::next (void)
{
  ptr<dbrec> art;
  strbuf resp;

  if (more () && len > 0 &&
      listrx.search (str (c, len)))
  {
    art = header_db->lookup(New refcounted<dbrec> (listrx[2],
						   listrx[2].len ()));
    if (art == NULL) {
      warn << "missing article " << start << "\n";
    } else {
      str msg (art->value, art->len); // xxx

      if (oversub.search (msg) &&
	  overfrom.search (msg) &&
	  overdate.search (msg)) {
	resp << start << "\t";
	resp << tabfilter (oversub[1]) << "\t"
	     << tabfilter (overfrom[1]) << "\t";
	resp << tabfilter (overdate[1]) << "\t";

	if (overmsgid.search (msg))
	  resp << tabfilter (overmsgid[1]) << "\t";
	else
	  resp << tabfilter (listrx[2]) << "\t";
	if (overref.search (msg))
	  resp << tabfilter (overref[1]);
	resp << "\t" << art->len << "\t";
	if (overlines.search (msg))
	  resp << tabfilter (overlines[1]);
	else
	  resp << "0";
      } else {
	warn << "msg parse error\n";
	warn << "msg " << listrx[2] << "\n";
	warn << "header " << msg << "\n";
      }
    }

    c += listrx.len (0);
    len -= listrx.len (0);
  }

  start++;
  resp << "\t\r\n";
  return resp;
}
<|endoftext|>


<commit_before>#include "yaml-cpp/yaml.h"
#include "yaml-cpp/eventhandler.h"
#include <fstream>
#include <iostream>
#include <vector>

struct Params {
	bool hasFile;
	std::string fileName;
};

Params ParseArgs(int argc, char **argv) {
	Params p;

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

	return p;
}

class NullEventHandler: public YAML::EventHandler
{
public:
	virtual void OnDocumentStart(const YAML::Mark&) {}
	virtual void OnDocumentEnd() {}

	virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {}
	virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {}
	virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {}

	virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
	virtual void OnSequenceEnd() {}

	virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
	virtual void OnMapEnd() {}
};

void parse(std::istream& input)
{
	try {
#if YAML_CPP_OLD_API
		YAML::Parser parser(input);
		YAML::Node doc;
		while(parser.GetNextDocument(doc)) {
			YAML::Emitter emitter;
			emitter << doc;
			std::cout << emitter.c_str() << "\n";
		}
#else
		// TODO: Parse with new API
#endif
	} catch(const YAML::Exception& e) {
		std::cerr << e.what() << "\n";
	}
}

int main(int argc, char **argv)
{
	Params p = ParseArgs(argc, argv);

	if(argc > 1) {
		std::ifstream fin;
		fin.open(argv[1]);
		parse(fin);
	} else {
		parse(std::cin);
	}

	return 0;
}
<commit_msg>Set up util/parse for the new API<commit_after>#include "yaml-cpp/yaml.h"
#include "yaml-cpp/eventhandler.h"
#include <fstream>
#include <iostream>
#include <vector>

struct Params {
	bool hasFile;
	std::string fileName;
};

Params ParseArgs(int argc, char **argv) {
	Params p;

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

	return p;
}

class NullEventHandler: public YAML::EventHandler
{
public:
	virtual void OnDocumentStart(const YAML::Mark&) {}
	virtual void OnDocumentEnd() {}

	virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {}
	virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {}
	virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {}

	virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
	virtual void OnSequenceEnd() {}

	virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {}
	virtual void OnMapEnd() {}
};

void parse(std::istream& input)
{
	try {
#if YAML_CPP_OLD_API
		YAML::Parser parser(input);
		YAML::Node doc;
		while(parser.GetNextDocument(doc)) {
			YAML::Emitter emitter;
			emitter << doc;
			std::cout << emitter.c_str() << "\n";
		}
#else
		YAML::Node doc = YAML::Parse(input);
		std::cout << doc << "\n";
#endif
	} catch(const YAML::Exception& e) {
		std::cerr << e.what() << "\n";
	}
}

int main(int argc, char **argv)
{
	Params p = ParseArgs(argc, argv);

	if(argc > 1) {
		std::ifstream fin;
		fin.open(argv[1]);
		parse(fin);
	} else {
		parse(std::cin);
	}

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fastos/fastos.h>
#include "default_tensor_engine.h"
#include <vespa/vespalib/eval/value.h>
#include <vespa/vespalib/eval/tensor_spec.h>
#include <vespa/vespalib/eval/operation_visitor.h>
#include "tensor.h"
#include "dense/dense_tensor_builder.h"
#include "default_tensor.h"

namespace vespalib {
namespace tensor {

using ErrorValue = eval::ErrorValue;
using DoubleValue = eval::DoubleValue;
using TensorValue = eval::TensorValue;

const DefaultTensorEngine DefaultTensorEngine::_engine;

eval::ValueType
DefaultTensorEngine::type_of(const Tensor &tensor) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    return my_tensor.getType().as_value_type();
}

bool
DefaultTensorEngine::equal(const Tensor &a, const Tensor &b) const
{
    assert(&a.engine() == this);
    assert(&b.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
    return my_a.equals(my_b);
}

vespalib::string
DefaultTensorEngine::to_string(const Tensor &tensor) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    return my_tensor.toString();
}

struct IsAddOperation : public eval::DefaultOperationVisitor {
    bool result = false;
    void visitDefault(const eval::Operation &) override {}
    void visit(const eval::operation::Add &) override { result = true; }
};

std::unique_ptr<eval::Tensor>
DefaultTensorEngine::create(const TensorSpec &spec) const
{
    ValueType type = ValueType::from_spec(spec.type());
    bool is_dense = false;
    bool is_sparse = false;
    for (const auto &dimension: type.dimensions()) {
        if (dimension.is_mapped()) {
            is_sparse = true;
        }
        if (dimension.is_indexed()) {
            is_dense = true;
        }
    }
    if (type.dimensions().empty()) {
        // XXX: should be number instead, but need to match empty sparse tensors elsewhere
        is_sparse = true;
    }
    assert(is_dense != is_sparse);
    if (is_dense) {
        DenseTensorBuilder builder;
        std::map<vespalib::string,DenseTensorBuilder::Dimension> dimension_map;
        for (const auto &dimension: type.dimensions()) {
            dimension_map[dimension.name] = builder.defineDimension(dimension.name, dimension.size);
        }
        for (const auto &cell: spec.cells()) {
            const auto &address = cell.first;
            for (const auto &binding: address) {
                builder.addLabel(dimension_map[binding.first], binding.second.index);
            }
            builder.addCell(cell.second);
        }
        return builder.build();
    } else { // sparse
        DefaultTensor::builder builder;
        std::map<vespalib::string,DefaultTensor::builder::Dimension> dimension_map;
        for (const auto &dimension: type.dimensions()) {
            dimension_map[dimension.name] = builder.define_dimension(dimension.name);
        }
        for (const auto &cell: spec.cells()) {
            const auto &address = cell.first;
            for (const auto &binding: address) {
                builder.add_label(dimension_map[binding.first], binding.second.name);
            }
            builder.add_cell(cell.second);
        }
        return builder.build();
    }
}

const eval::Value &
DefaultTensorEngine::reduce(const Tensor &tensor, const BinaryOperation &op, const std::vector<vespalib::string> &dimensions, Stash &stash) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    IsAddOperation check;
    op.accept(check);
    if (check.result) {
        if (dimensions.empty()) { // sum
            return stash.create<eval::DoubleValue>(my_tensor.sum());
        } else { // dimension sum
            tensor::Tensor::UP result;
            for (const auto &dimension: dimensions) {
                if (result) {
                    result = result->sum(dimension);
                } else {
                    result = my_tensor.sum(dimension);
                }
            }
            return stash.create<TensorValue>(std::move(result));
        }
    }
    return stash.create<ErrorValue>();
}

struct CellFunctionAdapter : tensor::CellFunction {
    const eval::UnaryOperation &op;
    CellFunctionAdapter(const eval::UnaryOperation &op_in) : op(op_in) {}
    virtual double apply(double value) const override { return op.eval(value); }
};

const eval::Value &
DefaultTensorEngine::map(const UnaryOperation &op, const Tensor &a, Stash &stash) const
{
    assert(&a.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    CellFunctionAdapter cell_function(op);
    return stash.create<TensorValue>(my_a.apply(cell_function));
}

struct TensorOperationOverride : eval::DefaultOperationVisitor {
    const tensor::Tensor &lhs;
    const tensor::Tensor &rhs;
    tensor::Tensor::UP result;
    TensorOperationOverride(const tensor::Tensor &lhs_in,
                            const tensor::Tensor &rhs_in)
        : lhs(lhs_in), rhs(rhs_in), result() {}
    virtual void visitDefault(const eval::Operation &) override {
        // empty result indicates error
    }
    virtual void visit(const eval::operation::Add &) override {
        result = lhs.add(rhs);
    }
    virtual void visit(const eval::operation::Sub &) override {
        result = lhs.subtract(rhs);
    }
    virtual void visit(const eval::operation::Mul &) override {
        if (lhs.getType() == rhs.getType()) {
            result = lhs.match(rhs);
        } else {
            result = lhs.multiply(rhs);
        }
    }
    virtual void visit(const eval::operation::Min &) override {
        result = lhs.min(rhs);
    }
    virtual void visit(const eval::operation::Max &) override {
        result = lhs.max(rhs);
    }
};

const eval::Value &
DefaultTensorEngine::apply(const BinaryOperation &op, const Tensor &a, const Tensor &b, Stash &stash) const
{
    assert(&a.engine() == this);
    assert(&b.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
    TensorOperationOverride tensor_override(my_a, my_b);
    op.accept(tensor_override);
    if (tensor_override.result) {
        return stash.create<TensorValue>(std::move(tensor_override.result));
    } else {
        return stash.create<ErrorValue>();
    }
}

} // namespace vespalib::tensor
} // namespace vespalib
<commit_msg>do not crash on unsupported functionality<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fastos/fastos.h>
#include "default_tensor_engine.h"
#include <vespa/vespalib/eval/value.h>
#include <vespa/vespalib/eval/tensor_spec.h>
#include <vespa/vespalib/eval/operation_visitor.h>
#include "tensor.h"
#include "dense/dense_tensor_builder.h"
#include "default_tensor.h"

namespace vespalib {
namespace tensor {

using ErrorValue = eval::ErrorValue;
using DoubleValue = eval::DoubleValue;
using TensorValue = eval::TensorValue;

const DefaultTensorEngine DefaultTensorEngine::_engine;

eval::ValueType
DefaultTensorEngine::type_of(const Tensor &tensor) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    return my_tensor.getType().as_value_type();
}

bool
DefaultTensorEngine::equal(const Tensor &a, const Tensor &b) const
{
    assert(&a.engine() == this);
    assert(&b.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
    if (my_a.getType().type() != my_b.getType().type()) {
        return false;
    }
    return my_a.equals(my_b);
}

vespalib::string
DefaultTensorEngine::to_string(const Tensor &tensor) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    return my_tensor.toString();
}

struct IsAddOperation : public eval::DefaultOperationVisitor {
    bool result = false;
    void visitDefault(const eval::Operation &) override {}
    void visit(const eval::operation::Add &) override { result = true; }
};

std::unique_ptr<eval::Tensor>
DefaultTensorEngine::create(const TensorSpec &spec) const
{
    ValueType type = ValueType::from_spec(spec.type());
    bool is_dense = false;
    bool is_sparse = false;
    for (const auto &dimension: type.dimensions()) {
        if (dimension.is_mapped()) {
            is_sparse = true;
        }
        if (dimension.is_indexed()) {
            is_dense = true;
        }
    }
    if (is_dense && is_sparse) {
        return DefaultTensor::builder().build();
    } else if (is_dense) {
        DenseTensorBuilder builder;
        std::map<vespalib::string,DenseTensorBuilder::Dimension> dimension_map;
        for (const auto &dimension: type.dimensions()) {
            dimension_map[dimension.name] = builder.defineDimension(dimension.name, dimension.size);
        }
        for (const auto &cell: spec.cells()) {
            const auto &address = cell.first;
            for (const auto &binding: address) {
                builder.addLabel(dimension_map[binding.first], binding.second.index);
            }
            builder.addCell(cell.second);
        }
        return builder.build();
    } else { // sparse
        DefaultTensor::builder builder;
        std::map<vespalib::string,DefaultTensor::builder::Dimension> dimension_map;
        for (const auto &dimension: type.dimensions()) {
            dimension_map[dimension.name] = builder.define_dimension(dimension.name);
        }
        for (const auto &cell: spec.cells()) {
            const auto &address = cell.first;
            for (const auto &binding: address) {
                builder.add_label(dimension_map[binding.first], binding.second.name);
            }
            builder.add_cell(cell.second);
        }
        return builder.build();
    }
}

const eval::Value &
DefaultTensorEngine::reduce(const Tensor &tensor, const BinaryOperation &op, const std::vector<vespalib::string> &dimensions, Stash &stash) const
{
    assert(&tensor.engine() == this);
    const tensor::Tensor &my_tensor = static_cast<const tensor::Tensor &>(tensor);
    IsAddOperation check;
    op.accept(check);
    if (check.result) {
        if (dimensions.empty()) { // sum
            return stash.create<eval::DoubleValue>(my_tensor.sum());
        } else { // dimension sum
            tensor::Tensor::UP result;
            for (const auto &dimension: dimensions) {
                if (result) {
                    result = result->sum(dimension);
                } else {
                    result = my_tensor.sum(dimension);
                }
            }
            return stash.create<TensorValue>(std::move(result));
        }
    }
    return stash.create<ErrorValue>();
}

struct CellFunctionAdapter : tensor::CellFunction {
    const eval::UnaryOperation &op;
    CellFunctionAdapter(const eval::UnaryOperation &op_in) : op(op_in) {}
    virtual double apply(double value) const override { return op.eval(value); }
};

const eval::Value &
DefaultTensorEngine::map(const UnaryOperation &op, const Tensor &a, Stash &stash) const
{
    assert(&a.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    CellFunctionAdapter cell_function(op);
    return stash.create<TensorValue>(my_a.apply(cell_function));
}

struct TensorOperationOverride : eval::DefaultOperationVisitor {
    const tensor::Tensor &lhs;
    const tensor::Tensor &rhs;
    tensor::Tensor::UP result;
    TensorOperationOverride(const tensor::Tensor &lhs_in,
                            const tensor::Tensor &rhs_in)
        : lhs(lhs_in), rhs(rhs_in), result() {}
    virtual void visitDefault(const eval::Operation &) override {
        // empty result indicates error
    }
    virtual void visit(const eval::operation::Add &) override {
        result = lhs.add(rhs);
    }
    virtual void visit(const eval::operation::Sub &) override {
        result = lhs.subtract(rhs);
    }
    virtual void visit(const eval::operation::Mul &) override {
        if (lhs.getType() == rhs.getType()) {
            result = lhs.match(rhs);
        } else {
            result = lhs.multiply(rhs);
        }
    }
    virtual void visit(const eval::operation::Min &) override {
        result = lhs.min(rhs);
    }
    virtual void visit(const eval::operation::Max &) override {
        result = lhs.max(rhs);
    }
};

const eval::Value &
DefaultTensorEngine::apply(const BinaryOperation &op, const Tensor &a, const Tensor &b, Stash &stash) const
{
    assert(&a.engine() == this);
    assert(&b.engine() == this);
    const tensor::Tensor &my_a = static_cast<const tensor::Tensor &>(a);
    const tensor::Tensor &my_b = static_cast<const tensor::Tensor &>(b);
    if (my_a.getType().type() != my_b.getType().type()) {
        return stash.create<ErrorValue>();
    }
    TensorOperationOverride tensor_override(my_a, my_b);
    op.accept(tensor_override);
    if (tensor_override.result) {
        return stash.create<TensorValue>(std::move(tensor_override.result));
    } else {
        return stash.create<ErrorValue>();
    }
}

} // namespace vespalib::tensor
} // namespace vespalib
<|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
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================

#include <cstdio>

#include "subsys/trackSystem/TrackSystem.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables

// idler
const ChVector<> TrackSystem::m_idlerPos(-2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);

// drive gear
const ChVector<> TrackSystem::m_gearPos(2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);

// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_rollerMass = 100.0;
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;

// suspension
// const std::string m_suspensionFilename;
const int TrackSystem::m_numSuspensions = 5;

TrackSystem::TrackSystem(const std::string& name, int track_idx)
  : m_track_idx(track_idx), m_name(name)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(track_idx);

}

void TrackSystem::Create(int track_idx)
{
  /*
  // read idler info
  assert(d.HasMember("Idler"));
  m_idlerMass = d["Idler"]["Mass"].GetDouble();
  m_idlerPos = loadVector(d["Idler"]["Location"]);
  m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
  m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
  m_idlerWidth = d["Spindle"]["Width"].GetDouble();
  m_idler_K = d["Idler"]["SpringK"].GetDouble();
  m_idler_C = d["Idler"]["SpringC"].GetDouble();

  // Read Drive Gear data
  assert(d.HasMember("Drive Gear"));
  assert(d["Drive Gear"].IsObject());

  m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
  m_gearPos = loadVector(d["Drive Gear"]["Location"]);
  m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
  m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
  m_gearWidth = d["Drive Gear"]["Width"].GetDouble();

  // Read Support Roller info
  assert(d.HasMember("Support Roller"));
  assert(d["Support Roller"].IsObject());

  m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
  m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
  m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
  m_rollerWidth = d["Support Roller"]["Width"].GetDouble();

  assert(d["Support Roller"]["Location"].IsArray());
  m_NumRollers = d["Support Roller"]["Location"].Size();

  m_rollerLocs.resize(m_NumRollers);
  for(int i = 0; i < m_NumRollers; i++ )
  {
	m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
  }

  // Read Suspension data
  assert(d.HasMember("Suspension"));
  assert(d["Suspension"].IsObject());
  assert(d["Suspension"]["Location"].IsArray() );

  m_suspensionFilename = d["Suspension"]["Input File"].GetString();
  m_NumSuspensions = d["Suspension"]["Location"].Size();

  m_suspensionLocs.resize(m_NumSuspensions);
  for(int j = 0; j < m_NumSuspensions; j++)
  {
    m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
  }

  // Read Track Chain data
  assert(d.HasMember("Track Chain"));
  assert(d["Track Chain"].IsObject());
  m_trackChainFilename = d["Track Chain"]["Input File"].GetString()

  */

  // create the various subsystems, from the class private variables
  BuildSubsystems();

}

void TrackSystem::BuildSubsystems()
{
  // build one of each of the following subsystems
  m_driveGear = ChSharedPtr<DriveGear>(new DriveGear() );
  m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple() );
  m_chain = ChSharedPtr<TrackChain>(new TrackChain());

  // build suspension/road wheel subsystems
  m_suspensions.resize(m_numSuspensions);
  for(int i = 0; i < m_numSuspensions; i++)
  {
    m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension());
  }

  // build support wheel subsystems (if any)
  m_supportRollers.resize(m_numRollers);
  m_supportRollers_rev.resize(m_numRollers);
  for(int j = 0; j < m_numRollers; j++)
  {
    m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
  }

}

void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
			 const ChVector<>&  location)
{
  // initialize 1 of each of the following subsystems:
  m_driveGear->Initialize(chassis, m_gearPos, QUNIT);
  m_idler->Initialize(chassis, m_idlerPos, QUNIT);

  // initialize the road wheels & torsion arm suspension subsystems
  for(int i = 0; i < m_suspensionLocs.size(); i++)
  {
    m_suspensions[i]->Initialize(chassis, m_suspensionLocs[i], QUNIT);
  }

  // initialize the support rollers
  for(int j = 0; j < m_rollerLocs.size(); j++)
  {
    initialize_roller(m_supportRollers[j], chassis,
      m_rollerLocs[j], QUNIT, j);
  }

}

// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef>  chassis,
                                    const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
  // express loc and rot in the global c-sys
  ChFrame<> frame_to_abs(loc, rot);

  body->SetPos(loc);
  body->SetRot(rot);
  body->SetMass(m_rollerMass);

  // transform point to absolute frame and initialize

  // add the revolute joint at the location and w/ orientation specified

  // Add a visual asset
}

} // end namespace chrono
<commit_msg>use new constructors for subsystems<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
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================

#include <cstdio>

#include "subsys/trackSystem/TrackSystem.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables

// idler
const ChVector<> TrackSystem::m_idlerPos(-2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);

// drive gear
const ChVector<> TrackSystem::m_gearPos(2.0, 0.75, 0);
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);

// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_rollerMass = 100.0;
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;

// suspension
// const std::string m_suspensionFilename;
const int TrackSystem::m_numSuspensions = 5;

TrackSystem::TrackSystem(const std::string& name, int track_idx)
  : m_track_idx(track_idx), m_name(name)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(track_idx);

}

void TrackSystem::Create(int track_idx)
{
  /*
  // read idler info
  assert(d.HasMember("Idler"));
  m_idlerMass = d["Idler"]["Mass"].GetDouble();
  m_idlerPos = loadVector(d["Idler"]["Location"]);
  m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
  m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
  m_idlerWidth = d["Spindle"]["Width"].GetDouble();
  m_idler_K = d["Idler"]["SpringK"].GetDouble();
  m_idler_C = d["Idler"]["SpringC"].GetDouble();

  // Read Drive Gear data
  assert(d.HasMember("Drive Gear"));
  assert(d["Drive Gear"].IsObject());

  m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
  m_gearPos = loadVector(d["Drive Gear"]["Location"]);
  m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
  m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
  m_gearWidth = d["Drive Gear"]["Width"].GetDouble();

  // Read Support Roller info
  assert(d.HasMember("Support Roller"));
  assert(d["Support Roller"].IsObject());

  m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
  m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
  m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
  m_rollerWidth = d["Support Roller"]["Width"].GetDouble();

  assert(d["Support Roller"]["Location"].IsArray());
  m_NumRollers = d["Support Roller"]["Location"].Size();

  m_rollerLocs.resize(m_NumRollers);
  for(int i = 0; i < m_NumRollers; i++ )
  {
	m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
  }

  // Read Suspension data
  assert(d.HasMember("Suspension"));
  assert(d["Suspension"].IsObject());
  assert(d["Suspension"]["Location"].IsArray() );

  m_suspensionFilename = d["Suspension"]["Input File"].GetString();
  m_NumSuspensions = d["Suspension"]["Location"].Size();

  m_suspensionLocs.resize(m_NumSuspensions);
  for(int j = 0; j < m_NumSuspensions; j++)
  {
    m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
  }

  // Read Track Chain data
  assert(d.HasMember("Track Chain"));
  assert(d["Track Chain"].IsObject());
  m_trackChainFilename = d["Track Chain"]["Input File"].GetString()

  */

  // create the various subsystems, from the class static variables
  BuildSubsystems();

}

void TrackSystem::BuildSubsystems()
{
  // build one of each of the following subsystems
  m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx)) );
  m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx)) );
  m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx)) );

  // build suspension/road wheel subsystems
  m_suspensions.resize(m_numSuspensions);
  for(int i = 0; i < m_numSuspensions; i++)
  {
    m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx)) );
  }

  // build support wheel subsystems (if any)
  m_supportRollers.resize(m_numRollers);
  m_supportRollers_rev.resize(m_numRollers);
  for(int j = 0; j < m_numRollers; j++)
  {
    m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
    m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) );
  }

}

void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
			 const ChVector<>&  location)
{
  // initialize 1 of each of the following subsystems:
  m_driveGear->Initialize(chassis, m_gearPos, QUNIT);
  m_idler->Initialize(chassis, m_idlerPos, QUNIT);

  // initialize the road wheels & torsion arm suspension subsystems
  for(int i = 0; i < m_suspensionLocs.size(); i++)
  {
    m_suspensions[i]->Initialize(chassis, m_suspensionLocs[i], QUNIT);
  }

  // initialize the support rollers
  for(int j = 0; j < m_rollerLocs.size(); j++)
  {
    initialize_roller(m_supportRollers[j], chassis,
      m_rollerLocs[j], QUNIT, j);
  }

}

// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef>  chassis,
                                    const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
  // express loc and rot in the global c-sys
  ChFrame<> frame_to_abs(loc, rot);

  body->SetPos(loc);
  body->SetRot(rot);
  body->SetMass(m_rollerMass);

  // transform point to absolute frame and initialize

  // add the revolute joint at the location and w/ orientation specified

  // Add a visual asset
}

} // end namespace chrono
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxIdentityTransformRegistrationComponent.h"
#include "selxCheckTemplateProperties.h"
#include <string>

namespace selx
{
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::IdentityTransformRegistrationComponent( const std::string & name,
  LoggerImpl & logger ) : Superclass( name, logger )
{
	this->m_DisplacementField = DisplacementFieldImageType::New();
}

template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::~IdentityTransformRegistrationComponent()
{
}

template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedInterface< Dimensionality, TPixel >::Pointer component )
{
  // Since SuperElastix is an itk filter in a pipeline, we need to set the domain of the resulting deformation field before running the registration.
  // As done in pairwise registration, typically, we use the domain of the fixed image for that.
  auto fixed = component->GetItkImageFixed();
  fixed->UpdateOutputInformation();
  auto size = fixed->GetLargestPossibleRegion().GetSize();
  this->m_DisplacementField->SetRegions(size);

  auto spacing = fixed->GetSpacing();
  this->m_DisplacementField->SetSpacing(spacing);

  auto origin = fixed->GetOrigin();
  this->m_DisplacementField->SetOrigin(origin);

  auto direction = fixed->GetDirection();
  this->m_DisplacementField->SetDirection(direction);

  this->m_ImageFixedInterface = component;
  return 0;
}

template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingInterface< Dimensionality, TPixel >::Pointer component )
{
  this->m_ImageMovingInterface = component;
  return 0;
}

template< int Dimensionality, class TPixel >
typename IdentityTransformRegistrationComponent< Dimensionality, TPixel >::DisplacementFieldImageType::Pointer
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::GetDisplacementFieldItkImage()
{

  return this->m_DisplacementField;
}

template< int Dimensionality, class TPixel >
void
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::RunRegistration( void )
{
	auto fixed = this->m_ImageFixedInterface->GetItkImageFixed();
	auto moving = this->m_ImageMovingInterface->GetItkImageMoving();
  fixed->UpdateLargestPossibleRegion();
  moving->UpdateLargestPossibleRegion();
  // Here you can implement your registration algorithm using the fixed and moving image.
	// For an Identity Transform it is just creating a vector field with zeros.
	this->m_DisplacementField->Allocate();
}

template< int Dimensionality, class TPixel >
bool
IdentityTransformRegistrationComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
  bool hasUndefinedCriteria( false );
  bool meetsCriteria( false );
  auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
  if( status == CriterionStatus::Satisfied )
  {
    return true;
  }
  else if( status == CriterionStatus::Failed )
  {
    return false;
  } // else: CriterionStatus::Unknown

  return meetsCriteria;
}
} //end namespace selx
<commit_msg>BUG: wrong function to update and expose raw image data<commit_after>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxIdentityTransformRegistrationComponent.h"
#include "selxCheckTemplateProperties.h"
#include <string>

namespace selx
{
template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::IdentityTransformRegistrationComponent( const std::string & name,
  LoggerImpl & logger ) : Superclass( name, logger )
{
	this->m_DisplacementField = DisplacementFieldImageType::New();
}

template< int Dimensionality, class TPixel >
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::~IdentityTransformRegistrationComponent()
{
}

template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedInterface< Dimensionality, TPixel >::Pointer component )
{
  // Since SuperElastix is an itk filter in a pipeline, we need to set the domain of the resulting deformation field before running the registration.
  // As done in pairwise registration, typically, we use the domain of the fixed image for that.
  auto fixed = component->GetItkImageFixed();
  fixed->UpdateOutputInformation();
  auto size = fixed->GetLargestPossibleRegion().GetSize();
  this->m_DisplacementField->SetRegions(size);

  auto spacing = fixed->GetSpacing();
  this->m_DisplacementField->SetSpacing(spacing);

  auto origin = fixed->GetOrigin();
  this->m_DisplacementField->SetOrigin(origin);

  auto direction = fixed->GetDirection();
  this->m_DisplacementField->SetDirection(direction);

  this->m_ImageFixedInterface = component;
  return 0;
}

template< int Dimensionality, class TPixel >
int
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingInterface< Dimensionality, TPixel >::Pointer component )
{
  this->m_ImageMovingInterface = component;
  return 0;
}

template< int Dimensionality, class TPixel >
typename IdentityTransformRegistrationComponent< Dimensionality, TPixel >::DisplacementFieldImageType::Pointer
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::GetDisplacementFieldItkImage()
{

  return this->m_DisplacementField;
}

template< int Dimensionality, class TPixel >
void
IdentityTransformRegistrationComponent< Dimensionality, TPixel >::RunRegistration( void )
{
  auto fixed = this->m_ImageFixedInterface->GetItkImageFixed();
  auto moving = this->m_ImageMovingInterface->GetItkImageMoving();

  fixed->SetRequestedRegionToLargestPossibleRegion();
  fixed->Update();
  // Raw pixel data is accessible by GetBufferPointer()
  moving->SetRequestedRegionToLargestPossibleRegion();
  moving->Update();
  // Raw pixel data is accessible by GetBufferPointer()

  // Here you can implement your registration algorithm using the fixed and moving image.
  // For an Identity Transform it is just creating a vector field with zeros.
  this->m_DisplacementField->Allocate();
}

template< int Dimensionality, class TPixel >
bool
IdentityTransformRegistrationComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
  bool hasUndefinedCriteria( false );
  bool meetsCriteria( false );
  auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
  if( status == CriterionStatus::Satisfied )
  {
    return true;
  }
  else if( status == CriterionStatus::Failed )
  {
    return false;
  } // else: CriterionStatus::Unknown

  return meetsCriteria;
}
} //end namespace selx
<|endoftext|>


<commit_before>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#ifndef POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#define POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP

#if (_MSC_VER > 1000)
#	pragma once
#endif

#include "../Platform.Win32/Win32Prerequisites.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <d3d11shader.h>
#include <wrl/client.h> // ComPtr

namespace Pomdog {
namespace Details {
namespace RenderSystem {
namespace Direct3D11 {

class GraphicsDeviceDirect3D11;
class GraphicsContextDirect3D11;

}// namespace Direct3D11
}// namespace RenderSystem
}// namespace Details
}// namespace Readymade

#endif // !defined(POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP)
<commit_msg>Update forward declarations header in Direct3D<commit_after>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#ifndef POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP
#define POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP

#if (_MSC_VER > 1000)
#	pragma once
#endif

#include "../Platform.Win32/Win32Prerequisites.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <d3d11shader.h>
#include <wrl/client.h> // ComPtr

namespace Pomdog {
namespace Details {
namespace RenderSystem {
namespace Direct3D11 {

class BlendStateDirect3D11;
class ConstantBufferDirect3D11;
class ConstantLayoutDirect3D11;
class DepthStencilStateDirect3D11;
class EffectPassDirect3D11;
class EffectReflectionDirect3D11;
class GraphicsDeviceDirect3D11;
class GraphicsContextDirect3D11;
class IndexBufferDirect3D11;
class InputLayoutDirect3D11;
class RasterizerStateDirect3D11;
class RenderTarget2DDirect3D11;
class SamplerStateDirect3D11;
class Texture2DDirect3D11;
class VertexBufferDirect3D11;

}// namespace Direct3D11
}// namespace RenderSystem
}// namespace Details
}// namespace Readymade

#endif // !defined(POMDOG_PREREQUISITESDIRECT3D11_EED05C73_4879_45F8_B1EB_0AABCC8FBCD5_HPP)
<|endoftext|>


<commit_before>#include <babylon/babylon_fwd.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/cameras/follow_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/cube_texture.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/maths/curve3.h>
#include <babylon/maths/vector3.h>
#include <babylon/meshes/mesh.h>
#include <babylon/samples/babylon_register_sample.h>

namespace BABYLON {

FWD_CLASS_SPTR(FollowCamera)
FWD_CLASS_SPTR(Mesh)

namespace Samples {

/**
 * @brief Rollercoaster Scene. Scene demonstrating a follow camera following a moving target.
 * @see https://www.babylonjs-playground.com/#1HH4OJ#29
 */
class RollercoasterScene : public IRenderableScene {

public:
  RollercoasterScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
  {
  }

  ~RollercoasterScene() override = default;

  const char* getName() override
  {
    return "Rollercoaster Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // Image resources for textures
    std::string urlRoof   = "textures/rooftile2.jpg";
    std::string urlWall   = "textures/stonewall.jpg";
    std::string urlGrass  = "textures/grass2.jpg";
    std::string urlSkyBox = "textures/skybox/skybox";

    // Let's create a scene with an hemispheric light
    scene->clearColor = Color3(0.4f, 0.6f, 1.f);
    auto light        = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.2f), scene);
    light->intensity  = 0.7f;

    // Then the sky with a Skybox
    auto skybox            = Mesh::CreateBox("skyBox", 2000.f, scene, false, Mesh::BACKSIDE);
    auto skyboxMaterial    = StandardMaterial::New("skyBox", scene);
    auto reflectionTexture = CubeTexture::New(urlSkyBox, scene);
    reflectionTexture->coordinatesMode = TextureConstants::SKYBOX_MODE;
    skyboxMaterial->diffuseColor       = Color3(0.f, 0.f, 0.f);
    skyboxMaterial->specularColor      = Color3(0.f, 0.f, 0.f);
    skyboxMaterial->reflectionTexture  = reflectionTexture;
    skybox->material                   = skyboxMaterial;

    // Then the ground with a textured big disc
    auto ground               = Mesh::CreateDisc("ground", 800, 60, scene);
    ground->rotation().x      = Math::PI_2;
    auto matGround            = StandardMaterial::New("mg", scene);
    ground->material          = matGround;
    auto groundTexture        = Texture::New(urlGrass, scene);
    groundTexture->uScale     = 100.f;
    groundTexture->vScale     = 100.f;
    matGround->diffuseTexture = groundTexture;
    matGround->specularColor  = Color3::Black();

    // Now we will draw the roller coaster rails
    // We set a closed curve by concatenating 5 different curves :
    // 1 - a set of three chained loops
    // 2 - a  left turn
    // 3 - a hill
    // 4 - a  right turn
    // 5 - a tiny hermite spline to close the curve
    // Curve computation ============================================
    Curve3 continued;
    float x = 0.f, y = 0.f, z = 0.f;

    // Loops : cosinus and sinus
    std::vector<Vector3> loops;
    size_t nbpt = 200;
    auto nbptf  = static_cast<float>(nbpt);
    float pi6   = Math::PI * 6.f;
    for (float lp = 0; lp < nbpt; ++lp) {
      x = lp - nbptf / 2.f + (nbptf / 5.f - lp / 8.f) * std::cos(pi6 * lp / nbptf);
      y = nbptf / 5.f + (nbptf / 5.f - lp / 8.f) * std::sin(pi6 * lp / nbptf);
      z = lp - nbptf;
      loops.emplace_back(Vector3(x, y, z));
    }

    // First turn : cosinus and sinus
    std::vector<Vector3> turn1;
    float ang = Math::PI;
    nbpt      = 40;
    nbptf     = static_cast<float>(nbpt);
    for (float tp = 0; tp < nbpt; ++tp) {
      x = 30.f * std::cos(ang * tp / nbptf - 0.8f);
      y = 30.f * std::sin(ang * tp / nbptf);
      z = 30.f * std::sin(ang * tp / nbptf - 0.8f);
      turn1.emplace_back(Vector3(x, y, z));
    }

    // Hill : exponential
    std::vector<Vector3> hill;
    nbpt  = 80;
    nbptf = static_cast<float>(nbpt);
    for (float hp = 0; hp < nbpt; ++hp) {
      x = -hp * 2.f;
      y = 80.f * std::exp(-(hp - nbptf / 3.f) * (hp - nbptf / 3.f) / (nbptf * 5.f));
      z = -hp * 3.2f;
      hill.emplace_back(Vector3(x, y, z));
    }

    // Second turn : cosinus and sinus
    std::vector<Vector3> turn2;
    nbpt  = 60;
    nbptf = static_cast<float>(nbpt);
    ang   = -Math::PI * 3.f / 2.f;
    for (float tp = 0; tp < nbpt; ++tp) {
      x = 30.f * std::cos(ang * tp / nbptf - 0.6f);
      y = -tp / 2.5f;
      z = 30.f * std::sin(ang * tp / nbptf - 0.6f);
      turn2.emplace_back(Vector3(x, y, z));
    }

    // Close rails with hermite
    Curve3 curloops(loops);
    Curve3 curturn1(turn1);
    Curve3 curhill(hill);
    Curve3 curturn2(turn2);
    continued
      = (curloops).continueCurve3(curturn1).continueCurve3(curhill).continueCurve3(curturn2);
    _points = continued.getPoints();

    auto p1      = _points[_points.size() - 1];
    auto t1      = (p1.subtract(_points[_points.size() - 2])).scale(10.f);
    auto p2      = _points[0];
    auto t2      = (_points[1].subtract(p2)).scale(30.f);
    auto hermite = Curve3::CreateHermiteSpline(p1, t1, p2, t2, 15);

    // Full final curve
    continued = hermite.continueCurve3(continued);
    _points   = continued.getPoints();
    // Curve computed ===========================================

    // Let's know define a simple triangular shape for the rails
    std::vector<Vector3> shape{
      Vector3(0.f, 2.f, 0.f),  //
      Vector3(-1.f, 0.f, 0.f), //
      Vector3(0.f, -2.f, 0.f), //
    };
    shape.emplace_back(shape[0]);

    // Let's now extrude this shape along the curve to draw the whole roller
    // coaster
    auto origin             = Vector3::Zero();
    auto rollerCoaster      = Mesh::ExtrudeShape("rc", shape, _points, 2, 0, Mesh::NO_CAP, scene);
    auto mat                = StandardMaterial::New("mat1", scene);
    mat->diffuseColor       = Color3(1.f, 0.8f, 1.f);
    mat->wireframe          = true;
    rollerCoaster->material = mat;
    rollerCoaster->position = origin;

    // As the first and final extruded shape may not fit along a closed curve, we
    // hide this junction with a little house
    auto house               = Mesh::CreateBox("house", 10, scene);
    house->scaling().x       = 2.f;
    house->scaling().z       = 1.5f;
    house->rotation().y      = 0.6f;
    house->position          = _points[0];
    auto roof                = Mesh::CreateCylinder("roof", 22, 20, 20, 3, 1, scene);
    roof->rotation().y       = house->rotation().y;
    roof->rotation().z       = Math::PI_2;
    roof->position().x       = house->position().x;
    roof->position().y       = 12;
    roof->position().z       = house->position().z;
    auto wallTexture         = Texture::New(urlWall, scene);
    auto houseMat            = StandardMaterial::New("housemat", scene);
    houseMat->diffuseTexture = wallTexture;
    house->material          = houseMat;
    auto roofTexture         = Texture::New(urlRoof, scene);
    roofTexture->uScale      = 10.f;
    roofTexture->vScale      = 5.f;
    auto roofMat             = StandardMaterial::New("roofmat", scene);
    roofMat->specularColor   = Color3::Black();
    roofMat->diffuseTexture  = roofTexture;
    roof->material           = roofMat;

    // All immobile meshes can be now frozen to avoid un-needed matrix
    // computations
    skybox->freezeWorldMatrix();
    ground->freezeWorldMatrix();
    house->freezeWorldMatrix();
    roof->freezeWorldMatrix();

    // We've got the rails, we need now a wagon !
    _wagon                 = Mesh::CreateBox("wagon", 4, scene);
    _wagon->scaling().x    = 2.f;
    auto matWagon          = StandardMaterial::New("mw", scene);
    matWagon->diffuseColor = Color3(1.f, 0.f, 0.8f);
    _wagon->material       = matWagon;
    _wagon->position       = origin;

    // Just in case you want to position the roller coaster somewhere else
    // translate the relative curve points to the same origin than the mesh
    _lg = _points.size();
    for (size_t pt = 0; pt < _lg; ++pt) {
      _points[pt].addInPlace(origin);
    }

    // Let's add a Follow Camera.
    // It is set initially very far from the roller-coaster in order to get an
    // "approach"" effect on start
    _followCam               = FollowCamera::New("fcam", Vector3(20.f, 200.f, -800.f), scene);
    _followCam->lockedTarget = _wagon;
    _followCam->attachControl(canvas, true);

    // followCam.target = wagon;
    _followCam->radius         = 50.f;
    _followCam->maxCameraSpeed = 1.f;
    scene->activeCamera        = _followCam;

    // All meshes and cam are set, so now let's handle the wagon trajectory
    // Let's create a Path3D object with the curve
    auto path3d = Path3D(_points);
    _tgts       = path3d.getTangents();
    _norms      = path3d.getNormals();
    _binorms    = path3d.getBinormals();

    // let's scale the normals, where the wagon will be attached, to be a little
    // farther from the rails
    float shift = 2.f;
    for (size_t n = 0; n < _lg; n++) {
      _norms[n].scaleInPlace(shift);
    }

    // Let's initialize now some variables for updating the wagon position each
    // frame
    _i       = 0;
    _j       = 1;
    _curvect = _points[_j].subtract(_points[_i]);
    _rot     = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
    _pos     = Vector3::Zero();
    _scaled  = Vector3::Zero();
    _step    = 3;
    _k       = 0;

    // Animation
    // the wagon slides many steps on each curve segment
    scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) {
      _curvect.scaleToRef(static_cast<float>(_k) / static_cast<float>(_step), _scaled);
      _points[_i].addToRef(_scaled, _pos);
      _pos.addInPlace(_norms[_i]);
      _wagon->position = _pos;
      _wagon->rotation = _rot;
      ++_k;
      // next segment
      if (_k == _step) {
        _i   = (_i + 1) % _lg;
        _j   = (_i + 1) % _lg;
        _rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
        _points[_j].subtractToRef(_points[_i], _curvect);
        _k = 0;
        if (_i == 0) {
          // followCam->radius = 50.f + 200.f * Math::random();
        }
      }
      _followCam->position().y = 50.f;
    });
  }

private:
  // List with points
  std::vector<Vector3> _points;
  // Points size
  size_t _lg;
  // Tangent vectors
  std::vector<Vector3> _tgts;
  // Normal vectors
  std::vector<Vector3> _norms;
  // Binormal vectors
  std::vector<Vector3> _binorms;
  // Curve current point
  size_t _i;
  // Curve next current point
  size_t _j;
  // Curve current segment
  Vector3 _curvect;
  // Wagon current rotation
  Vector3 _rot;
  // Wagon current position
  Vector3 _pos;
  // Current scaled segment
  Vector3 _scaled;
  // nb steps on each segment
  size_t _step;
  // Counter
  size_t _k;
  // Wagon Mesh
  MeshPtr _wagon;
  // Follow Camera
  FollowCameraPtr _followCam;

}; // end of class RollercoasterScene

BABYLON_REGISTER_SAMPLE("Cameras", RollercoasterScene)

} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Added lambda return type<commit_after>#include <babylon/babylon_fwd.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/cameras/follow_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/cube_texture.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/maths/curve3.h>
#include <babylon/maths/vector3.h>
#include <babylon/meshes/mesh.h>
#include <babylon/samples/babylon_register_sample.h>

namespace BABYLON {

FWD_CLASS_SPTR(FollowCamera)
FWD_CLASS_SPTR(Mesh)

namespace Samples {

/**
 * @brief Rollercoaster Scene. Scene demonstrating a follow camera following a moving target.
 * @see https://www.babylonjs-playground.com/#1HH4OJ#29
 */
class RollercoasterScene : public IRenderableScene {

public:
  RollercoasterScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
  {
  }

  ~RollercoasterScene() override = default;

  const char* getName() override
  {
    return "Rollercoaster Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // Image resources for textures
    std::string urlRoof   = "textures/rooftile2.jpg";
    std::string urlWall   = "textures/stonewall.jpg";
    std::string urlGrass  = "textures/grass2.jpg";
    std::string urlSkyBox = "textures/skybox/skybox";

    // Let's create a scene with an hemispheric light
    scene->clearColor = Color3(0.4f, 0.6f, 1.f);
    auto light        = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.2f), scene);
    light->intensity  = 0.7f;

    // Then the sky with a Skybox
    auto skybox            = Mesh::CreateBox("skyBox", 2000.f, scene, false, Mesh::BACKSIDE);
    auto skyboxMaterial    = StandardMaterial::New("skyBox", scene);
    auto reflectionTexture = CubeTexture::New(urlSkyBox, scene);
    reflectionTexture->coordinatesMode = TextureConstants::SKYBOX_MODE;
    skyboxMaterial->diffuseColor       = Color3(0.f, 0.f, 0.f);
    skyboxMaterial->specularColor      = Color3(0.f, 0.f, 0.f);
    skyboxMaterial->reflectionTexture  = reflectionTexture;
    skybox->material                   = skyboxMaterial;

    // Then the ground with a textured big disc
    auto ground               = Mesh::CreateDisc("ground", 800, 60, scene);
    ground->rotation().x      = Math::PI_2;
    auto matGround            = StandardMaterial::New("mg", scene);
    ground->material          = matGround;
    auto groundTexture        = Texture::New(urlGrass, scene);
    groundTexture->uScale     = 100.f;
    groundTexture->vScale     = 100.f;
    matGround->diffuseTexture = groundTexture;
    matGround->specularColor  = Color3::Black();

    // Now we will draw the roller coaster rails
    // We set a closed curve by concatenating 5 different curves :
    // 1 - a set of three chained loops
    // 2 - a  left turn
    // 3 - a hill
    // 4 - a  right turn
    // 5 - a tiny hermite spline to close the curve
    // Curve computation ============================================
    Curve3 continued;
    float x = 0.f, y = 0.f, z = 0.f;

    // Loops : cosinus and sinus
    std::vector<Vector3> loops;
    size_t nbpt = 200;
    auto nbptf  = static_cast<float>(nbpt);
    float pi6   = Math::PI * 6.f;
    for (float lp = 0; lp < nbpt; ++lp) {
      x = lp - nbptf / 2.f + (nbptf / 5.f - lp / 8.f) * std::cos(pi6 * lp / nbptf);
      y = nbptf / 5.f + (nbptf / 5.f - lp / 8.f) * std::sin(pi6 * lp / nbptf);
      z = lp - nbptf;
      loops.emplace_back(Vector3(x, y, z));
    }

    // First turn : cosinus and sinus
    std::vector<Vector3> turn1;
    float ang = Math::PI;
    nbpt      = 40;
    nbptf     = static_cast<float>(nbpt);
    for (float tp = 0; tp < nbpt; ++tp) {
      x = 30.f * std::cos(ang * tp / nbptf - 0.8f);
      y = 30.f * std::sin(ang * tp / nbptf);
      z = 30.f * std::sin(ang * tp / nbptf - 0.8f);
      turn1.emplace_back(Vector3(x, y, z));
    }

    // Hill : exponential
    std::vector<Vector3> hill;
    nbpt  = 80;
    nbptf = static_cast<float>(nbpt);
    for (float hp = 0; hp < nbpt; ++hp) {
      x = -hp * 2.f;
      y = 80.f * std::exp(-(hp - nbptf / 3.f) * (hp - nbptf / 3.f) / (nbptf * 5.f));
      z = -hp * 3.2f;
      hill.emplace_back(Vector3(x, y, z));
    }

    // Second turn : cosinus and sinus
    std::vector<Vector3> turn2;
    nbpt  = 60;
    nbptf = static_cast<float>(nbpt);
    ang   = -Math::PI * 3.f / 2.f;
    for (float tp = 0; tp < nbpt; ++tp) {
      x = 30.f * std::cos(ang * tp / nbptf - 0.6f);
      y = -tp / 2.5f;
      z = 30.f * std::sin(ang * tp / nbptf - 0.6f);
      turn2.emplace_back(Vector3(x, y, z));
    }

    // Close rails with hermite
    Curve3 curloops(loops);
    Curve3 curturn1(turn1);
    Curve3 curhill(hill);
    Curve3 curturn2(turn2);
    continued
      = (curloops).continueCurve3(curturn1).continueCurve3(curhill).continueCurve3(curturn2);
    _points = continued.getPoints();

    auto p1      = _points[_points.size() - 1];
    auto t1      = (p1.subtract(_points[_points.size() - 2])).scale(10.f);
    auto p2      = _points[0];
    auto t2      = (_points[1].subtract(p2)).scale(30.f);
    auto hermite = Curve3::CreateHermiteSpline(p1, t1, p2, t2, 15);

    // Full final curve
    continued = hermite.continueCurve3(continued);
    _points   = continued.getPoints();
    // Curve computed ===========================================

    // Let's know define a simple triangular shape for the rails
    std::vector<Vector3> shape{
      Vector3(0.f, 2.f, 0.f),  //
      Vector3(-1.f, 0.f, 0.f), //
      Vector3(0.f, -2.f, 0.f), //
    };
    shape.emplace_back(shape[0]);

    // Let's now extrude this shape along the curve to draw the whole roller
    // coaster
    auto origin             = Vector3::Zero();
    auto rollerCoaster      = Mesh::ExtrudeShape("rc", shape, _points, 2, 0, Mesh::NO_CAP, scene);
    auto mat                = StandardMaterial::New("mat1", scene);
    mat->diffuseColor       = Color3(1.f, 0.8f, 1.f);
    mat->wireframe          = true;
    rollerCoaster->material = mat;
    rollerCoaster->position = origin;

    // As the first and final extruded shape may not fit along a closed curve, we
    // hide this junction with a little house
    auto house               = Mesh::CreateBox("house", 10, scene);
    house->scaling().x       = 2.f;
    house->scaling().z       = 1.5f;
    house->rotation().y      = 0.6f;
    house->position          = _points[0];
    auto roof                = Mesh::CreateCylinder("roof", 22, 20, 20, 3, 1, scene);
    roof->rotation().y       = house->rotation().y;
    roof->rotation().z       = Math::PI_2;
    roof->position().x       = house->position().x;
    roof->position().y       = 12;
    roof->position().z       = house->position().z;
    auto wallTexture         = Texture::New(urlWall, scene);
    auto houseMat            = StandardMaterial::New("housemat", scene);
    houseMat->diffuseTexture = wallTexture;
    house->material          = houseMat;
    auto roofTexture         = Texture::New(urlRoof, scene);
    roofTexture->uScale      = 10.f;
    roofTexture->vScale      = 5.f;
    auto roofMat             = StandardMaterial::New("roofmat", scene);
    roofMat->specularColor   = Color3::Black();
    roofMat->diffuseTexture  = roofTexture;
    roof->material           = roofMat;

    // All immobile meshes can be now frozen to avoid un-needed matrix
    // computations
    skybox->freezeWorldMatrix();
    ground->freezeWorldMatrix();
    house->freezeWorldMatrix();
    roof->freezeWorldMatrix();

    // We've got the rails, we need now a wagon !
    _wagon                 = Mesh::CreateBox("wagon", 4, scene);
    _wagon->scaling().x    = 2.f;
    auto matWagon          = StandardMaterial::New("mw", scene);
    matWagon->diffuseColor = Color3(1.f, 0.f, 0.8f);
    _wagon->material       = matWagon;
    _wagon->position       = origin;

    // Just in case you want to position the roller coaster somewhere else
    // translate the relative curve points to the same origin than the mesh
    _lg = _points.size();
    for (size_t pt = 0; pt < _lg; ++pt) {
      _points[pt].addInPlace(origin);
    }

    // Let's add a Follow Camera.
    // It is set initially very far from the roller-coaster in order to get an
    // "approach"" effect on start
    _followCam               = FollowCamera::New("fcam", Vector3(20.f, 200.f, -800.f), scene);
    _followCam->lockedTarget = _wagon;
    _followCam->attachControl(canvas, true);

    // followCam.target = wagon;
    _followCam->radius         = 50.f;
    _followCam->maxCameraSpeed = 1.f;
    scene->activeCamera        = _followCam;

    // All meshes and cam are set, so now let's handle the wagon trajectory
    // Let's create a Path3D object with the curve
    auto path3d = Path3D(_points);
    _tgts       = path3d.getTangents();
    _norms      = path3d.getNormals();
    _binorms    = path3d.getBinormals();

    // let's scale the normals, where the wagon will be attached, to be a little
    // farther from the rails
    float shift = 2.f;
    for (size_t n = 0; n < _lg; n++) {
      _norms[n].scaleInPlace(shift);
    }

    // Let's initialize now some variables for updating the wagon position each
    // frame
    _i       = 0;
    _j       = 1;
    _curvect = _points[_j].subtract(_points[_i]);
    _rot     = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
    _pos     = Vector3::Zero();
    _scaled  = Vector3::Zero();
    _step    = 3;
    _k       = 0;

    // Animation
    // the wagon slides many steps on each curve segment
    scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) -> void {
      _curvect.scaleToRef(static_cast<float>(_k) / static_cast<float>(_step), _scaled);
      _points[_i].addToRef(_scaled, _pos);
      _pos.addInPlace(_norms[_i]);
      _wagon->position = _pos;
      _wagon->rotation = _rot;
      ++_k;
      // next segment
      if (_k == _step) {
        _i   = (_i + 1) % _lg;
        _j   = (_i + 1) % _lg;
        _rot = Vector3::RotationFromAxis(_tgts[_i], _norms[_i], _binorms[_i]);
        _points[_j].subtractToRef(_points[_i], _curvect);
        _k = 0;
        if (_i == 0) {
          // followCam->radius = 50.f + 200.f * Math::random();
        }
      }
      _followCam->position().y = 50.f;
    });
  }

private:
  // List with points
  std::vector<Vector3> _points;
  // Points size
  size_t _lg;
  // Tangent vectors
  std::vector<Vector3> _tgts;
  // Normal vectors
  std::vector<Vector3> _norms;
  // Binormal vectors
  std::vector<Vector3> _binorms;
  // Curve current point
  size_t _i;
  // Curve next current point
  size_t _j;
  // Curve current segment
  Vector3 _curvect;
  // Wagon current rotation
  Vector3 _rot;
  // Wagon current position
  Vector3 _pos;
  // Current scaled segment
  Vector3 _scaled;
  // nb steps on each segment
  size_t _step;
  // Counter
  size_t _k;
  // Wagon Mesh
  MeshPtr _wagon;
  // Follow Camera
  FollowCameraPtr _followCam;

}; // end of class RollercoasterScene

BABYLON_REGISTER_SAMPLE("Cameras", RollercoasterScene)

} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|>


<commit_before>#include "chainerx/routines/statistics.h"

#include "chainerx/array.h"
#include "chainerx/axes.h"

#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/macro.h"
#include "chainerx/routines/creation.h"

namespace chainerx {

Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) {
    Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
    Array out = internal::EmptyReduced(a.shape(), a.dtype(), sorted_axis, keepdims, a.device());
    Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis);

    {
        NoBackpropModeScope scope{};
        a.device().Sum(a, sorted_axis, out);
        a.device().DivideAS(out, n, out);
    }

    BackwardBuilder bb{"mean", a, out};
    if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
        bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
            const Array& gout = *bctx.output_grad();
            CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));

            if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
                Shape out_shape_broadcastable = gout.shape();
                for (auto axis : sorted_axis) {
                    out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
                }
                bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n;
            } else {
                bctx.input_grad() = gout.BroadcastTo(in_shape) / n;
            }
        });
    }
    bb.Finalize();

    return out;
}

Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) {
    // TODO(hvy): Consider allowing device implementations.
    Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
    Array diff = a - Mean(a, sorted_axis, true);
    return Mean(diff * diff, sorted_axis, keepdims);
}

}  // namespace chainerx
<commit_msg>promote_integral2floats<commit_after>#include "chainerx/routines/statistics.h"

#include "chainerx/array.h"
#include "chainerx/axes.h"

#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/macro.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/type_util.h"

namespace chainerx {

Dtype promote_int2float(Dtype dtype){
    return GetKind(dtype) == DtypeKind::kFloat? dtype :internal::GetDefaultDtype(DtypeKind::kFloat);
}

Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) {
    Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
    Dtype out_dtype = promote_int2float(a.dtype());
    Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
    Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis);

    {
        NoBackpropModeScope scope{};
        a.device().Sum(a, sorted_axis, out);
        a.device().DivideAS(out, n, out);
    }

    BackwardBuilder bb{"mean", a, out};
    if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
        bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
            const Array& gout = *bctx.output_grad();
            CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));

            if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
                Shape out_shape_broadcastable = gout.shape();
                for (auto axis : sorted_axis) {
                    out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
                }
                bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n;
            } else {
                bctx.input_grad() = gout.BroadcastTo(in_shape) / n;
            }
        });
    }
    bb.Finalize();

    return out;
}

Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) {
    // TODO(hvy): Consider allowing device implementations.
    Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
    Dtype mean_out = promote_int2float(a.dtype());
    // TODO: remove once subtract allows mixed types.
    Array diff = a.AsType(mean_out, true) - Mean(a, sorted_axis, true);
    return Mean(diff * diff, sorted_axis, keepdims);
}

}  // namespace chainerx
<|endoftext|>


<commit_before><commit_msg>Remove all infobars from a tab when its renderer crashes. They are irrelevant in the sad tab.<commit_after><|endoftext|>


<commit_before><commit_msg>Close pop up notification when navigating to other site.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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/basictypes.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_process_filter.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/perf/mem_usage.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
#define BASE_URL L"http://localhost:8000"

namespace {

class PageCyclerTest : public UITest {
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    CommandLine::AppendSwitchWithValue(&launch_arguments_,
                                       switches::kJavaScriptFlags,
                                       L"--expose_gc");
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const wchar_t* name, std::wstring* pages,
                     std::wstring* timings, bool use_http) {
    GURL test_url;
    if (use_http) {
      std::wstring test_path(BASE_URL);
      file_util::AppendToPath(&test_path, name);
      file_util::AppendToPath(&test_path, L"start.html");
      test_url = GURL(test_path);
    } else {
      std::wstring test_path;
      PathService::Get(base::DIR_EXE, &test_path);
      file_util::UpOneDirectory(&test_path);
      file_util::UpOneDirectory(&test_path);
      file_util::AppendToPath(&test_path, L"data");
      file_util::AppendToPath(&test_path, L"page_cycler");
      file_util::AppendToPath(&test_path, name);
      file_util::AppendToPath(&test_path, L"start.html");
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_ptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->swap(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->swap(UTF8ToWide(cookie));
    ASSERT_FALSE(timings->empty());
  }

  void PrintIOPerfInfo(const wchar_t* test_name) {
    BrowserProcessFilter chrome_filter(L"");
    process_util::NamedProcessIterator
        chrome_process_itr(chrome::kBrowserProcessExecutableName,
                           &chrome_filter);

    const PROCESSENTRY32* chrome_entry;
    while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
      uint32 pid = chrome_entry->th32ProcessID;
      HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION,
                                          false,
                                          pid);

      scoped_ptr<process_util::ProcessMetrics> process_metrics;
      IO_COUNTERS io_counters;
      process_metrics.reset(
          process_util::ProcessMetrics::CreateProcessMetrics(process_handle));
      ZeroMemory(&io_counters, sizeof(io_counters));

      if (process_metrics.get()->GetIOCounters(&io_counters)) {
        // Print out IO performance.  We assume that the values can be
        // converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
        std::wstring chrome_name =
            (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";

        PrintResult(L"read_op", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadOperationCount), L"",
                    false /* not important */);
        PrintResult(L"write_op", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteOperationCount), L"",
                    false /* not important */);
        PrintResult(L"other_op", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherOperationCount), L"",
                    false /* not important */);

        size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
                                           io_counters.WriteOperationCount +
                                           io_counters.OtherOperationCount);
        PrintResult(L"total_op", chrome_name, chrome_name + test_name,
                    total, L"", true /* important */);

        PrintResult(L"read_byte", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadTransferCount / 1024),
                    L"kb", false /* not important */);
        PrintResult(L"write_byte", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteTransferCount / 1024),
                    L"kb", false /* not important */);
        PrintResult(L"other_byte", chrome_name, chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherTransferCount / 1024),
                    L"kb", false /* not important */);

        total = static_cast<size_t>((io_counters.ReadTransferCount +
                                     io_counters.WriteTransferCount +
                                     io_counters.OtherTransferCount) / 1024);
        PrintResult(L"total_byte", chrome_name, chrome_name + test_name,
                    total, L"kb", true /* important */);

      }
    }
  }

  void PrintMemoryUsageInfo(const wchar_t* test_name) {
    BrowserProcessFilter chrome_filter(L"");
    process_util::NamedProcessIterator
        chrome_process_itr(chrome::kBrowserProcessExecutableName,
                           &chrome_filter);

    const PROCESSENTRY32* chrome_entry;
    while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
      uint32 pid = chrome_entry->th32ProcessID;
      size_t peak_virtual_size;
      size_t current_virtual_size;
      size_t peak_working_set_size;
      size_t current_working_set_size;
      if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size,
                        &peak_working_set_size, &current_working_set_size)) {

        std::wstring chrome_name =
            (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";

        std::wstring trace_name(test_name);
        PrintResult(L"vm_peak", chrome_name,
                    L"vm_pk" + chrome_name + trace_name,
                    peak_virtual_size, L"bytes",
                    true /* important */);
        PrintResult(L"vm_final", chrome_name,
                    L"vm_f" + chrome_name + trace_name,
                    current_virtual_size, L"bytes",
                    false /* not important */);
        PrintResult(L"ws_peak", chrome_name,
                    L"ws_pk" + chrome_name + trace_name,
                    peak_working_set_size, L"bytes",
                    true /* important */);
        PrintResult(L"ws_final", chrome_name,
                    L"ws_pk" + chrome_name + trace_name,
                    current_working_set_size, L"bytes",
                    false /* not important */);
      }
    }
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTest(const wchar_t* name, bool use_http) {
    std::wstring pages, timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo(L"");
    PrintIOPerfInfo(L"");

    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList(L"times", L"", L"t", timings, L"ms",
                    true /* important */);
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    std::wstring dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    file_util::AppendToPath(&dir, L"reference_build");
    file_util::AppendToPath(&dir, L"chrome");
    browser_directory_ = dir;
    UITest::SetUp();
  }

  void RunTest(const wchar_t* name, bool use_http) {
    std::wstring pages, timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo(L"_ref");
    PrintIOPerfInfo(L"_ref");

    PrintResultList(L"times", L"", L"t_ref", timings, L"ms",
                    true /* important */);
  }
};

}  // namespace

// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
  RunTest(L"moz", false);
}

TEST_F(PageCyclerReferenceTest, MozFile) {
  RunTest(L"moz", false);
}

TEST_F(PageCyclerTest, Intl1File) {
  RunTest(L"intl1", false);
}

TEST_F(PageCyclerReferenceTest, Intl1File) {
  RunTest(L"intl1", false);
}

TEST_F(PageCyclerTest, Intl2File) {
  RunTest(L"intl2", false);
}

TEST_F(PageCyclerReferenceTest, Intl2File) {
  RunTest(L"intl2", false);
}

TEST_F(PageCyclerTest, DomFile) {
  RunTest(L"dom", false);
}

TEST_F(PageCyclerReferenceTest, DomFile) {
  RunTest(L"dom", false);
}

TEST_F(PageCyclerTest, DhtmlFile) {
  RunTest(L"dhtml", false);
}

TEST_F(PageCyclerReferenceTest, DhtmlFile) {
  RunTest(L"dhtml", false);
}

// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
  RunTest(L"moz", true);
}

TEST_F(PageCyclerReferenceTest, MozHttp) {
  RunTest(L"moz", true);
}

TEST_F(PageCyclerTest, Intl1Http) {
  RunTest(L"intl1", true);
}

TEST_F(PageCyclerReferenceTest, Intl1Http) {
  RunTest(L"intl1", true);
}

TEST_F(PageCyclerTest, Intl2Http) {
  RunTest(L"intl2", true);
}

TEST_F(PageCyclerReferenceTest, Intl2Http) {
  RunTest(L"intl2", true);
}

TEST_F(PageCyclerTest, DomHttp) {
  RunTest(L"dom", true);
}

TEST_F(PageCyclerReferenceTest, DomHttp) {
  RunTest(L"dom", true);
}

TEST_F(PageCyclerTest, BloatHttp) {
  RunTest(L"bloat", true);
}

TEST_F(PageCyclerReferenceTest, BloatHttp) {
  RunTest(L"bloat", true);
}

<commit_msg>Add prefixes to I/O data trace names so they can be distinguished on the waterfall.<commit_after>// Copyright (c) 2006-2008 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/basictypes.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_process_filter.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/perf/mem_usage.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
#define BASE_URL L"http://localhost:8000"

namespace {

class PageCyclerTest : public UITest {
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    CommandLine::AppendSwitchWithValue(&launch_arguments_,
                                       switches::kJavaScriptFlags,
                                       L"--expose_gc");
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const wchar_t* name, std::wstring* pages,
                     std::wstring* timings, bool use_http) {
    GURL test_url;
    if (use_http) {
      std::wstring test_path(BASE_URL);
      file_util::AppendToPath(&test_path, name);
      file_util::AppendToPath(&test_path, L"start.html");
      test_url = GURL(test_path);
    } else {
      std::wstring test_path;
      PathService::Get(base::DIR_EXE, &test_path);
      file_util::UpOneDirectory(&test_path);
      file_util::UpOneDirectory(&test_path);
      file_util::AppendToPath(&test_path, L"data");
      file_util::AppendToPath(&test_path, L"page_cycler");
      file_util::AppendToPath(&test_path, name);
      file_util::AppendToPath(&test_path, L"start.html");
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_ptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->swap(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->swap(UTF8ToWide(cookie));
    ASSERT_FALSE(timings->empty());
  }

  void PrintIOPerfInfo(const wchar_t* test_name) {
    BrowserProcessFilter chrome_filter(L"");
    process_util::NamedProcessIterator
        chrome_process_itr(chrome::kBrowserProcessExecutableName,
                           &chrome_filter);

    const PROCESSENTRY32* chrome_entry;
    while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
      uint32 pid = chrome_entry->th32ProcessID;
      HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION,
                                          false,
                                          pid);

      scoped_ptr<process_util::ProcessMetrics> process_metrics;
      IO_COUNTERS io_counters;
      process_metrics.reset(
          process_util::ProcessMetrics::CreateProcessMetrics(process_handle));
      ZeroMemory(&io_counters, sizeof(io_counters));

      if (process_metrics.get()->GetIOCounters(&io_counters)) {
        // Print out IO performance.  We assume that the values can be
        // converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
        std::wstring chrome_name =
            (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";

        PrintResult(L"read_op", chrome_name,
                    L"r_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadOperationCount), L"",
                    false /* not important */);
        PrintResult(L"write_op", chrome_name,
                    L"w_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteOperationCount), L"",
                    false /* not important */);
        PrintResult(L"other_op", chrome_name,
                    L"o_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherOperationCount), L"",
                    false /* not important */);

        size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
                                           io_counters.WriteOperationCount +
                                           io_counters.OtherOperationCount);
        PrintResult(L"total_op", chrome_name,
                    L"IO_op" + chrome_name + test_name,
                    total, L"", true /* important */);

        PrintResult(L"read_byte", chrome_name,
                    L"r_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadTransferCount / 1024),
                    L"kb", false /* not important */);
        PrintResult(L"write_byte", chrome_name,
                    L"w_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteTransferCount / 1024),
                    L"kb", false /* not important */);
        PrintResult(L"other_byte", chrome_name,
                    L"o_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherTransferCount / 1024),
                    L"kb", false /* not important */);

        total = static_cast<size_t>((io_counters.ReadTransferCount +
                                     io_counters.WriteTransferCount +
                                     io_counters.OtherTransferCount) / 1024);
        PrintResult(L"total_byte", chrome_name,
                    L"IO_b" + chrome_name + test_name,
                    total, L"kb", true /* important */);

      }
    }
  }

  void PrintMemoryUsageInfo(const wchar_t* test_name) {
    BrowserProcessFilter chrome_filter(L"");
    process_util::NamedProcessIterator
        chrome_process_itr(chrome::kBrowserProcessExecutableName,
                           &chrome_filter);

    const PROCESSENTRY32* chrome_entry;
    while(chrome_entry = chrome_process_itr.NextProcessEntry()) {
      uint32 pid = chrome_entry->th32ProcessID;
      size_t peak_virtual_size;
      size_t current_virtual_size;
      size_t peak_working_set_size;
      size_t current_working_set_size;
      if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size,
                        &peak_working_set_size, &current_working_set_size)) {

        std::wstring chrome_name =
            (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r";

        std::wstring trace_name(test_name);
        PrintResult(L"vm_peak", chrome_name,
                    L"vm_pk" + chrome_name + trace_name,
                    peak_virtual_size, L"bytes",
                    true /* important */);
        PrintResult(L"vm_final", chrome_name,
                    L"vm_f" + chrome_name + trace_name,
                    current_virtual_size, L"bytes",
                    false /* not important */);
        PrintResult(L"ws_peak", chrome_name,
                    L"ws_pk" + chrome_name + trace_name,
                    peak_working_set_size, L"bytes",
                    true /* important */);
        PrintResult(L"ws_final", chrome_name,
                    L"ws_pk" + chrome_name + trace_name,
                    current_working_set_size, L"bytes",
                    false /* not important */);
      }
    }
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTest(const wchar_t* name, bool use_http) {
    std::wstring pages, timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo(L"");
    PrintIOPerfInfo(L"");

    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList(L"times", L"", L"t", timings, L"ms",
                    true /* important */);
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    std::wstring dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    file_util::AppendToPath(&dir, L"reference_build");
    file_util::AppendToPath(&dir, L"chrome");
    browser_directory_ = dir;
    UITest::SetUp();
  }

  void RunTest(const wchar_t* name, bool use_http) {
    std::wstring pages, timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo(L"_ref");
    PrintIOPerfInfo(L"_ref");

    PrintResultList(L"times", L"", L"t_ref", timings, L"ms",
                    true /* important */);
  }
};

}  // namespace

// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
  RunTest(L"moz", false);
}

TEST_F(PageCyclerReferenceTest, MozFile) {
  RunTest(L"moz", false);
}

TEST_F(PageCyclerTest, Intl1File) {
  RunTest(L"intl1", false);
}

TEST_F(PageCyclerReferenceTest, Intl1File) {
  RunTest(L"intl1", false);
}

TEST_F(PageCyclerTest, Intl2File) {
  RunTest(L"intl2", false);
}

TEST_F(PageCyclerReferenceTest, Intl2File) {
  RunTest(L"intl2", false);
}

TEST_F(PageCyclerTest, DomFile) {
  RunTest(L"dom", false);
}

TEST_F(PageCyclerReferenceTest, DomFile) {
  RunTest(L"dom", false);
}

TEST_F(PageCyclerTest, DhtmlFile) {
  RunTest(L"dhtml", false);
}

TEST_F(PageCyclerReferenceTest, DhtmlFile) {
  RunTest(L"dhtml", false);
}

// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
  RunTest(L"moz", true);
}

TEST_F(PageCyclerReferenceTest, MozHttp) {
  RunTest(L"moz", true);
}

TEST_F(PageCyclerTest, Intl1Http) {
  RunTest(L"intl1", true);
}

TEST_F(PageCyclerReferenceTest, Intl1Http) {
  RunTest(L"intl1", true);
}

TEST_F(PageCyclerTest, Intl2Http) {
  RunTest(L"intl2", true);
}

TEST_F(PageCyclerReferenceTest, Intl2Http) {
  RunTest(L"intl2", true);
}

TEST_F(PageCyclerTest, DomHttp) {
  RunTest(L"dom", true);
}

TEST_F(PageCyclerReferenceTest, DomHttp) {
  RunTest(L"dom", true);
}

TEST_F(PageCyclerTest, BloatHttp) {
  RunTest(L"bloat", true);
}

TEST_F(PageCyclerReferenceTest, BloatHttp) {
  RunTest(L"bloat", true);
}

<|endoftext|>


<commit_before><commit_msg>The version of gcc on mac (4.2) doesn't like inheriting from a test in an anonymous namespace.  Just move the actual test cases into the namespace so everything is in the same translation unit.<commit_after><|endoftext|>


<commit_before><commit_msg>Enable new tab test reference builds on Mac now that the reference builds are new enough.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Chrome frame builder redness.<commit_after><|endoftext|>